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

NewTaskRouteScreen.tsx

367 lines14.0 KB

1import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
2import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
3import { SymbolView } from "../../components/AppSymbol";
4import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
5import { useEffect, useRef, useState } from "react";
6import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
7import { useSafeAreaInsets } from "react-native-safe-area-context";
8import { useThemeColor } from "../../lib/useThemeColor";
9import { cn } from "../../lib/cn";
10​
11import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
12import { AppText as Text } from "../../components/AppText";
13import { ProjectFavicon } from "../../components/ProjectFavicon";
14import { useProjects } from "../../state/entities";
15import type { WorkspaceState } from "../../state/workspaceModel";
16import { useWorkspaceState } from "../../state/workspace";
17import { scopedProjectKey } from "../../lib/scopedEntities";
18import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
19import { useIncomingShare } from "../sharing/IncomingShareProvider";
20import { useNewTaskFlow } from "./new-task-flow-provider";
21​
22type NewTaskRouteParams = {
23 readonly incomingShareId?: string | string[];
24};
25​
26function deriveProjectEmptyState(catalogState: WorkspaceState): {
27 readonly title: string;
28 readonly detail: string;
29 readonly loading: boolean;
30} {
31 if (catalogState.isLoadingConnections) {
32 return {
33 title: "Loading environments",
34 detail: "Checking saved environments on this device.",
35 loading: true,
36 };
37 }
38​
39 if (!catalogState.hasConnections) {
40 return {
41 title: "No environments connected",
42 detail: "Add an environment before creating a task.",
43 loading: false,
44 };
45 }
46​
47 if (
48 (catalogState.connectionState === "available" ||
49 catalogState.connectionState === "offline" ||
50 catalogState.connectionState === "error") &&
51 !catalogState.hasLoadedShellSnapshot
52 ) {
53 return {
54 title: "Environment unavailable",
55 detail:
56 catalogState.connectionError ??
57 "The saved environment is offline. Check the URL or start the environment, then retry.",
58 loading: false,
59 };
60 }
61​
62 if (
63 catalogState.hasConnectingEnvironment &&
64 !catalogState.hasLoadedShellSnapshot &&
65 catalogState.connectionError === null
66 ) {
67 return {
68 title: "Connecting to environment",
69 detail: "Loading projects from the saved environment.",
70 loading: true,
71 };
72 }
73​
74 return {
75 title: "No projects found",
76 detail: "The connected environment did not report any projects.",
77 loading: false,
78 };
80​
81export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
82 const projects = useProjects();
83 const { projectScopes } = useNewTaskFlow();
84 const { state: catalogState } = useWorkspaceState();
85 const navigation = useNavigation();
86 const isFocused = useIsFocused();
87 const { layout } = useAdaptiveWorkspaceLayout();
88 const insets = useSafeAreaInsets();
89 const chevronColor = useThemeColor("--color-chevron");
90 const accentColor = useThemeColor("--color-icon-muted");
91 const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
92 const { getShare, releaseShareReservation } = useIncomingShare();
93 const routeShareId = Array.isArray(route.params?.incomingShareId)
94 ? route.params.incomingShareId[0]
95 : route.params?.incomingShareId;
96 const incomingShare = routeShareId ? getShare(routeShareId) : null;
97 const incomingShareSubtitle = incomingShare
98 ? incomingShare.attachments.length === 0
99 ? "Choose a project for what you shared"
100 : incomingShare.attachments.length === 1
101 ? "Choose a project for the image you shared"
102 : `Choose a project for the ${incomingShare.attachments.length} images you shared`
103 : null;
104 const screenTitle = incomingShare ? "Start a task" : "Choose project";
105 const projectEmptyState = deriveProjectEmptyState(catalogState);
106 const resumedDestinationKeyRef = useRef<string | null>(null);
107 const reservedDestinationProject = incomingShare?.destination
108 ? (projects.find(
109 (project) =>
110 project.environmentId === incomingShare.destination?.environmentId &&
111 project.id === incomingShare.destination?.projectId,
112 ) ?? null)
113 : null;
114​
115 async function selectProject(project: EnvironmentProject): Promise<void> {
116 if (incomingShare?.destination && !reservedDestinationProject) {
117 try {
118 await releaseShareReservation(incomingShare.id, incomingShare.destination);
119 } catch (error) {
120 Alert.alert(
121 "Could not change project",
122 error instanceof Error
123 ? error.message
124 : "The shared content reservation could not be updated.",
125 );
126 return;
127 }
128 }
129 navigation.navigate("NewTaskSheet", {
130 screen: "NewTaskDraft",
131 params: {
132 environmentId: project.environmentId,
133 projectId: project.id,
134 title: project.title,
135 incomingShareId: incomingShare?.id,
136 },
137 });
138 }
139​
140 function toggleGroup(groupKey: string): void {
141 setExpandedGroupKeys((current) => {
142 const next = new Set(current);
143 if (next.has(groupKey)) {
144 next.delete(groupKey);
145 } else {
146 next.add(groupKey);
147 }
148 return next;
149 });
150 }
151​
152 useEffect(() => {
153 const destination = incomingShare?.destination;
154 if (!destination) {
155 resumedDestinationKeyRef.current = null;
156 return;
157 }
158 if (!isFocused) {
159 // Returning from the reserved draft is a fresh resume attempt. Keeping
160 // this latch set would leave every project row disabled with no route.
161 resumedDestinationKeyRef.current = null;
162 return;
163 }
164 const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`;
165 if (resumedDestinationKeyRef.current === destinationKey) {
166 return;
167 }
168 if (!reservedDestinationProject) {
169 return;
170 }
171 resumedDestinationKeyRef.current = destinationKey;
172 navigation.navigate("NewTaskSheet", {
173 screen: "NewTaskDraft",
174 params: {
175 environmentId: reservedDestinationProject.environmentId,
176 projectId: reservedDestinationProject.id,
177 title: reservedDestinationProject.title,
178 incomingShareId: incomingShare.id,
179 },
180 });
181 }, [incomingShare, isFocused, navigation, reservedDestinationProject]);
182​
183 return (
184 <View collapsable={false} className="flex-1 bg-sheet">
185 {Platform.OS === "android" ? (
186 <>
187 {/* Android renders its own in-screen header instead of the native bar. */}
188 <NativeStackScreenOptions options={{ headerShown: false }} />
189 <AndroidScreenHeader
190 title={screenTitle}
191 subtitle={incomingShareSubtitle}
192 onBack={layout.usesSplitView ? () => navigation.goBack() : undefined}
193 actions={
194 catalogState.hasReadyEnvironment
195 ? [
196 {
197 accessibilityLabel: "Add project",
198 icon: "plus",
199 onPress: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
200 },
201 ]
202 : []
203 }
204 />
205 </>
206 ) : (
207 <>
208 <NativeStackScreenOptions
209 options={{
210 title: screenTitle,
211 unstable_headerSubtitle: incomingShareSubtitle ?? undefined,
212 }}
213 />
214 <NativeHeaderToolbar placement="right">
215 {layout.usesSplitView ? (
216 <NativeHeaderToolbar.Button
217 accessibilityLabel="Close new task"
218 icon="xmark"
219 onPress={() => navigation.goBack()}
220 separateBackground
221 />
222 ) : null}
223 {catalogState.hasReadyEnvironment ? (
224 <NativeHeaderToolbar.Button
225 icon="plus"
226 onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
227 separateBackground
228 />
229 ) : null}
230 </NativeHeaderToolbar>
231 </>
232 )}
233​
234 <ScrollView
235 contentInsetAdjustmentBehavior="automatic"
236 showsVerticalScrollIndicator={false}
237 className="flex-1"
238 contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
239 contentContainerStyle={{
240 gap: 12,
241 paddingBottom: 8,
242 paddingHorizontal: 20,
243 paddingTop: 8,
244 }}
245 >
246 {projectScopes.length === 0 ? (
247 <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
248 {projectEmptyState.loading ? <ActivityIndicator color={accentColor} /> : null}
249 <Text className="text-center text-lg font-t3-bold text-foreground">
250 {projectEmptyState.title}
251 </Text>
252 <Text className="text-center text-sm leading-normal text-foreground-muted">
253 {projectEmptyState.detail}
254 </Text>
255 {!catalogState.hasReadyEnvironment ? (
256 <Pressable
257 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
258 onPress={() => navigation.navigate("ConnectionsNew")}
259 >
260 <Text className="text-sm font-t3-bold text-primary-foreground">
261 Add environment
262 </Text>
263 </Pressable>
264 ) : (
265 <Pressable
266 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
267 onPress={() => navigation.navigate("NewTaskSheet", { screen: "AddProject" })}
268 >
269 <Text className="text-sm font-t3-bold text-primary-foreground">
270 Add new project
271 </Text>
272 </Pressable>
273 )}
274 </View>
275 ) : (
276 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
277 {projectScopes.map((scope, scopeIndex) => {
278 const hasMultipleProjects = scope.projects.length > 1;
279 const expanded = expandedGroupKeys.has(scope.key);
280 const singleProject = hasMultipleProjects ? null : scope.projects[0];
281 return (
282 <View
283 key={scope.key}
284 className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
285 >
286 <Pressable
287 disabled={singleProject !== null && reservedDestinationProject !== null}
288 onPress={() => {
289 if (singleProject) {
290 void selectProject(singleProject);
291 } else {
292 toggleGroup(scope.key);
293 }
294 }}
295 className="flex-row items-center gap-3 bg-card px-4 py-3.5"
296 >
297 <View className="h-7 w-7 items-center justify-center">
298 <ProjectFavicon
299 environmentId={scope.representative.environmentId}
300 size={20}
301 projectTitle={scope.title}
302 workspaceRoot={scope.representative.workspaceRoot}
303 />
304 </View>
305 <View className="min-w-0 flex-1">
306 <Text className="text-base leading-snug font-t3-bold">{scope.title}</Text>
307 <Text
308 className="text-xs leading-snug text-foreground-muted"
309 ellipsizeMode="middle"
310 numberOfLines={1}
311 >
312 {hasMultipleProjects
313 ? `${scope.projects.length} workspaces`
314 : singleProject?.workspaceRoot}
315 </Text>
316 </View>
317 <SymbolView
318 name={hasMultipleProjects && expanded ? "chevron.down" : "chevron.right"}
319 size={14}
320 tintColor={chevronColor}
321 type="monochrome"
322 />
323 </Pressable>
324 {hasMultipleProjects && expanded
325 ? scope.projects.map((project) => (
326 <Pressable
327 key={scopedProjectKey(project.environmentId, project.id)}
328 disabled={reservedDestinationProject !== null}
329 onPress={() => void selectProject(project)}
330 className="flex-row items-center gap-3 border-t border-border-subtle bg-card py-3 pr-4 pl-10"
331 >
332 <ProjectFavicon
333 environmentId={project.environmentId}
334 size={18}
335 projectTitle={project.title}
336 workspaceRoot={project.workspaceRoot}
337 />
338 <View className="min-w-0 flex-1">
339 <Text className="text-sm font-t3-bold text-foreground">
340 {project.title}
341 </Text>
342 <Text
343 className="text-xs text-foreground-muted"
344 ellipsizeMode="middle"
345 numberOfLines={1}
346 >
347 {project.workspaceRoot}
348 </Text>
349 </View>
350 <SymbolView
351 name="chevron.right"
352 size={14}
353 tintColor={chevronColor}
354 type="monochrome"
355 />
356 </Pressable>
357 ))
358 : null}
359 </View>
360 );
361 })}
362 </View>
363 )}
364 </ScrollView>
365 </View>
366 );