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

NewTaskDraftRouteScreen.tsx

207 lines7.8 KB

1import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
2import { useNewTaskFlow } from "./new-task-flow-provider";
3import * as Dialog from "../../components/ui/Dialog";
4import {
5 useNavigation,
6 useRoute,
7 usePreventRemove,
8 usePreventRemoveContext,
9 type StaticScreenProps,
10} from "@react-navigation/native";
11import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
12import { View } from "react-native";
13import {
14 isAtomCommandInterrupted,
15 squashAtomCommandFailure,
16} from "@t3tools/client-runtime/state/runtime";
17import { AppText as Text } from "../../components/ui/AppText";
18import { useProjects } from "../../state/entities";
19import { useAtomCommand } from "../../state/use-atom-command";
20import { useWorkspaceState } from "../../state/workspace";
21import { vcsEnvironment } from "../../state/vcs";
22import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
23import { resolveNewTaskBranchWorktreePath } from "./new-task-context-presentation";
24import { NativeStackScreenOptions } from "../../native/StackHeader";
25​
26import { ThreadScreenFallback } from "./ThreadScreenHost";
27import { NewTaskDraftScreen } from "./NewTaskDraftScreen";
28​
29import type { NewTaskDraftRouteParams } from "./thread-route-state";
30export type { NewTaskDraftRouteParams } from "./thread-route-state";
31​
32export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {
33 const currentRoute = useRoute();
34 const params = useMemo(() => route.params ?? {}, [route.params]);
35 const { reset } = useNewTaskFlow();
36 const { deferThreadSelectionUntil } = useAdaptiveWorkspaceLayout();
37 const [initialized, setInitialized] = useState(false);
38 useLayoutEffect(() => {
39 reset();
40 setInitialized(true);
41 }, [reset]);
42 const pendingTaskId = Array.isArray(params.pendingTaskId)
43 ? params.pendingTaskId[0]
44 : params.pendingTaskId;
45 const draftId = Array.isArray(params.draftId) ? params.draftId[0] : params.draftId;
46 const projects = useProjects();
47 const { state: catalogState } = useWorkspaceState();
48 const navigation = useNavigation();
49 const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false });
50 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
51​
52 const initialProjectRef = useMemo(
53 () => ({
54 environmentId: Array.isArray(params.environmentId)
55 ? params.environmentId[0]
56 : params.environmentId,
57 projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
58 branch: params.branch,
59 worktreePath: params.worktreePath,
60 cloning: (Array.isArray(params.cloning) ? params.cloning[0] : params.cloning) === "1",
61 }),
62 [params],
63 );
64​
65 const [preparation, setPreparation] = useState<{
66 request: typeof initialProjectRef;
67 result: Awaited<ReturnType<typeof checkoutNewTaskBranch>>;
68 workspaceRoot: string | undefined;
69 } | null>(null);
70 const project = projects.find(
71 (candidate) =>
72 candidate.environmentId === initialProjectRef.environmentId &&
73 candidate.id === initialProjectRef.projectId,
74 );
75 const environmentId = project?.environmentId;
76 const workspaceRoot = project?.workspaceRoot;
77 const needsPreparation = Boolean(initialProjectRef.branch && !pendingTaskId && !draftId);
78​
79 const [pendingCheckouts, setPendingCheckouts] = useState(0);
80 const checkoutTail = useRef(Promise.resolve());
81 const committedCheckoutReleases = useRef(new Set<() => void>());
82 const waitingForProject =
83 !project &&
84 (catalogState.isLoadingConnections ||
85 (!catalogState.hasLoadedShellSnapshot &&
86 catalogState.hasConnectingEnvironment &&
87 catalogState.connectionError === null));
88​
89 useEffect(() => {
90 if (!needsPreparation || !initialProjectRef.branch || waitingForProject) return;
91 const branchName = initialProjectRef.branch;
92 let active = true;
93 setPendingCheckouts((count) => count + 1);
94 // Serialize replacements: ignoring a stale result cannot undo its Git mutation.
95 checkoutTail.current = checkoutTail.current.then(async () => {
96 if (!active) {
97 setPendingCheckouts((count) => count - 1);
98 return;
99 }
100 const result = await checkoutNewTaskBranch({
101 branch: {
102 name: branchName,
103 current: false,
104 isDefault: false,
105 worktreePath: initialProjectRef.worktreePath ?? null,
106 },
107 project: environmentId && workspaceRoot ? { environmentId, workspaceRoot } : null,
108 workspaceMode: "local",
109 readRefs,
110 switchRef,
111 });
112 setPendingCheckouts((count) => count - 1);
113 if (active) setPreparation({ request: initialProjectRef, result, workspaceRoot });
114 });
115 const committed = Promise.withResolvers<void>();
116 committedCheckoutReleases.current.add(committed.resolve);
117 deferThreadSelectionUntil(Promise.allSettled([checkoutTail.current, committed.promise]));
118 return () => {
119 active = false;
120 };
121 }, [
122 deferThreadSelectionUntil,
123 environmentId,
124 workspaceRoot,
125 initialProjectRef,
126 needsPreparation,
127 readRefs,
128 switchRef,
129 waitingForProject,
130 ]);
131​
132 const result =
133 preparation?.request === initialProjectRef && preparation.workspaceRoot === workspaceRoot
134 ? preparation.result
135 : null;
136 // Guard native swipes too; replaced checkout requests must settle before leaving the shared checkout.
137 const checkoutPending = pendingCheckouts > 0 || (needsPreparation && result === null);
138 usePreventRemove(checkoutPending, () => undefined);
139 const { preventedRoutes } = usePreventRemoveContext();
140 const removalBlocked = preventedRoutes[currentRoute.key]?.preventRemove === true;
141 useEffect(() => {
142 if (checkoutPending || removalBlocked) return;
143 // Native-stack reads the provider state, which commits after the hook updates its registry.
144 for (const release of committedCheckoutReleases.current) release();
145 committedCheckoutReleases.current.clear();
146 }, [checkoutPending, removalBlocked]);
147 useEffect(() => {
148 const releases = committedCheckoutReleases.current;
149 return () => {
150 for (const release of releases) release();
151 releases.clear();
152 };
153 }, []);
154 useEffect(() => {
155 if (checkoutPending || result?._tag !== "Failure") return;
156 if (!isAtomCommandInterrupted(result)) {
157 const error = squashAtomCommandFailure(result);
158 Dialog.alert(
159 "Could not switch branch",
160 error instanceof Error ? error.message : "The branch could not be checked out.",
161 );
162 }
163 navigation.goBack();
164 }, [checkoutPending, result, navigation]);
165​
166 const preparedProjectRef = useMemo(
167 () =>
168 result?._tag === "Success" && workspaceRoot
169 ? {
170 ...initialProjectRef,
171 branch: result.value.name,
172 worktreePath: resolveNewTaskBranchWorktreePath({
173 workspaceMode: "local",
174 projectCwd: workspaceRoot,
175 branchWorktreePath: result.value.worktreePath,
176 }),
177 }
178 : initialProjectRef,
179 [initialProjectRef, result, workspaceRoot],
180 );
181 const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");
182​
183 if (!initialized) return null;
184 return (
185 <>
186 {preparingBranch ? (
187 <ThreadScreenFallback>
188 <NativeStackScreenOptions options={{ title: "New thread" }} />
189 <View className="flex-1 items-center justify-center bg-screen">
190 <Text className="text-foreground">Switching branch...</Text>
191 </View>
192 </ThreadScreenFallback>
193 ) : (
194 <NewTaskDraftScreen
195 initialProjectRef={preparedProjectRef}
196 incomingShareId={
197 Array.isArray(params.incomingShareId)
198 ? params.incomingShareId[0]
199 : params.incomingShareId
200 }
201 pendingTaskId={pendingTaskId}
202 draftId={draftId}
203 />
204 )}
205 </>
206 );