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

NewTaskDraftRouteScreen.tsx

172 lines6.4 KB

1import { useNavigation, usePreventRemove, type StaticScreenProps } from "@react-navigation/native";
2import { useEffect, useMemo, useRef, useState } from "react";
3import { Alert, View } from "react-native";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import { AppText as Text } from "../../components/AppText";
9import { useProjects } from "../../state/entities";
10import { useAtomCommand } from "../../state/use-atom-command";
11import { useWorkspaceState } from "../../state/workspace";
12import { vcsEnvironment } from "../../state/vcs";
13import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
14import { NativeStackScreenOptions } from "../../native/StackHeader";
15​
16import { NewTaskDraftScreen } from "./NewTaskDraftScreen";
17​
18type NewTaskDraftRouteParams = {
19 readonly environmentId?: string | string[];
20 readonly projectId?: string | string[];
21 readonly branch?: string | null;
22 readonly worktreePath?: string | null;
23 readonly title?: string | string[];
24 readonly pendingTaskId?: string | string[];
25 readonly draftId?: string | string[];
26 readonly incomingShareId?: string | string[];
27};
28​
29export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {
30 const params = useMemo(() => route.params ?? {}, [route.params]);
31 const pendingTaskId = Array.isArray(params.pendingTaskId)
32 ? params.pendingTaskId[0]
33 : params.pendingTaskId;
34 const draftId = Array.isArray(params.draftId) ? params.draftId[0] : params.draftId;
35 const projects = useProjects();
36 const { state: catalogState } = useWorkspaceState();
37 const navigation = useNavigation();
38 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
39​
40 // Keyed on the params object so a fresh navigation to this (already
41 // mounted) screen produces a new reference, letting the draft screen
42 // re-apply the requested project.
43 const initialProjectRef = useMemo(
44 () => ({
45 environmentId: Array.isArray(params.environmentId)
46 ? params.environmentId[0]
47 : params.environmentId,
48 projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
49 branch: params.branch,
50 worktreePath: params.worktreePath,
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 Alert.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 // Send/queue remain unavailable on failure while the unlocked route closes.
145 const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");
146​
147 return (
148 <>
149 <NativeStackScreenOptions
150 options={{
151 title: Array.isArray(params.title) ? params.title[0] : (params.title ?? "New task"),
152 }}
153 />
154 {preparingBranch ? (
155 <View className="flex-1 items-center justify-center bg-screen">
156 <Text className="text-foreground">Switching branch...</Text>
157 </View>
158 ) : (
159 <NewTaskDraftScreen
160 initialProjectRef={preparedProjectRef}
161 incomingShareId={
162 Array.isArray(params.incomingShareId)
163 ? params.incomingShareId[0]
164 : params.incomingShareId
165 }
166 pendingTaskId={pendingTaskId}
167 draftId={draftId}
168 />
169 )}
170 </>
171 );