Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import { useNavigation, usePreventRemove, type StaticScreenProps } from "@react-navigation/native";
3import { useEffect, useMemo, useRef, useState } from "react";
4import { View } from "react-native";
5import {
6 isAtomCommandInterrupted,
7 squashAtomCommandFailure,
8} from "@t3tools/client-runtime/state/runtime";
9import { AppText as Text } from "../../components/ui/AppText";
10import { useProjects } from "../../state/entities";
11import { useAtomCommand } from "../../state/use-atom-command";
12import { useWorkspaceState } from "../../state/workspace";
13import { vcsEnvironment } from "../../state/vcs";
14import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
15import { NativeStackScreenOptions } from "../../native/StackHeader";
16
17import { NewTaskDraftScreen } from "./NewTaskDraftScreen";
18
19type NewTaskDraftRouteParams = {
20 readonly environmentId?: string | string[];
21 readonly projectId?: string | string[];
22 readonly branch?: string | null;
23 readonly worktreePath?: string | null;
24 readonly title?: string | string[];
25 readonly cloning?: string | string[];
26 readonly pendingTaskId?: string | string[];
27 readonly draftId?: string | string[];
28 readonly incomingShareId?: string | string[];
29};
30
31export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {
32 const params = useMemo(() => route.params ?? {}, [route.params]);
33 const pendingTaskId = Array.isArray(params.pendingTaskId)
34 ? params.pendingTaskId[0]
35 : params.pendingTaskId;
36 const draftId = Array.isArray(params.draftId) ? params.draftId[0] : params.draftId;
37 const projects = useProjects();
38 const { state: catalogState } = useWorkspaceState();
39 const navigation = useNavigation();
40 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
41
42 const initialProjectRef = useMemo(
43 () => ({
44 environmentId: Array.isArray(params.environmentId)
45 ? params.environmentId[0]
46 : params.environmentId,
47 projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
48 branch: params.branch,
49 worktreePath: params.worktreePath,
50 cloning: (Array.isArray(params.cloning) ? params.cloning[0] : params.cloning) === "1",
51 }),
52 [params],
53 );
54
55 const [preparation, setPreparation] = useState<{
56 request: typeof initialProjectRef;
57 result: Awaited<ReturnType<typeof checkoutNewTaskBranch>>;
58 workspaceRoot: string | undefined;
59 } | null>(null);
60 const project = projects.find(
61 (candidate) =>
62 candidate.environmentId === initialProjectRef.environmentId &&
63 candidate.id === initialProjectRef.projectId,
64 );
65 const environmentId = project?.environmentId;
66 const workspaceRoot = project?.workspaceRoot;
67 const needsPreparation = Boolean(initialProjectRef.branch && !pendingTaskId && !draftId);
68
69 const [pendingCheckouts, setPendingCheckouts] = useState(0);
70 const checkoutTail = useRef(Promise.resolve());
71 const waitingForProject =
72 !project &&
73 (catalogState.isLoadingConnections ||
74 (!catalogState.hasLoadedShellSnapshot &&
75 catalogState.hasConnectingEnvironment &&
76 catalogState.connectionError === null));
77
78 useEffect(() => {
79 if (!needsPreparation || !initialProjectRef.branch || waitingForProject) return;
80 const branchName = initialProjectRef.branch;
81 let active = true;
82 setPendingCheckouts((count) => count + 1);
83 // Serialize replacements: ignoring a stale result cannot undo its Git mutation.
84 checkoutTail.current = checkoutTail.current.then(async () => {
85 if (!active) {
86 setPendingCheckouts((count) => count - 1);
87 return;
88 }
89 const result = await checkoutNewTaskBranch({
90 // A thread's branch is historical; only switchRef can establish that
91 // the shared project checkout now matches it.
92 branch: {
93 name: branchName,
94 current: false,
95 isDefault: false,
96 worktreePath: initialProjectRef.worktreePath ?? null,
97 },
98 project: environmentId && workspaceRoot ? { environmentId, workspaceRoot } : null,
99 workspaceMode: "local",
100 switchRef,
101 });
102 setPendingCheckouts((count) => count - 1);
103 if (active) setPreparation({ request: initialProjectRef, result, workspaceRoot });
104 });
105 return () => {
106 active = false;
107 };
108 }, [
109 environmentId,
110 workspaceRoot,
111 initialProjectRef,
112 needsPreparation,
113 switchRef,
114 waitingForProject,
115 ]);
116
117 const result =
118 preparation?.request === initialProjectRef && preparation.workspaceRoot === workspaceRoot
119 ? preparation.result
120 : null;
121 // The native-stack guard covers iOS swipe dismissal as well as back actions.
122 // A replaced request must settle too before the shared checkout is left behind.
123 const checkoutPending = pendingCheckouts > 0 || (needsPreparation && result === null);
124 usePreventRemove(checkoutPending, () => undefined);
125 useEffect(() => {
126 if (checkoutPending || result?._tag !== "Failure") return;
127 if (!isAtomCommandInterrupted(result)) {
128 const error = squashAtomCommandFailure(result);
129 Dialog.alert(
130 "Could not switch branch",
131 error instanceof Error ? error.message : "The branch could not be checked out.",
132 );
133 }
134 navigation.goBack();
135 }, [checkoutPending, result, navigation]);
136
137 const preparedProjectRef = useMemo(
138 () =>
139 result?._tag === "Success"
140 ? { ...initialProjectRef, branch: result.value.name }
141 : initialProjectRef,
142 [initialProjectRef, result],
143 );
144 const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");
145
146 return (
147 <>
148 <NativeStackScreenOptions
149 options={{
150 title: Array.isArray(params.title) ? params.title[0] : (params.title ?? "New task"),
151 }}
152 />
153 {preparingBranch ? (
154 <View className="flex-1 items-center justify-center bg-screen">
155 <Text className="text-foreground">Switching branch...</Text>
156 </View>
157 ) : (
158 <NewTaskDraftScreen
159 initialProjectRef={preparedProjectRef}
160 incomingShareId={
161 Array.isArray(params.incomingShareId)
162 ? params.incomingShareId[0]
163 : params.incomingShareId
164 }
165 pendingTaskId={pendingTaskId}
166 draftId={draftId}
167 />
168 )}
169 </>
170 );
171}