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

NewTaskDraftRouteScreen.tsx

209 lines8.0 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 // oxlint-disable-next-line react/set-state-in-effect -- Draft reset runs once before first paint; initialized gates the screen until then.
41 setInitialized(true);
42 }, [reset]);
43 const pendingTaskId = Array.isArray(params.pendingTaskId)
44 ? params.pendingTaskId[0]
45 : params.pendingTaskId;
46 const draftId = Array.isArray(params.draftId) ? params.draftId[0] : params.draftId;
47 const projects = useProjects();
48 const { state: catalogState } = useWorkspaceState();
49 const navigation = useNavigation();
50 const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false });
51 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
52​
53 const initialProjectRef = useMemo(
54 () => ({
55 environmentId: Array.isArray(params.environmentId)
56 ? params.environmentId[0]
57 : params.environmentId,
58 projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
59 branch: params.branch,
60 worktreePath: params.worktreePath,
61 cloning: (Array.isArray(params.cloning) ? params.cloning[0] : params.cloning) === "1",
62 }),
63 [params],
64 );
65​
66 const [preparation, setPreparation] = useState<{
67 request: typeof initialProjectRef;
68 result: Awaited<ReturnType<typeof checkoutNewTaskBranch>>;
69 workspaceRoot: string | undefined;
70 } | null>(null);
71 const project = projects.find(
72 (candidate) =>
73 candidate.environmentId === initialProjectRef.environmentId &&
74 candidate.id === initialProjectRef.projectId,
75 );
76 const environmentId = project?.environmentId;
77 const workspaceRoot = project?.workspaceRoot;
78 const needsPreparation = Boolean(initialProjectRef.branch && !pendingTaskId && !draftId);
79​
80 const [pendingCheckouts, setPendingCheckouts] = useState(0);
81 const checkoutTail = useRef(Promise.resolve());
82 const committedCheckoutReleases = useRef(new Set<() => void>());
83 const waitingForProject =
84 !project &&
85 (catalogState.isLoadingConnections ||
86 (!catalogState.hasLoadedShellSnapshot &&
87 catalogState.hasConnectingEnvironment &&
88 catalogState.connectionError === null));
89​
90 useEffect(() => {
91 if (!needsPreparation || !initialProjectRef.branch || waitingForProject) return;
92 const branchName = initialProjectRef.branch;
93 let active = true;
94 // oxlint-disable-next-line react/set-state-in-effect -- Counts the serialized Git checkout this effect starts.
95 setPendingCheckouts((count) => count + 1);
96 // Serialize replacements: ignoring a stale result cannot undo its Git mutation.
97 checkoutTail.current = checkoutTail.current.then(async () => {
98 if (!active) {
99 setPendingCheckouts((count) => count - 1);
100 return;
101 }
102 const result = await checkoutNewTaskBranch({
103 branch: {
104 name: branchName,
105 current: false,
106 isDefault: false,
107 worktreePath: initialProjectRef.worktreePath ?? null,
108 },
109 project: environmentId && workspaceRoot ? { environmentId, workspaceRoot } : null,
110 workspaceMode: "local",
111 readRefs,
112 switchRef,
113 });
114 setPendingCheckouts((count) => count - 1);
115 if (active) setPreparation({ request: initialProjectRef, result, workspaceRoot });
116 });
117 const committed = Promise.withResolvers<void>();
118 committedCheckoutReleases.current.add(committed.resolve);
119 deferThreadSelectionUntil(Promise.allSettled([checkoutTail.current, committed.promise]));
120 return () => {
121 active = false;
122 };
123 }, [
124 deferThreadSelectionUntil,
125 environmentId,
126 workspaceRoot,
127 initialProjectRef,
128 needsPreparation,
129 readRefs,
130 switchRef,
131 waitingForProject,
132 ]);
133​
134 const result =
135 preparation?.request === initialProjectRef && preparation.workspaceRoot === workspaceRoot
136 ? preparation.result
137 : null;
138 // Guard native swipes too; replaced checkout requests must settle before leaving the shared checkout.
139 const checkoutPending = pendingCheckouts > 0 || (needsPreparation && result === null);
140 usePreventRemove(checkoutPending, () => undefined);
141 const { preventedRoutes } = usePreventRemoveContext();
142 const removalBlocked = preventedRoutes[currentRoute.key]?.preventRemove === true;
143 useEffect(() => {
144 if (checkoutPending || removalBlocked) return;
145 // Native-stack reads the provider state, which commits after the hook updates its registry.
146 for (const release of committedCheckoutReleases.current) release();
147 committedCheckoutReleases.current.clear();
148 }, [checkoutPending, removalBlocked]);
149 useEffect(() => {
150 const releases = committedCheckoutReleases.current;
151 return () => {
152 for (const release of releases) release();
153 releases.clear();
154 };
155 }, []);
156 useEffect(() => {
157 if (checkoutPending || result?._tag !== "Failure") return;
158 if (!isAtomCommandInterrupted(result)) {
159 const error = squashAtomCommandFailure(result);
160 Dialog.alert(
161 "Could not switch branch",
162 error instanceof Error ? error.message : "The branch could not be checked out.",
163 );
164 }
165 navigation.goBack();
166 }, [checkoutPending, result, navigation]);
167​
168 const preparedProjectRef = useMemo(
169 () =>
170 result?._tag === "Success" && workspaceRoot
171 ? {
172 ...initialProjectRef,
173 branch: result.value.name,
174 worktreePath: resolveNewTaskBranchWorktreePath({
175 workspaceMode: "local",
176 projectCwd: workspaceRoot,
177 branchWorktreePath: result.value.worktreePath,
178 }),
179 }
180 : initialProjectRef,
181 [initialProjectRef, result, workspaceRoot],
182 );
183 const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");
184​
185 if (!initialized) return null;
186 return (
187 <>
188 {preparingBranch ? (
189 <ThreadScreenFallback>
190 <NativeStackScreenOptions options={{ title: "New thread" }} />
191 <View className="flex-1 items-center justify-center bg-screen">
192 <Text className="text-foreground">Switching branch...</Text>
193 </View>
194 </ThreadScreenFallback>
195 ) : (
196 <NewTaskDraftScreen
197 initialProjectRef={preparedProjectRef}
198 incomingShareId={
199 Array.isArray(params.incomingShareId)
200 ? params.incomingShareId[0]
201 : params.incomingShareId
202 }
203 pendingTaskId={pendingTaskId}
204 draftId={draftId}
205 />
206 )}
207 </>
208 );