Open History to see the last commit
1import { SearchField } from "../../components/ui/SearchField";
2import { Button } from "../../components/ui/Button";
3import { Toolbar } from "../../components/ui/Toolbar";
4import * as Dialog from "../../components/ui/Dialog";
5import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
6import { SelectionRow } from "../../components/ui/SelectionRow";
7import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
8import { shouldCheckoutNewTaskBranch } from "./new-task-context-presentation";
9import type { VcsRef } from "@t3tools/client-runtime/state/vcs";
10import {
11 AuthSourceControlWriteScope,
12 resolveEnvironmentMachineKind,
13 type EnvironmentId,
14} from "@t3tools/contracts";
15import { LegendList } from "@legendapp/list/react-native";
16import {
17 isAtomCommandInterrupted,
18 squashAtomCommandFailure,
19} from "@t3tools/client-runtime/state/runtime";
20import * as Haptics from "expo-haptics";
21import { useNavigation } from "@react-navigation/native";
22import { useEffect, useRef, useState, type ReactNode } from "react";
23import { Platform, Pressable, ScrollView, View } from "react-native";
24import { useSafeAreaInsets } from "react-native-safe-area-context";
25
26import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
27import { ScreenContent } from "../../components/ui/ScreenContent";
28import { SymbolView } from "../../components/ui/AppSymbol";
29import { AppText as Text } from "../../components/ui/AppText";
30import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
31import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
32import { cn } from "../../lib/cn";
33import { NativeStackScreenOptions } from "../../native/StackHeader";
34import { useEnvironmentScope } from "../../state/session";
35import { useAtomCommand } from "../../state/use-atom-command";
36import { vcsEnvironment } from "../../state/vcs";
37import {
38 createNativeMailSearchToolbarItem,
39 NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET,
40} from "../layout/native-mail-search-toolbar";
41import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-toolbar";
42import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
43import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
44
45import { useEnvironmentPresentation } from "../../state/presentation";
46import { useRemoteConnections } from "../../state/use-remote-environment-registry";
47import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
48import {
49 ConnectionDiagnosisDetails,
50 useConnectionDiagnosis,
51} from "../connection/ConnectionDiagnosisDetails";
52import { environmentStatusText } from "../connection/environmentStatusText";
53
54function EnvironmentPickerRow(props: {
55 environmentId: EnvironmentId;
56 title: string;
57 selected: boolean;
58 disabled: boolean;
59 isLast: boolean;
60 onPress: () => void;
61}) {
62 const [expanded, setExpanded] = useState(false);
63 const { presentation } = useEnvironmentPresentation(props.environmentId);
64 const { diagnosis, state } = useConnectionDiagnosis(props.environmentId, presentation);
65 const { onReconnectEnvironment } = useRemoteConnections();
66 const connection = presentation?.connection;
67 const status =
68 diagnosis?.headline ??
69 (connection ? environmentStatusText({ ...connection, error: null }) : "Offline");
70 return (
71 <View className={cn("bg-grouped-card", !props.isLast && "border-b border-border-subtle")}>
72 <View className="flex-row items-center">
73 <Pressable
74 accessibilityRole="radio"
75 accessibilityLabel={`${props.title}, ${status}`}
76 accessibilityState={{ checked: props.selected }}
77 disabled={props.disabled}
78 onPress={props.onPress}
79 className="min-h-16 flex-1 flex-row items-center gap-3 px-4 py-3 active:bg-subtle"
80 >
81 <EnvironmentMachineSymbol
82 kind={resolveEnvironmentMachineKind(presentation?.serverConfig ?? null)}
83 size={20}
84 tintColorClassName="accent-icon-muted"
85 />
86 <View className="min-w-0 flex-1 gap-1">
87 <Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>
88 {props.title}
89 </Text>
90 <View className="flex-row items-center gap-1.5">
91 <ConnectionStatusDot state={connection?.phase ?? "offline"} pulse={false} size={6} />
92 <Text className="shrink text-xs text-foreground-muted" numberOfLines={2}>
93 {status}
94 </Text>
95 </View>
96 </View>
97 {props.selected ? (
98 <SymbolView name="checkmark" size={16} tintColorClassName="accent-icon" />
99 ) : null}
100 </Pressable>
101 <Pressable
102 accessibilityRole="button"
103 accessibilityLabel={`${expanded ? "Hide" : "Show"} connection details for ${props.title}`}
104 accessibilityState={{ expanded }}
105 onPress={() => setExpanded(!expanded)}
106 className="min-h-11 min-w-11 items-center justify-center active:opacity-65"
107 >
108 <SymbolView
109 name={expanded ? "chevron.up" : "chevron.down"}
110 size={13}
111 tintColorClassName="accent-icon-muted"
112 />
113 </Pressable>
114 </View>
115 {expanded ? (
116 <View className="gap-3 px-4 pb-4">
117 {diagnosis ? (
118 <ConnectionDiagnosisDetails hostLabel={props.title} diagnosis={diagnosis} />
119 ) : (
120 <Text className="text-sm text-foreground-muted">{status}</Text>
121 )}
122 {state.retryAt ? (
123 <Text className="text-sm text-foreground-muted">
124 Next reconnect at {new Date(state.retryAt).toLocaleTimeString()}
125 </Text>
126 ) : null}
127 {connection?.phase !== "connected" ? (
128 <Button
129 label="Reconnect now"
130 onPress={() => onReconnectEnvironment(props.environmentId)}
131 />
132 ) : null}
133 </View>
134 ) : null}
135 </View>
136 );
137}
138
139function ToggleRow(props: {
140 readonly title: string;
141 readonly value: boolean;
142 readonly onValueChange: (value: boolean) => void;
143}) {
144 return (
145 <View className="min-h-14 flex-row items-center gap-3 bg-grouped-card px-4 py-3">
146 <Text
147 className={cn(
148 "min-w-0 flex-1 text-base text-foreground",
149 Platform.OS !== "android" && "font-t3-medium",
150 )}
151 numberOfLines={1}
152 >
153 {props.title}
154 </Text>
155 <ThemedSwitch
156 accessibilityLabel={props.title}
157 onValueChange={props.onValueChange}
158 value={props.value}
159 />
160 </View>
161 );
162}
163
164function PickerSurface(props: { readonly children: ReactNode }) {
165 return (
166 <View
167 className={
168 Platform.OS === "android"
169 ? "overflow-hidden rounded-[28px] bg-grouped-card"
170 : "overflow-hidden rounded-2xl bg-grouped-card"
171 }
172 >
173 {props.children}
174 </View>
175 );
176}
177
178export function NewTaskEnvironmentPickerRouteScreen() {
179 const flow = useNewTaskFlow();
180 const navigation = useNavigation();
181 const insets = useSafeAreaInsets();
182 return (
183 <View className="flex-1 bg-sheet" collapsable={false}>
184 <NativeStackScreenOptions
185 options={{
186 headerShown: Platform.OS !== "android",
187 title: "Environment",
188 }}
189 />
190 {Platform.OS === "android" ? (
191 <AndroidScreenHeader
192 title="Environment"
193 hideBottomBorder
194 onBack={() => navigation.goBack()}
195 />
196 ) : null}
197 <ScreenContent>
198 <ScrollView
199 contentInsetAdjustmentBehavior="automatic"
200 contentContainerStyle={{
201 paddingBottom: Math.max(insets.bottom, 16) + 16,
202 paddingHorizontal: 16,
203 paddingTop: 16,
204 }}
205 showsVerticalScrollIndicator={false}
206 >
207 <PickerSurface>
208 {flow.environments.map((environment, index) => (
209 <EnvironmentPickerRow
210 key={String(environment.environmentId)}
211 environmentId={environment.environmentId}
212 isLast={index === flow.environments.length - 1}
213 disabled={flow.switchingToEnvironmentId !== null}
214 onPress={() => {
215 void Haptics.selectionAsync();
216 void flow.switchEnvironment(environment.environmentId).then((switched) => {
217 if (switched) navigation.goBack();
218 });
219 }}
220 selected={flow.selectedEnvironmentId === environment.environmentId}
221 title={environment.environmentLabel}
222 />
223 ))}
224 </PickerSurface>
225 </ScrollView>
226 </ScreenContent>
227 </View>
228 );
229}
230
231export function NewTaskBranchPickerRouteScreen() {
232 const flow = useNewTaskFlow();
233 const canWriteSourceControl = useEnvironmentScope(
234 flow.selectedProject?.environmentId ?? null,
235 AuthSourceControlWriteScope,
236 );
237 const navigation = useNavigation();
238 const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false });
239 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
240 const [switchingBranchName, setSwitchingBranchName] = useState<string | null>(null);
241 const selectingBranchNameRef = useRef<string | null>(null);
242 const allowSelectionNavigationRef = useRef(false);
243 const mountedRef = useRef(true);
244
245 useEffect(() => {
246 mountedRef.current = true;
247 return () => {
248 mountedRef.current = false;
249 flow.setBranchQuery("");
250 };
251 }, [flow.setBranchQuery]);
252
253 useEffect(
254 () =>
255 navigation.addListener("beforeRemove", (event) => {
256 if (selectingBranchNameRef.current !== null && !allowSelectionNavigationRef.current) {
257 event.preventDefault();
258 }
259 }),
260 [navigation],
261 );
262
263 const selectBranch = async (branch: VcsRef) => {
264 const needsCheckout = shouldCheckoutNewTaskBranch({
265 branchIsCurrent: branch.current,
266 branchWorktreePath: branch.worktreePath,
267 workspaceMode: flow.workspaceMode,
268 });
269 if (selectingBranchNameRef.current !== null || (needsCheckout && !canWriteSourceControl)) {
270 return;
271 }
272 selectingBranchNameRef.current = branch.name;
273 void Haptics.selectionAsync();
274
275 const project = flow.selectedProject;
276 if (!project) {
277 selectingBranchNameRef.current = null;
278 return;
279 }
280 setSwitchingBranchName(branch.name);
281 const result = await checkoutNewTaskBranch({
282 branch,
283 project,
284 workspaceMode: flow.workspaceMode,
285 readRefs,
286 switchRef,
287 });
288 if (mountedRef.current) setSwitchingBranchName(null);
289 if (result._tag === "Failure") {
290 selectingBranchNameRef.current = null;
291 if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
292 const error = squashAtomCommandFailure(result);
293 Dialog.alert(
294 "Could not switch branch",
295 error instanceof Error ? error.message : "The branch could not be checked out.",
296 );
297 }
298 return;
299 }
300
301 // Checkout already changed Git; persist the draft selection even if the sheet dismissed mid-command.
302 flow.selectBranch(result.value);
303 if (!mountedRef.current || !navigation.isFocused()) {
304 selectingBranchNameRef.current = null;
305 return;
306 }
307 flow.setBranchQuery("");
308 // beforeRemove blocks dismissal while a switch is in flight; this one is ours.
309 allowSelectionNavigationRef.current = true;
310 navigation.goBack();
311 allowSelectionNavigationRef.current = false;
312 selectingBranchNameRef.current = null;
313 };
314
315 return (
316 <BranchPickerScreen
317 title={flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}
318 project={flow.selectedProject}
319 branches={flow.filteredBranches}
320 selectedBranchName={
321 flow.selectedBranchName ??
322 flow.availableBranches.find((branch) => branch.current)?.name ??
323 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
324 null
325 }
326 query={flow.branchQuery}
327 onQueryChange={flow.setBranchQuery}
328 loading={flow.branchesLoading}
329 error={flow.branchesError}
330 refreshing={flow.branchesFetchingNextPage}
331 hasMore={flow.hasMoreBranches}
332 onRefresh={flow.loadBranches}
333 onLoadMore={flow.loadMoreBranches}
334 selectionDisabled={switchingBranchName !== null}
335 onSelect={selectBranch}
336 worktree={
337 flow.workspaceMode === "worktree"
338 ? {
339 startFromOrigin: flow.startFromOrigin,
340 onChangeStartFromOrigin: flow.setStartFromOrigin,
341 }
342 : undefined
343 }
344 />
345 );
346}
347
348export function BranchPickerScreen(props: {
349 readonly title: string;
350 readonly project: EnvironmentProject | null;
351 readonly branches: readonly VcsRef[];
352 readonly selectedBranchName: string | null;
353 readonly query: string;
354 readonly onQueryChange: (query: string) => void;
355 readonly loading: boolean;
356 readonly error: string | null;
357 readonly refreshing: boolean;
358 readonly hasMore: boolean;
359 readonly onRefresh: () => void;
360 readonly onLoadMore: () => void;
361 readonly selectionDisabled?: boolean;
362 readonly onSelect: (branch: VcsRef) => void;
363 readonly worktree?: {
364 readonly startFromOrigin: boolean;
365 readonly onChangeStartFromOrigin: (value: boolean) => void;
366 };
367}) {
368 const searchRef = useRef<import("react-native").TextInputInstance>(null);
369 const navigation = useNavigation();
370 const insets = useSafeAreaInsets();
371 const usesNativeMailSearchToolbar = useNativeMailSearchToolbar();
372 const selectedBranchName =
373 props.selectedBranchName ??
374 props.branches.find((branch) => branch.current)?.name ??
375 props.branches.find((branch) => branch.isDefault)?.name ??
376 null;
377 const branchListContentStyle = {
378 paddingBottom: usesNativeMailSearchToolbar
379 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
380 : Platform.OS === "ios"
381 ? 16
382 : Math.max(insets.bottom, 16) + 16,
383 paddingHorizontal: 16,
384 paddingTop: 16,
385 };
386
387 const renderBranch = ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
388 <SelectionRow
389 icon="arrow.triangle.branch"
390 disabled={props.selectionDisabled ?? false}
391 isFirst={index === 0}
392 isLast={index === props.branches.length - 1}
393 onPress={() => props.onSelect(item)}
394 selected={selectedBranchName === item.name}
395 subtitle={branchBadgeLabel({ branch: item, project: props.project })?.toUpperCase()}
396 title={item.name}
397 />
398 );
399
400 const branchListHeader = props.worktree ? (
401 <View
402 className={cn(
403 "mb-3 overflow-hidden",
404 Platform.OS === "android" ? "rounded-[28px]" : "rounded-2xl",
405 )}
406 >
407 <ToggleRow
408 onValueChange={props.worktree.onChangeStartFromOrigin}
409 title="Start from remote"
410 value={props.worktree.startFromOrigin}
411 />
412 </View>
413 ) : null;
414
415 const branchContent =
416 props.branches.length === 0 ? (
417 <ScrollView
418 className="flex-1 bg-sheet android:bg-sheet-solid"
419 contentInsetAdjustmentBehavior="automatic"
420 contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 16, paddingTop: 16 }}
421 scrollEnabled={false}
422 showsVerticalScrollIndicator={false}
423 >
424 {branchListHeader}
425 <View
426 className="flex-1 items-center justify-center gap-3 px-4"
427 style={{
428 marginBottom: usesNativeMailSearchToolbar
429 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET
430 : 0,
431 }}
432 >
433 {props.loading ? <AppActivityIndicator /> : null}
434 <Text className="text-center text-sm text-foreground-muted">
435 {props.loading
436 ? "Loading branches…"
437 : props.error
438 ? props.error
439 : props.query
440 ? "No matching branches"
441 : "No branches available"}
442 </Text>
443 {!props.loading && props.error ? (
444 <View className="self-center">
445 <Button label="Try again" tone="secondary" onPress={props.onRefresh} />
446 </View>
447 ) : null}
448 </View>
449 </ScrollView>
450 ) : (
451 <LegendList
452 alwaysBounceVertical={false}
453 automaticallyAdjustsScrollIndicatorInsets
454 automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
455 className="flex-1 bg-sheet android:bg-sheet-solid"
456 contentInsetAdjustmentBehavior="automatic"
457 contentContainerStyle={branchListContentStyle}
458 data={props.branches}
459 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
460 keyboardShouldPersistTaps="handled"
461 keyExtractor={(branch) =>
462 `${branch.remoteName ?? "local"}:${branch.name}:${branch.worktreePath ?? ""}`
463 }
464 ListHeaderComponent={branchListHeader}
465 ListFooterComponent={
466 props.refreshing ? (
467 <View className="items-center py-4">
468 <AppActivityIndicator />
469 </View>
470 ) : null
471 }
472 onEndReached={props.hasMore ? props.onLoadMore : undefined}
473 onEndReachedThreshold={0.35}
474 renderItem={renderBranch}
475 showsVerticalScrollIndicator={false}
476 />
477 );
478
479 if (Platform.OS === "android") {
480 return (
481 <View className="flex-1 bg-sheet" collapsable={false}>
482 <NativeStackScreenOptions options={{ headerShown: false }} />
483 <AndroidScreenHeader
484 title={props.title}
485 hideBottomBorder
486 onBack={() => navigation.goBack()}
487 />
488 <View className="bg-header px-4 pb-3 pt-1">
489 <SearchField
490 inputRef={searchRef}
491 autoFocus={false}
492 accessibilityLabel="Find a branch"
493 clearAccessibilityLabel="Clear branch search"
494 onChangeText={props.onQueryChange}
495 placeholder="Find a branch"
496 value={props.query}
497 />
498 </View>
499 <ScreenContent>{branchContent}</ScreenContent>
500 </View>
501 );
502 }
503
504 return (
505 <>
506 <NativeStackScreenOptions
507 options={{
508 headerShown: true,
509 title: props.title,
510 unstable_headerToolbarItems: usesNativeMailSearchToolbar
511 ? () => [
512 createNativeMailSearchToolbarItem({
513 onSearchTextChange: props.onQueryChange,
514 placeholder: "Find a branch",
515 searchTextChangeId: "new-task-branch-search-text",
516 showsSearchDismissButton: true,
517 }),
518 ]
519 : undefined,
520 headerSearchBarOptions: usesNativeMailSearchToolbar
521 ? undefined
522 : {
523 allowToolbarIntegration: true,
524 autoCapitalize: "none",
525 hideNavigationBar: false,
526 obscureBackground: false,
527 placeholder: "Find a branch",
528 onChangeText: (event) => {
529 props.onQueryChange(event.nativeEvent.text);
530 },
531 onCancelButtonPress: () => {
532 props.onQueryChange("");
533 },
534 },
535 }}
536 />
537 {usesNativeMailSearchToolbar ? null : (
538 <Toolbar placement="bottom">
539 <Toolbar.SearchBarSlot />
540 </Toolbar>
541 )}
542 {branchContent}
543 </>
544 );
545}