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 /** Set by Add Project when this draft opens while the project's clone runs. */
26 readonly cloning?: string | string[];
27 readonly pendingTaskId?: string | string[];
28 readonly draftId?: string | string[];
29 readonly incomingShareId?: string | string[];
30};
31
32export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {
33 const params = useMemo(() => route.params ?? {}, [route.params]);
34 const pendingTaskId = Array.isArray(params.pendingTaskId)
35 ? params.pendingTaskId[0]
36 : params.pendingTaskId;
37 const draftId = Array.isArray(params.draftId) ? params.draftId[0] : params.draftId;
38 const projects = useProjects();
39 const { state: catalogState } = useWorkspaceState();
40 const navigation = useNavigation();
41 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
42
43 // Keyed on the params object so a fresh navigation to this (already
44 // mounted) screen produces a new reference, letting the draft screen
45 // re-apply the requested project.
46 const initialProjectRef = useMemo(
47 () => ({
48 environmentId: Array.isArray(params.environmentId)
49 ? params.environmentId[0]
50 : params.environmentId,
51 projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
52 branch: params.branch,
53 worktreePath: params.worktreePath,
54 cloning: (Array.isArray(params.cloning) ? params.cloning[0] : params.cloning) === "1",
55 }),
56 [params],
57 );
58
59 const [preparation, setPreparation] = useState<{
60 request: typeof initialProjectRef;
61 result: Awaited<ReturnType<typeof checkoutNewTaskBranch>>;
62 workspaceRoot: string | undefined;
63 } | null>(null);
64 const project = projects.find(
65 (candidate) =>
66 candidate.environmentId === initialProjectRef.environmentId &&
67 candidate.id === initialProjectRef.projectId,
68 );
69 const environmentId = project?.environmentId;
70 const workspaceRoot = project?.workspaceRoot;
71 const needsPreparation = Boolean(initialProjectRef.branch && !pendingTaskId && !draftId);
72
73 const [pendingCheckouts, setPendingCheckouts] = useState(0);
74 const checkoutTail = useRef(Promise.resolve());
75 const waitingForProject =
76 !project &&
77 (catalogState.isLoadingConnections ||
78 (!catalogState.hasLoadedShellSnapshot &&
79 catalogState.hasConnectingEnvironment &&
80 catalogState.connectionError === null));
81
82 useEffect(() => {
83 if (!needsPreparation || !initialProjectRef.branch || waitingForProject) return;
84 const branchName = initialProjectRef.branch;
85 let active = true;
86 setPendingCheckouts((count) => count + 1);
87 // Serialize replacements: ignoring a stale result cannot undo its Git mutation.
88 checkoutTail.current = checkoutTail.current.then(async () => {
89 if (!active) {
90 setPendingCheckouts((count) => count - 1);
91 return;
92 }
93 const result = await checkoutNewTaskBranch({
94 // A thread's branch is historical; only switchRef can establish that
95 // the shared project checkout now matches it.
96 branch: {
97 name: branchName,
98 current: false,
99 isDefault: false,
100 worktreePath: initialProjectRef.worktreePath ?? null,
101 },
102 project: environmentId && workspaceRoot ? { environmentId, workspaceRoot } : null,
103 workspaceMode: "local",
104 switchRef,
105 });
106 setPendingCheckouts((count) => count - 1);
107 if (active) setPreparation({ request: initialProjectRef, result, workspaceRoot });
108 });
109 return () => {
110 active = false;
111 };
112 }, [
113 environmentId,
114 workspaceRoot,
115 initialProjectRef,
116 needsPreparation,
117 switchRef,
118 waitingForProject,
119 ]);
120
121 const result =
122 preparation?.request === initialProjectRef && preparation.workspaceRoot === workspaceRoot
123 ? preparation.result
124 : null;
125 // The native-stack guard covers iOS swipe dismissal as well as back actions.
126 // A replaced request must settle too before the shared checkout is left behind.
127 const checkoutPending = pendingCheckouts > 0 || (needsPreparation && result === null);
128 usePreventRemove(checkoutPending, () => undefined);
129 useEffect(() => {
130 if (checkoutPending || result?._tag !== "Failure") return;
131 if (!isAtomCommandInterrupted(result)) {
132 const error = squashAtomCommandFailure(result);
133 Dialog.alert(
134 "Could not switch branch",
135 error instanceof Error ? error.message : "The branch could not be checked out.",
136 );
137 }
138 navigation.goBack();
139 }, [checkoutPending, result, navigation]);
140
141 const preparedProjectRef = useMemo(
142 () =>
143 result?._tag === "Success"
144 ? { ...initialProjectRef, branch: result.value.name }
145 : initialProjectRef,
146 [initialProjectRef, result],
147 );
148 // Send/queue remain unavailable on failure while the unlocked route closes.
149 const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");
150
151 return (
152 <>
153 <NativeStackScreenOptions
154 options={{
155 title: Array.isArray(params.title) ? params.title[0] : (params.title ?? "New task"),
156 }}
157 />
158 {preparingBranch ? (
159 <View className="flex-1 items-center justify-center bg-screen">
160 <Text className="text-foreground">Switching branch...</Text>
161 </View>
162 ) : (
163 <NewTaskDraftScreen
164 initialProjectRef={preparedProjectRef}
165 incomingShareId={
166 Array.isArray(params.incomingShareId)
167 ? params.incomingShareId[0]
168 : params.incomingShareId
169 }
170 pendingTaskId={pendingTaskId}
171 draftId={draftId}
172 />
173 )}
174 </>
175 );
176}