Open History to see the last commit
1import { NativeScrollView } from "../../native/NativeScrollViewMarker";
2import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3import { Button } from "../../components/ui/Button";
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 { T, useGT, useMessages, Var } from "gt-react-native";
23import { m } from "../../i18n/messages";
24import { useRef, useState, type ReactNode } from "react";
25import { sanitizeNewRefName } from "@t3tools/shared/git";
26import { Platform, Pressable, ScrollView, View } from "react-native";
27import { useSafeAreaInsets } from "react-native-safe-area-context";
28
29import { AppBar } from "../../components/ui/AppBar";
30import { ScreenContent } from "../../components/ui/ScreenContent";
31import { SymbolView } from "../../components/ui/AppSymbol";
32import { AppText as Text } from "../../components/ui/AppText";
33import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
34import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
35import { cn } from "../../lib/cn";
36import { useEnvironmentScope } from "../../state/session";
37import { useAtomCommand } from "../../state/use-atom-command";
38import { vcsEnvironment } from "../../state/vcs";
39import { useRefreshBranchesOnFocus } from "./use-refresh-branches-on-focus";
40import { useSearchToolbarInset } from "../../components/ui/useBarInset";
41import type { AppBarSearch } from "../../components/ui/AppBar";
42import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
43import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
44import { filterNewTaskBranches } from "./new-task-context-presentation";
45import { useDebouncedValue, usePaginatedBranches } from "../../state/queries";
46import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
47
48import { useEnvironmentPresentation } from "../../state/presentation";
49import { useRemoteConnections } from "../../state/use-remote-environment-registry";
50import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
51import {
52 ConnectionDiagnosisDetails,
53 useConnectionDiagnosis,
54} from "../connection/ConnectionDiagnosisDetails";
55import { environmentStatusText } from "../connection/environmentStatusText";
56
57const BRANCH_SEARCH_DEBOUNCE_MS = 150;
58
59function EnvironmentPickerRow(props: {
60 environmentId: EnvironmentId;
61 title: string;
62 selected: boolean;
63 disabled: boolean;
64 isLast: boolean;
65 onPress: () => void;
66}) {
67 const gt = useGT();
68 const messages = useMessages();
69 const [expanded, setExpanded] = useState(false);
70 const { presentation } = useEnvironmentPresentation(props.environmentId);
71 const { diagnosis, state } = useConnectionDiagnosis(props.environmentId, presentation);
72 const { onReconnectEnvironment } = useRemoteConnections();
73 const connection = presentation?.connection;
74 const status =
75 diagnosis?.headline ??
76 (connection ? environmentStatusText({ ...connection, error: null }, messages) : gt("Offline"));
77 return (
78 <View className={cn("bg-grouped-card", !props.isLast && "border-b border-border-subtle")}>
79 <View className="flex-row items-center">
80 <Pressable
81 accessibilityRole="radio"
82 accessibilityLabel={`${props.title}, ${status}`}
83 accessibilityState={{ checked: props.selected }}
84 disabled={props.disabled}
85 onPress={props.onPress}
86 className="min-h-16 flex-1 flex-row items-center gap-3 px-4 py-3 active:bg-subtle"
87 >
88 <EnvironmentMachineSymbol
89 kind={resolveEnvironmentMachineKind(presentation?.serverConfig ?? null)}
90 size={20}
91 tintColorClassName="accent-icon-muted"
92 />
93 <View className="min-w-0 flex-1 gap-1">
94 <Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>
95 {props.title}
96 </Text>
97 <View className="flex-row items-center gap-1.5">
98 <ConnectionStatusDot state={connection?.phase ?? "offline"} pulse={false} size={6} />
99 <Text className="shrink text-xs text-foreground-muted" numberOfLines={2}>
100 {status}
101 </Text>
102 </View>
103 </View>
104 {props.selected ? (
105 <SymbolView name="checkmark" size={16} tintColorClassName="accent-icon" />
106 ) : null}
107 </Pressable>
108 <Pressable
109 accessibilityRole="button"
110 accessibilityLabel={
111 expanded
112 ? gt("Hide connection details for {title}", { title: props.title })
113 : gt("Show connection details for {title}", { title: props.title })
114 }
115 accessibilityState={{ expanded }}
116 onPress={() => setExpanded(!expanded)}
117 className="min-h-11 min-w-11 items-center justify-center active:opacity-65"
118 >
119 <SymbolView
120 name={expanded ? "chevron.up" : "chevron.down"}
121 size={13}
122 tintColorClassName="accent-icon-muted"
123 />
124 </Pressable>
125 </View>
126 {expanded ? (
127 <View className="gap-3 px-4 pb-4">
128 {diagnosis ? (
129 <ConnectionDiagnosisDetails hostLabel={props.title} diagnosis={diagnosis} />
130 ) : (
131 <Text className="text-sm text-foreground-muted">{status}</Text>
132 )}
133 {state.retryAt ? (
134 <Text className="text-sm text-foreground-muted">
135 <T>
136 Next reconnect at <Var>{new Date(state.retryAt).toLocaleTimeString()}</Var>
137 </T>
138 </Text>
139 ) : null}
140 {connection?.phase !== "connected" ? (
141 <Button
142 label={gt("Reconnect now")}
143 onPress={() => onReconnectEnvironment(props.environmentId)}
144 />
145 ) : null}
146 </View>
147 ) : null}
148 </View>
149 );
150}
151
152function ToggleRow(props: {
153 readonly title: string;
154 readonly value: boolean;
155 readonly onValueChange: (value: boolean) => void;
156}) {
157 return (
158 <View className="min-h-14 flex-row items-center gap-3 bg-grouped-card px-4 py-3">
159 <Text
160 className={cn(
161 "min-w-0 flex-1 text-base text-foreground",
162 Platform.OS !== "android" && "font-t3-medium",
163 )}
164 numberOfLines={1}
165 >
166 {props.title}
167 </Text>
168 <ThemedSwitch
169 accessibilityLabel={props.title}
170 onValueChange={props.onValueChange}
171 value={props.value}
172 />
173 </View>
174 );
175}
176
177function PickerSurface(props: { readonly children: ReactNode }) {
178 return (
179 <View
180 className={
181 Platform.OS === "android"
182 ? "overflow-hidden rounded-[28px] bg-grouped-card"
183 : "overflow-hidden rounded-2xl bg-grouped-card"
184 }
185 >
186 {props.children}
187 </View>
188 );
189}
190
191export function NewTaskEnvironmentPickerRouteScreen() {
192 const gt = useGT();
193 const flow = useNewTaskFlow();
194 const navigation = useNavigation();
195 const insets = useSafeAreaInsets();
196 return (
197 <View className="flex-1 bg-sheet" collapsable={false}>
198 <AppBar title={gt("Environment")} hideBottomBorder onBack={() => navigation.goBack()} />
199 <ScreenContent>
200 <ScrollView
201 contentInsetAdjustmentBehavior="automatic"
202 contentContainerStyle={{
203 paddingBottom: Math.max(insets.bottom, 16) + 16,
204 paddingHorizontal: 16,
205 paddingTop: 16,
206 }}
207 showsVerticalScrollIndicator={false}
208 >
209 <PickerSurface>
210 {flow.environments.map((environment, index) => (
211 <EnvironmentPickerRow
212 key={String(environment.environmentId)}
213 environmentId={environment.environmentId}
214 isLast={index === flow.environments.length - 1}
215 disabled={flow.switchingToEnvironmentId !== null}
216 onPress={() => {
217 void Haptics.selectionAsync();
218 void flow.switchEnvironment(environment.environmentId).then((switched) => {
219 if (switched) navigation.goBack();
220 });
221 }}
222 selected={flow.selectedEnvironmentId === environment.environmentId}
223 title={environment.environmentLabel}
224 />
225 ))}
226 </PickerSurface>
227 </ScrollView>
228 </ScreenContent>
229 </View>
230 );
231}
232
233export function NewTaskBranchPickerRouteScreen() {
234 const gt = useGT();
235 const flow = useNewTaskFlow();
236 const canWriteSourceControl = useEnvironmentScope(
237 flow.selectedProject?.environmentId ?? null,
238 AuthSourceControlWriteScope,
239 );
240 const navigation = useNavigation();
241 const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false });
242 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
243 const [switchingBranchName, setSwitchingBranchName] = useState<string | null>(null);
244 const selectingBranchNameRef = useRef<string | null>(null);
245 const [branchQuery, setBranchQuery] = useState("");
246 const branchSearchQuery = sanitizeNewRefName(branchQuery);
247 const debouncedBranchQuery = useDebouncedValue(branchSearchQuery, BRANCH_SEARCH_DEBOUNCE_MS);
248 const branchState = usePaginatedBranches({
249 environmentId: flow.selectedProject?.environmentId ?? null,
250 cwd: flow.selectedProject?.workspaceRoot || null,
251 query: debouncedBranchQuery,
252 });
253 const branchesLoading =
254 branchSearchQuery !== debouncedBranchQuery ||
255 (branchState.isPending && branchState.data === null);
256 const refreshBranches = () => {
257 if (!flow.selectedProject) return;
258 setPendingConnectionError(null);
259 branchState.refresh();
260 };
261
262 const selectBranch = async (branch: VcsRef) => {
263 const needsCheckout = shouldCheckoutNewTaskBranch({
264 branchIsCurrent: branch.current,
265 branchWorktreePath: branch.worktreePath,
266 workspaceMode: flow.workspaceMode,
267 });
268 if (selectingBranchNameRef.current !== null || (needsCheckout && !canWriteSourceControl)) {
269 return;
270 }
271 selectingBranchNameRef.current = branch.name;
272 void Haptics.selectionAsync();
273
274 const project = flow.selectedProject;
275 if (!project) {
276 selectingBranchNameRef.current = null;
277 return;
278 }
279 setSwitchingBranchName(branch.name);
280 // The guard belongs to this checkout: back actions are refused while it is
281 // in flight, and our own goBack runs after it is lifted.
282 const releaseRemovalGuard = navigation.addListener("beforeRemove", (event) => {
283 event.preventDefault();
284 });
285 const result = await checkoutNewTaskBranch({
286 branch,
287 project,
288 workspaceMode: flow.workspaceMode,
289 readRefs,
290 switchRef,
291 }).finally(releaseRemovalGuard);
292 setSwitchingBranchName(null);
293 if (result._tag === "Failure") {
294 selectingBranchNameRef.current = null;
295 if (navigation.isFocused() && !isAtomCommandInterrupted(result)) {
296 const error = squashAtomCommandFailure(result);
297 Dialog.alert(
298 gt("Could not switch branch"),
299 errorDisplayMessage(error, m) ?? gt("The branch could not be checked out."),
300 );
301 }
302 return;
303 }
304
305 // Checkout already changed Git; persist the draft selection even if the sheet dismissed mid-command.
306 flow.selectBranch(result.value);
307 if (!navigation.isFocused()) {
308 selectingBranchNameRef.current = null;
309 return;
310 }
311 navigation.goBack();
312 selectingBranchNameRef.current = null;
313 };
314
315 return (
316 <BranchPickerScreen
317 title={flow.workspaceMode === "worktree" ? gt("Base branch") : gt("Branch")}
318 project={flow.selectedProject}
319 branches={filterNewTaskBranches(branchState.refs, branchQuery)}
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={branchQuery}
327 onQueryChange={setBranchQuery}
328 loading={branchesLoading}
329 error={branchState.error}
330 refreshing={branchState.isFetchingNextPage}
331 hasMore={branchState.data?.nextCursor !== null && branchState.data?.nextCursor !== undefined}
332 onRefresh={refreshBranches}
333 onLoadMore={branchState.loadNext}
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 NewTaskRepositoriesPickerRouteScreen() {
349 const gt = useGT();
350 const flow = useNewTaskFlow();
351 const navigation = useNavigation();
352 const insets = useSafeAreaInsets();
353 const choices = flow.worktreeRepositoryChoices;
354 const selection = flow.worktreeRepositorySelection;
355 const selected = new Set(selection.selected);
356 const toggle = (repositoryPath: string) => {
357 if (choices === null) return;
358 void Haptics.selectionAsync();
359 flow.setWorktreeRepositories(
360 choices.flatMap((choice) =>
361 (choice.repositoryPath === repositoryPath) !== selected.has(choice.repositoryPath)
362 ? [choice.repositoryPath]
363 : [],
364 ),
365 );
366 };
367 const header =
368 choices === null || choices.length === 0 ? null : (
369 <View className="gap-3 pb-3">
370 <Text textRole="footnote" className="px-1 text-foreground-muted">
371 {selection.needsChoice
372 ? gt("Choose the repositories this thread works on.")
373 : gt("Each gets its own worktree on the thread's branch.")}
374 </Text>
375 <View className="flex-row gap-2">
376 <Button
377 label={gt("Select all")}
378 size="compact"
379 disabled={selected.size === choices.length}
380 onPress={() =>
381 flow.setWorktreeRepositories(choices.map((choice) => choice.repositoryPath))
382 }
383 />
384 <Button
385 label={gt("Select none")}
386 size="compact"
387 disabled={!selection.needsChoice && selected.size === 0}
388 onPress={() => flow.setWorktreeRepositories([])}
389 />
390 </View>
391 </View>
392 );
393 return (
394 <View className="flex-1 bg-sheet" collapsable={false}>
395 <AppBar title={gt("Repositories")} hideBottomBorder onBack={() => navigation.goBack()} />
396 <ScreenContent>
397 {choices === null || choices.length === 0 ? (
398 <View className="flex-1 items-center justify-center gap-3 px-4">
399 {choices === null ? <AppActivityIndicator /> : null}
400 <Text className="text-center text-sm text-foreground-muted">
401 {choices === null
402 ? gt("Loading repositories…")
403 : gt("This project tracks no repositories")}
404 </Text>
405 </View>
406 ) : (
407 <LegendList
408 renderScrollComponent={NativeScrollView}
409 alwaysBounceVertical={false}
410 automaticallyAdjustsScrollIndicatorInsets
411 className="flex-1 bg-sheet android:bg-sheet-solid"
412 contentInsetAdjustmentBehavior="automatic"
413 contentContainerStyle={{
414 paddingBottom: Math.max(insets.bottom, 16) + 16,
415 paddingHorizontal: 16,
416 paddingTop: 16,
417 }}
418 data={choices}
419 extraData={selection.selected}
420 keyExtractor={(choice) => choice.repositoryPath}
421 ListHeaderComponent={header}
422 renderItem={({ item, index }) => (
423 <SelectionRow
424 icon="folder"
425 role="checkbox"
426 isFirst={index === 0}
427 isLast={index === choices.length - 1}
428 onPress={() => toggle(item.repositoryPath)}
429 selected={selected.has(item.repositoryPath)}
430 subtitle={
431 item.relativePath !== undefined && item.relativePath !== item.name
432 ? item.relativePath
433 : undefined
434 }
435 title={item.name}
436 />
437 )}
438 showsVerticalScrollIndicator={false}
439 />
440 )}
441 </ScreenContent>
442 </View>
443 );
444}
445
446export function BranchPickerScreen(props: {
447 readonly title: string;
448 readonly project: EnvironmentProject | null;
449 readonly branches: readonly VcsRef[];
450 readonly selectedBranchName: string | null;
451 readonly query: string;
452 readonly onQueryChange: (query: string) => void;
453 readonly loading: boolean;
454 readonly error: string | null;
455 readonly refreshing: boolean;
456 readonly hasMore: boolean;
457 readonly onRefresh: () => void;
458 readonly onLoadMore: () => void;
459 readonly selectionDisabled?: boolean;
460 readonly onSelect: (branch: VcsRef) => void;
461 readonly worktree?: {
462 readonly startFromOrigin: boolean;
463 readonly onChangeStartFromOrigin: (value: boolean) => void;
464 };
465}) {
466 const gt = useGT();
467 const m = useMessages();
468 const navigation = useNavigation();
469 const insets = useSafeAreaInsets();
470 useRefreshBranchesOnFocus(props.project?.environmentId, props.project?.workspaceRoot);
471 const search: AppBarSearch = {
472 value: props.query,
473 onChangeText: props.onQueryChange,
474 placeholder: gt("Find a branch"),
475 clearAccessibilityLabel: gt("Clear branch search"),
476 mode: "inline",
477 compactToolbar: true,
478 };
479 const searchToolbarInset = useSearchToolbarInset(search);
480 const selectedBranchName =
481 props.selectedBranchName ??
482 props.branches.find((branch) => branch.current)?.name ??
483 props.branches.find((branch) => branch.isDefault)?.name ??
484 null;
485 const branchListContentStyle = {
486 paddingBottom: searchToolbarInset
487 ? searchToolbarInset + 16
488 : Platform.OS === "ios"
489 ? 16
490 : Math.max(insets.bottom, 16) + 16,
491 paddingHorizontal: 16,
492 paddingTop: 16,
493 };
494
495 const renderBranch = ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
496 <SelectionRow
497 icon="arrow.triangle.branch"
498 disabled={props.selectionDisabled ?? false}
499 isFirst={index === 0}
500 isLast={index === props.branches.length - 1}
501 onPress={() => props.onSelect(item)}
502 selected={selectedBranchName === item.name}
503 subtitle={branchBadgeLabel({ branch: item, project: props.project }, m)?.toUpperCase()}
504 title={item.name}
505 />
506 );
507
508 const branchListHeader = props.worktree ? (
509 <View
510 className={cn(
511 "mb-3 overflow-hidden",
512 Platform.OS === "android" ? "rounded-[28px]" : "rounded-2xl",
513 )}
514 >
515 <ToggleRow
516 onValueChange={props.worktree.onChangeStartFromOrigin}
517 title={gt("Start from remote")}
518 value={props.worktree.startFromOrigin}
519 />
520 </View>
521 ) : null;
522
523 const branchContent =
524 props.branches.length === 0 ? (
525 <ScrollView
526 className="flex-1 bg-sheet android:bg-sheet-solid"
527 contentInsetAdjustmentBehavior="automatic"
528 contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 16, paddingTop: 16 }}
529 scrollEnabled={false}
530 showsVerticalScrollIndicator={false}
531 >
532 {branchListHeader}
533 <View
534 className="flex-1 items-center justify-center gap-3 px-4"
535 style={{
536 marginBottom: searchToolbarInset,
537 }}
538 >
539 {props.loading ? <AppActivityIndicator /> : null}
540 <Text className="text-center text-sm text-foreground-muted">
541 {props.loading
542 ? gt("Loading branches…")
543 : props.error
544 ? props.error
545 : props.query
546 ? gt("No matching branches")
547 : gt("No branches available")}
548 </Text>
549 {!props.loading && props.error ? (
550 <View className="self-center">
551 <Button label={gt("Try again")} tone="secondary" onPress={props.onRefresh} />
552 </View>
553 ) : null}
554 </View>
555 </ScrollView>
556 ) : (
557 <LegendList
558 renderScrollComponent={NativeScrollView}
559 alwaysBounceVertical={false}
560 automaticallyAdjustsScrollIndicatorInsets
561 automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
562 className="flex-1 bg-sheet android:bg-sheet-solid"
563 contentInsetAdjustmentBehavior="automatic"
564 contentContainerStyle={branchListContentStyle}
565 data={props.branches}
566 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
567 keyboardShouldPersistTaps="handled"
568 keyExtractor={(branch) =>
569 `${branch.remoteName ?? "local"}:${branch.name}:${branch.worktreePath ?? ""}`
570 }
571 ListHeaderComponent={branchListHeader}
572 ListFooterComponent={
573 props.refreshing ? (
574 <View className="items-center py-4">
575 <AppActivityIndicator />
576 </View>
577 ) : null
578 }
579 onEndReached={props.hasMore ? props.onLoadMore : undefined}
580 onEndReachedThreshold={0.35}
581 renderItem={renderBranch}
582 showsVerticalScrollIndicator={false}
583 />
584 );
585
586 return (
587 <View className="flex-1 bg-sheet" collapsable={false}>
588 <AppBar
589 title={props.title}
590 hideBottomBorder
591 onBack={() => navigation.goBack()}
592 search={search}
593 />
594 <ScreenContent>{branchContent}</ScreenContent>
595 </View>
596 );
597}