Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NewTaskDraftRouteScreen.tsx

181 lines6.6 KB

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 { resolveNewTaskBranchWorktreePath } from "./new-task-context-presentation";
16import { NativeStackScreenOptions } from "../../native/StackHeader";
17​
18import { NewTaskDraftScreen } from "./NewTaskDraftScreen";
19​
20type NewTaskDraftRouteParams = {
21 readonly environmentId?: string | string[];
22 readonly projectId?: string | string[];
23 readonly branch?: string | null;
24 readonly worktreePath?: string | null;
25 readonly title?: string | string[];
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 readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false });
42 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
43​
44 const initialProjectRef = useMemo(
45 () => ({
46 environmentId: Array.isArray(params.environmentId)
47 ? params.environmentId[0]
48 : params.environmentId,
49 projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
50 branch: params.branch,
51 worktreePath: params.worktreePath,
52 cloning: (Array.isArray(params.cloning) ? params.cloning[0] : params.cloning) === "1",
53 }),
54 [params],
55 );
56​
57 const [preparation, setPreparation] = useState<{
58 request: typeof initialProjectRef;
59 result: Awaited<ReturnType<typeof checkoutNewTaskBranch>>;
60 workspaceRoot: string | undefined;
61 } | null>(null);
62 const project = projects.find(
63 (candidate) =>
64 candidate.environmentId === initialProjectRef.environmentId &&
65 candidate.id === initialProjectRef.projectId,
66 );
67 const environmentId = project?.environmentId;
68 const workspaceRoot = project?.workspaceRoot;
69 const needsPreparation = Boolean(initialProjectRef.branch && !pendingTaskId && !draftId);
70​
71 const [pendingCheckouts, setPendingCheckouts] = useState(0);
72 const checkoutTail = useRef(Promise.resolve());
73 const waitingForProject =
74 !project &&
75 (catalogState.isLoadingConnections ||
76 (!catalogState.hasLoadedShellSnapshot &&
77 catalogState.hasConnectingEnvironment &&
78 catalogState.connectionError === null));
79​
80 useEffect(() => {
81 if (!needsPreparation || !initialProjectRef.branch || waitingForProject) return;
82 const branchName = initialProjectRef.branch;
83 let active = true;
84 setPendingCheckouts((count) => count + 1);
85 // Serialize replacements: ignoring a stale result cannot undo its Git mutation.
86 checkoutTail.current = checkoutTail.current.then(async () => {
87 if (!active) {
88 setPendingCheckouts((count) => count - 1);
89 return;
90 }
91 const result = await checkoutNewTaskBranch({
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 readRefs,
101 switchRef,
102 });
103 setPendingCheckouts((count) => count - 1);
104 if (active) setPreparation({ request: initialProjectRef, result, workspaceRoot });
105 });
106 return () => {
107 active = false;
108 };
109 }, [
110 environmentId,
111 workspaceRoot,
112 initialProjectRef,
113 needsPreparation,
114 readRefs,
115 switchRef,
116 waitingForProject,
117 ]);
118​
119 const result =
120 preparation?.request === initialProjectRef && preparation.workspaceRoot === workspaceRoot
121 ? preparation.result
122 : null;
123 // The native-stack guard covers iOS swipe dismissal as well as back actions.
124 // A replaced request must settle too before the shared checkout is left behind.
125 const checkoutPending = pendingCheckouts > 0 || (needsPreparation && result === null);
126 usePreventRemove(checkoutPending, () => undefined);
127 useEffect(() => {
128 if (checkoutPending || result?._tag !== "Failure") return;
129 if (!isAtomCommandInterrupted(result)) {
130 const error = squashAtomCommandFailure(result);
131 Dialog.alert(
132 "Could not switch branch",
133 error instanceof Error ? error.message : "The branch could not be checked out.",
134 );
135 }
136 navigation.goBack();
137 }, [checkoutPending, result, navigation]);
138​
139 const preparedProjectRef = useMemo(
140 () =>
141 result?._tag === "Success" && workspaceRoot
142 ? {
143 ...initialProjectRef,
144 branch: result.value.name,
145 worktreePath: resolveNewTaskBranchWorktreePath({
146 workspaceMode: "local",
147 projectCwd: workspaceRoot,
148 branchWorktreePath: result.value.worktreePath,
149 }),
150 }
151 : initialProjectRef,
152 [initialProjectRef, result, workspaceRoot],
153 );
154 const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");
155​
156 return (
157 <>
158 <NativeStackScreenOptions
159 options={{
160 title: Array.isArray(params.title) ? params.title[0] : (params.title ?? "New task"),
161 }}
162 />
163 {preparingBranch ? (
164 <View className="flex-1 items-center justify-center bg-screen">
165 <Text className="text-foreground">Switching branch...</Text>
166 </View>
167 ) : (
168 <NewTaskDraftScreen
169 initialProjectRef={preparedProjectRef}
170 incomingShareId={
171 Array.isArray(params.incomingShareId)
172 ? params.incomingShareId[0]
173 : params.incomingShareId
174 }
175 pendingTaskId={pendingTaskId}
176 draftId={draftId}
177 />
178 )}
179 </>
180 );