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 // The checkout has already changed the repository. Persist the matching
302 // draft selection even if the native sheet was dismissed while the
303 // command was in flight; only visible-screen work is focus-gated below.
304 flow.selectBranch(result.value);
305 if (!mountedRef.current || !navigation.isFocused()) {
306 selectingBranchNameRef.current = null;
307 return;
308 }
309 flow.setBranchQuery("");
310 // beforeRemove blocks dismissal while a switch is in flight; this one is ours.
311 allowSelectionNavigationRef.current = true;
312 navigation.goBack();
313 allowSelectionNavigationRef.current = false;
314 selectingBranchNameRef.current = null;
315 };
316
317 return (
318 <BranchPickerScreen
319 title={flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}
320 project={flow.selectedProject}
321 branches={flow.filteredBranches}
322 selectedBranchName={
323 flow.selectedBranchName ??
324 flow.availableBranches.find((branch) => branch.current)?.name ??
325 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
326 null
327 }
328 query={flow.branchQuery}
329 onQueryChange={flow.setBranchQuery}
330 loading={flow.branchesLoading}
331 error={flow.branchesError}
332 refreshing={flow.branchesFetchingNextPage}
333 hasMore={flow.hasMoreBranches}
334 onRefresh={flow.loadBranches}
335 onLoadMore={flow.loadMoreBranches}
336 selectionDisabled={switchingBranchName !== null}
337 onSelect={selectBranch}
338 worktree={
339 flow.workspaceMode === "worktree"
340 ? {
341 startFromOrigin: flow.startFromOrigin,
342 onChangeStartFromOrigin: flow.setStartFromOrigin,
343 }
344 : undefined
345 }
346 />
347 );
348}
349
350export function BranchPickerScreen(props: {
351 readonly title: string;
352 readonly project: EnvironmentProject | null;
353 readonly branches: readonly VcsRef[];
354 readonly selectedBranchName: string | null;
355 readonly query: string;
356 readonly onQueryChange: (query: string) => void;
357 readonly loading: boolean;
358 readonly error: string | null;
359 readonly refreshing: boolean;
360 readonly hasMore: boolean;
361 readonly onRefresh: () => void;
362 readonly onLoadMore: () => void;
363 readonly selectionDisabled?: boolean;
364 readonly onSelect: (branch: VcsRef) => void;
365 readonly worktree?: {
366 readonly startFromOrigin: boolean;
367 readonly onChangeStartFromOrigin: (value: boolean) => void;
368 };
369}) {
370 const searchRef = useRef<import("react-native").TextInputInstance>(null);
371 const navigation = useNavigation();
372 const insets = useSafeAreaInsets();
373 const usesNativeMailSearchToolbar = useNativeMailSearchToolbar();
374 const selectedBranchName =
375 props.selectedBranchName ??
376 props.branches.find((branch) => branch.current)?.name ??
377 props.branches.find((branch) => branch.isDefault)?.name ??
378 null;
379 const branchListContentStyle = {
380 paddingBottom: usesNativeMailSearchToolbar
381 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
382 : Platform.OS === "ios"
383 ? 16
384 : Math.max(insets.bottom, 16) + 16,
385 paddingHorizontal: 16,
386 paddingTop: 16,
387 };
388
389 const renderBranch = ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
390 <SelectionRow
391 icon="arrow.triangle.branch"
392 disabled={props.selectionDisabled ?? false}
393 isFirst={index === 0}
394 isLast={index === props.branches.length - 1}
395 onPress={() => props.onSelect(item)}
396 selected={selectedBranchName === item.name}
397 subtitle={branchBadgeLabel({ branch: item, project: props.project })?.toUpperCase()}
398 title={item.name}
399 />
400 );
401
402 const branchListHeader = props.worktree ? (
403 <View
404 className={cn(
405 "mb-3 overflow-hidden",
406 Platform.OS === "android" ? "rounded-[28px]" : "rounded-2xl",
407 )}
408 >
409 <ToggleRow
410 onValueChange={props.worktree.onChangeStartFromOrigin}
411 title="Start from remote"
412 value={props.worktree.startFromOrigin}
413 />
414 </View>
415 ) : null;
416
417 const branchContent =
418 props.branches.length === 0 ? (
419 <ScrollView
420 className="flex-1 bg-sheet android:bg-sheet-solid"
421 contentInsetAdjustmentBehavior="automatic"
422 contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 16, paddingTop: 16 }}
423 scrollEnabled={false}
424 showsVerticalScrollIndicator={false}
425 >
426 {branchListHeader}
427 <View
428 className="flex-1 items-center justify-center gap-3 px-4"
429 style={{
430 marginBottom: usesNativeMailSearchToolbar
431 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET
432 : 0,
433 }}
434 >
435 {props.loading ? <AppActivityIndicator /> : null}
436 <Text className="text-center text-sm text-foreground-muted">
437 {props.loading
438 ? "Loading branches…"
439 : props.error
440 ? props.error
441 : props.query
442 ? "No matching branches"
443 : "No branches available"}
444 </Text>
445 {!props.loading && props.error ? (
446 <View className="self-center">
447 <Button label="Try again" tone="secondary" onPress={props.onRefresh} />
448 </View>
449 ) : null}
450 </View>
451 </ScrollView>
452 ) : (
453 <LegendList
454 alwaysBounceVertical={false}
455 automaticallyAdjustsScrollIndicatorInsets
456 automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
457 className="flex-1 bg-sheet android:bg-sheet-solid"
458 contentInsetAdjustmentBehavior="automatic"
459 contentContainerStyle={branchListContentStyle}
460 data={props.branches}
461 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
462 keyboardShouldPersistTaps="handled"
463 keyExtractor={(branch) =>
464 `${branch.remoteName ?? "local"}:${branch.name}:${branch.worktreePath ?? ""}`
465 }
466 ListHeaderComponent={branchListHeader}
467 ListFooterComponent={
468 props.refreshing ? (
469 <View className="items-center py-4">
470 <AppActivityIndicator />
471 </View>
472 ) : null
473 }
474 onEndReached={props.hasMore ? props.onLoadMore : undefined}
475 onEndReachedThreshold={0.35}
476 renderItem={renderBranch}
477 showsVerticalScrollIndicator={false}
478 />
479 );
480
481 if (Platform.OS === "android") {
482 return (
483 <View className="flex-1 bg-sheet" collapsable={false}>
484 <NativeStackScreenOptions options={{ headerShown: false }} />
485 <AndroidScreenHeader
486 title={props.title}
487 hideBottomBorder
488 onBack={() => navigation.goBack()}
489 />
490 <View className="bg-header px-4 pb-3 pt-1">
491 <SearchField
492 inputRef={searchRef}
493 autoFocus={false}
494 accessibilityLabel="Find a branch"
495 clearAccessibilityLabel="Clear branch search"
496 onChangeText={props.onQueryChange}
497 placeholder="Find a branch"
498 value={props.query}
499 />
500 </View>
501 <ScreenContent>{branchContent}</ScreenContent>
502 </View>
503 );
504 }
505
506 return (
507 <>
508 <NativeStackScreenOptions
509 options={{
510 headerShown: true,
511 title: props.title,
512 unstable_headerToolbarItems: usesNativeMailSearchToolbar
513 ? () => [
514 createNativeMailSearchToolbarItem({
515 onSearchTextChange: props.onQueryChange,
516 placeholder: "Find a branch",
517 searchTextChangeId: "new-task-branch-search-text",
518 showsSearchDismissButton: true,
519 }),
520 ]
521 : undefined,
522 headerSearchBarOptions: usesNativeMailSearchToolbar
523 ? undefined
524 : {
525 allowToolbarIntegration: true,
526 autoCapitalize: "none",
527 hideNavigationBar: false,
528 obscureBackground: false,
529 placeholder: "Find a branch",
530 onChangeText: (event) => {
531 props.onQueryChange(event.nativeEvent.text);
532 },
533 onCancelButtonPress: () => {
534 props.onQueryChange("");
535 },
536 },
537 }}
538 />
539 {usesNativeMailSearchToolbar ? null : (
540 <Toolbar placement="bottom">
541 <Toolbar.SearchBarSlot />
542 </Toolbar>
543 )}
544 {branchContent}
545 </>
546 );
547}