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

NewTaskRouteScreen.tsx

533 lines20.6 KB

1import { MaterialListRow } from "../../components/MaterialListRow";
2import { ScreenHeader } from "../../components/ScreenHeader";
3import {
4 StackActions,
5 useIsFocused,
6 useNavigation,
7 type StaticScreenProps,
8} from "@react-navigation/native";
9import { SymbolView } from "../../components/AppSymbol";
10import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
11import { isScratchProject } from "@t3tools/client-runtime/state/projects";
12import {
13 isAtomCommandInterrupted,
14 squashAtomCommandFailure,
15} from "@t3tools/client-runtime/state/runtime";
16import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
17import { useEffect, useRef, useState } from "react";
18import { ActivityIndicator, Alert, Platform, Pressable, View } from "react-native";
19import { useSafeAreaInsets } from "react-native-safe-area-context";
20import { cn } from "../../lib/cn";
21import { MaterialScreenContent } from "../../components/MaterialScreenContent";
22import { MaterialButton } from "../../components/MaterialButton";
23import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
24import { AppText as Text } from "../../components/AppText";
25import { ProjectFavicon } from "../../components/ProjectFavicon";
26import { useProjects, useServerConfigs } from "../../state/entities";
27import { projectEnvironment } from "../../state/projects";
28import { useAtomCommand } from "../../state/use-atom-command";
29import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
30import type { WorkspaceState } from "../../state/workspaceModel";
31import { useWorkspaceState } from "../../state/workspace";
32import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
33import { useIncomingShare } from "../sharing/IncomingShareProvider";
34import { useNewTaskFlow } from "./new-task-flow-provider";
35import { filterProjectScopes, getProjectScopeSelectionTarget } from "./new-task-project-selection";
36​
37type NewTaskRouteParams = {
38 readonly incomingShareId?: string | string[];
39};
40​
41function deriveProjectEmptyState(catalogState: WorkspaceState): {
42 readonly title: string;
43 readonly detail: string;
44 readonly loading: boolean;
45} {
46 if (catalogState.isLoadingConnections) {
47 return {
48 title: "Loading environments",
49 detail: "Checking saved environments on this device.",
50 loading: true,
51 };
52 }
53​
54 if (!catalogState.hasConnections) {
55 return {
56 title: "No environments connected",
57 detail: "Add an environment before creating a task.",
58 loading: false,
59 };
60 }
61​
62 if (
63 (catalogState.connectionState === "available" ||
64 catalogState.connectionState === "offline" ||
65 catalogState.connectionState === "error") &&
66 !catalogState.hasLoadedShellSnapshot
67 ) {
68 return {
69 title: "Environment unavailable",
70 detail:
71 catalogState.connectionError ??
72 "The saved environment is offline. Check the URL or start the environment, then retry.",
73 loading: false,
74 };
75 }
76​
77 if (
78 catalogState.hasConnectingEnvironment &&
79 !catalogState.hasLoadedShellSnapshot &&
80 catalogState.connectionError === null
81 ) {
82 return {
83 title: "Connecting to environment",
84 detail: "Loading projects from the saved environment.",
85 loading: true,
86 };
87 }
88​
89 return {
90 title: "No projects found",
91 detail: "The connected environment did not report any projects.",
92 loading: false,
93 };
95​
96function NewTaskHeader(props: {
97 readonly title: string;
98 readonly subtitle: string | null;
99 readonly canAddProject: boolean;
100 readonly searchText: string;
101 readonly onSearchTextChange: (text: string) => void;
102}) {
103 const navigation = useNavigation();
104 const { layout } = useAdaptiveWorkspaceLayout();
105 return (
106 <ScreenHeader
107 title={props.title}
108 subtitle={props.subtitle ?? undefined}
109 sidebar={false}
110 backInSplitView={{
111 accessibilityLabel: "Go back",
112 icon: "chevron.left",
113 }}
114 options={{ headerBackVisible: !layout.usesSplitView }}
115 hideBottomBorder
116 onBack={() => navigation.goBack()}
117 actions={
118 props.canAddProject
119 ? [
120 {
121 accessibilityLabel: "Add project",
122 icon: "plus",
123 onPress: () => navigation.dispatch(StackActions.push("AddProject")),
124 },
125 ]
126 : []
127 }
128 search={{
129 value: props.searchText,
130 onChangeText: props.onSearchTextChange,
131 placeholder: "Search projects",
132 }}
133 />
134 );
136​
137export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
138 const projects = useProjects();
139 const [searchText, setSearchText] = useState("");
140 const { projectScopes, selectedEnvironmentId, setProject } = useNewTaskFlow();
141 const { state: catalogState } = useWorkspaceState();
142 const navigation = useNavigation();
143 const isFocused = useIsFocused();
144 const insets = useSafeAreaInsets();
145 const { getShare, releaseShareReservation } = useIncomingShare();
146 const routeShareId = Array.isArray(route.params?.incomingShareId)
147 ? route.params.incomingShareId[0]
148 : route.params?.incomingShareId;
149 const incomingShare = routeShareId ? getShare(routeShareId) : null;
150 const incomingShareSubtitle = incomingShare
151 ? incomingShare.attachments.length === 0
152 ? "Choose a project for what you shared"
153 : incomingShare.attachments.length === 1
154 ? `Choose a project for the ${incomingShare.attachments[0]?.type === "image" ? "image" : "file"} you shared`
155 : `Choose a project for the ${incomingShare.attachments.length} ${incomingShare.attachments.every((attachment) => attachment.type === "image") ? "images" : "files"} you shared`
156 : null;
157 const screenTitle = incomingShare ? "Start a task" : "Choose project";
158 const projectEmptyState = deriveProjectEmptyState(catalogState);
159 const serverConfigs = useServerConfigs();
160 // Scratch projects are reached through the No project row, never as rows
161 // of their own.
162 const listScopes = projectScopes.filter(
163 (scope) =>
164 !scope.projects.every((project) =>
165 isScratchProject(project, serverConfigs.get(project.environmentId)?.scratchWorkspaceRoot),
166 ),
167 );
168 const visibleScopes = filterProjectScopes(listScopes, searchText);
169 const resumedDestinationKeyRef = useRef<string | null>(null);
170 const reservedDestinationProject = incomingShare?.destination
171 ? (projects.find(
172 (project) =>
173 project.environmentId === incomingShare.destination?.environmentId &&
174 project.id === incomingShare.destination?.projectId,
175 ) ?? null)
176 : null;
177 const { connectedEnvironments } = useRemoteConnectionStatus();
178 const openScratch = useAtomCommand(projectEnvironment.openScratch, {
179 reportFailure: false,
180 });
181 // Threads without a project need a connected environment that offers them.
182 // The row starts on the selected environment when it has one, otherwise the
183 // first that does; the draft page's machine picker moves it from there.
184 const scratchEnvironments = connectedEnvironments.filter(
185 (environment) =>
186 availableScratchWorkspaceRoot(
187 environment.connectionState,
188 serverConfigs.get(environment.environmentId),
189 ) !== null,
190 );
191 const scratchEnvironment =
192 scratchEnvironments.find(
193 (environment) => environment.environmentId === selectedEnvironmentId,
194 ) ??
195 scratchEnvironments[0] ??
196 null;
197 const canStartScratch = scratchEnvironment !== null && reservedDestinationProject === null;
198 const scratchStartInFlightRef = useRef(false);
199​
200 async function selectProject(project: EnvironmentProject): Promise<void> {
201 if (incomingShare?.destination && !reservedDestinationProject) {
202 try {
203 await releaseShareReservation(incomingShare.id, incomingShare.destination);
204 } catch (error) {
205 Alert.alert(
206 "Could not change project",
207 error instanceof Error
208 ? error.message
209 : "The shared content reservation could not be updated.",
210 );
211 return;
212 }
213 }
214 const state = navigation.getState();
215 const previousRoute = state?.routes[state.index - 1];
216 if (previousRoute?.name === "NewTaskDraft") {
217 setProject(project);
218 navigation.goBack();
219 return;
220 }
221​
222 navigation.dispatch(
223 StackActions.push("NewTaskDraft", {
224 environmentId: project.environmentId,
225 projectId: project.id,
226 title: project.title,
227 incomingShareId: incomingShare?.id,
228 }),
229 );
230 }
231​
232 async function startScratch(): Promise<void> {
233 if (!scratchEnvironment || scratchStartInFlightRef.current) return;
234 const environmentId = scratchEnvironment.environmentId;
235 scratchStartInFlightRef.current = true;
236 try {
237 const result = await openScratch({ environmentId, input: {} });
238 if (result._tag === "Failure") {
239 if (!isAtomCommandInterrupted(result)) {
240 const error = squashAtomCommandFailure(result);
241 Alert.alert(
242 "Could not start without a project",
243 error instanceof Error
244 ? error.message
245 : "The folder for threads without a project could not be created.",
246 );
247 }
248 return;
249 }
250 await selectProject(result.value);
251 } finally {
252 scratchStartInFlightRef.current = false;
253 }
254 }
255​
256 useEffect(() => {
257 const destination = incomingShare?.destination;
258 if (!destination) {
259 resumedDestinationKeyRef.current = null;
260 return;
261 }
262 if (!isFocused) {
263 // Returning from the reserved draft is a fresh resume attempt. Keeping
264 // this latch set would leave every project row disabled with no route.
265 resumedDestinationKeyRef.current = null;
266 return;
267 }
268 const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`;
269 if (resumedDestinationKeyRef.current === destinationKey) {
270 return;
271 }
272 if (!reservedDestinationProject) {
273 return;
274 }
275 resumedDestinationKeyRef.current = destinationKey;
276 navigation.dispatch(
277 StackActions.push("NewTaskDraft", {
278 environmentId: reservedDestinationProject.environmentId,
279 projectId: reservedDestinationProject.id,
280 title: reservedDestinationProject.title,
281 incomingShareId: incomingShare.id,
282 }),
283 );
284 }, [incomingShare, isFocused, navigation, reservedDestinationProject]);
285​
286 return (
287 <View collapsable={false} className="flex-1 bg-sheet">
288 <NewTaskHeader
289 title={screenTitle}
290 subtitle={incomingShareSubtitle}
291 canAddProject={catalogState.hasReadyEnvironment}
292 searchText={searchText}
293 onSearchTextChange={setSearchText}
294 />
295​
296 <MaterialScreenContent>
297 <ScrollView
298 contentInsetAdjustmentBehavior="automatic"
299 showsVerticalScrollIndicator={false}
300 keyboardShouldPersistTaps="handled"
301 keyboardDismissMode="on-drag"
302 className="flex-1"
303 contentContainerStyle={{
304 gap: Platform.OS === "android" ? 8 : 12,
305 paddingBottom: Math.max(insets.bottom, 18) + 18,
306 paddingHorizontal: Platform.OS === "android" ? 16 : 20,
307 paddingTop: Platform.OS === "android" ? 16 : 8,
308 ...(Platform.OS === "android" && visibleScopes.length === 0
309 ? { flexGrow: 1, justifyContent: "center" as const }
310 : {}),
311 }}
312 >
313 {canStartScratch && listScopes.length > 0 ? (
314 Platform.OS === "android" ? (
315 <View collapsable={false} className="overflow-hidden rounded-[28px] bg-grouped-card">
316 <MaterialListRow
317 className="bg-grouped-card"
318 title="No project"
319 subtitle="Start a task without a project"
320 onPress={() => void startScratch()}
321 leading={
322 <SymbolView
323 name="text.bubble"
324 size={22}
325 tintColorClassName="accent-icon-muted"
326 type="monochrome"
327 />
328 }
329 />
330 </View>
331 ) : (
332 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-grouped-card">
333 <Pressable
334 accessibilityRole="button"
335 accessibilityLabel="No project"
336 onPress={() => void startScratch()}
337 className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5"
338 >
339 <View className="h-7 w-7 items-center justify-center">
340 <SymbolView
341 name="text.bubble"
342 size={18}
343 tintColorClassName="accent-icon-muted"
344 type="monochrome"
345 />
346 </View>
347 <View className="min-w-0 flex-1">
348 <Text className="text-base font-t3-bold leading-snug">No project</Text>
349 <Text className="text-xs leading-snug text-foreground-muted" numberOfLines={1}>
350 Start a task without a project
351 </Text>
352 </View>
353 <SymbolView
354 name="chevron.right"
355 size={14}
356 tintColorClassName="accent-chevron"
357 type="monochrome"
358 />
359 </Pressable>
360 </View>
361 )
362 ) : null}
363 {listScopes.length === 0 ? (
364 <View
365 collapsable={false}
366 className={cn(
367 "items-center gap-3 px-6 py-8",
368 Platform.OS !== "android" && "rounded-[24px] bg-grouped-card",
369 )}
370 >
371 {projectEmptyState.loading ? (
372 <ActivityIndicator colorClassName="accent-icon-muted" />
373 ) : null}
374 <Text className="text-center text-lg font-t3-bold text-foreground">
375 {projectEmptyState.title}
376 </Text>
377 <Text className="text-center text-sm leading-normal text-foreground-muted">
378 {projectEmptyState.detail}
379 </Text>
380 {Platform.OS === "android" ? (
381 <>
382 <MaterialButton
383 label={catalogState.hasReadyEnvironment ? "Add new project" : "Add environment"}
384 tone="primary"
385 onPress={() =>
386 catalogState.hasReadyEnvironment
387 ? navigation.dispatch(StackActions.push("AddProject"))
388 : navigation.navigate("ConnectionsNew")
389 }
390 />
391 {canStartScratch ? (
392 <MaterialButton
393 label="Start without a project"
394 tone="secondary"
395 onPress={() => void startScratch()}
396 />
397 ) : null}
398 </>
399 ) : !catalogState.hasReadyEnvironment ? (
400 <Pressable
401 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
402 onPress={() => navigation.navigate("ConnectionsNew")}
403 >
404 <Text className="text-sm font-t3-bold text-primary-foreground">
405 Add environment
406 </Text>
407 </Pressable>
408 ) : (
409 <>
410 <Pressable
411 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
412 onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
413 >
414 <Text className="text-sm font-t3-bold text-primary-foreground">
415 Add new project
416 </Text>
417 </Pressable>
418 {canStartScratch ? (
419 <Pressable
420 className="rounded-full bg-subtle px-4 py-2.5 active:opacity-70"
421 onPress={() => void startScratch()}
422 >
423 <Text className="text-sm font-t3-bold text-foreground">
424 Start without a project
425 </Text>
426 </Pressable>
427 ) : null}
428 </>
429 )}
430 </View>
431 ) : visibleScopes.length === 0 ? (
432 <View className="items-center gap-2 px-6 py-8">
433 <Text className="text-center text-lg font-t3-bold text-foreground">
434 No matching projects
435 </Text>
436 <Text className="text-center text-sm leading-normal text-foreground-muted">
437 Try a different project name or workspace path.
438 </Text>
439 </View>
440 ) : (
441 <View
442 collapsable={false}
443 className={
444 Platform.OS === "android"
445 ? "overflow-hidden rounded-[28px] bg-grouped-card"
446 : "overflow-hidden rounded-[24px] bg-grouped-card"
447 }
448 >
449 {visibleScopes.map((scope, scopeIndex) => {
450 const hasMultipleProjects = scope.projects.length > 1;
451 const selectionTarget = getProjectScopeSelectionTarget(
452 scope,
453 selectedEnvironmentId,
454 );
455 if (Platform.OS === "android") {
456 return (
457 <MaterialListRow
458 className="bg-grouped-card"
459 key={scope.key}
460 title={scope.title}
461 subtitle={
462 hasMultipleProjects
463 ? `${scope.projects.length} workspaces`
464 : selectionTarget.workspaceRoot
465 }
466 disabled={reservedDestinationProject !== null}
467 onPress={() => void selectProject(selectionTarget)}
468 leading={
469 <ProjectFavicon
470 environmentId={scope.representative.environmentId}
471 faviconPath={scope.representative.faviconPath}
472 projectIcon={scope.representative.projectIcon}
473 size={24}
474 projectTitle={scope.title}
475 workspaceRoot={scope.representative.workspaceRoot}
476 />
477 }
478 />
479 );
480 }
481 return (
482 <View
483 key={scope.key}
484 className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
485 >
486 <Pressable
487 accessibilityRole="button"
488 accessibilityLabel={scope.title}
489 disabled={reservedDestinationProject !== null}
490 onPress={() => void selectProject(selectionTarget)}
491 className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5"
492 >
493 <View className="h-7 w-7 items-center justify-center">
494 <ProjectFavicon
495 environmentId={scope.representative.environmentId}
496 faviconPath={scope.representative.faviconPath}
497 projectIcon={scope.representative.projectIcon}
498 size={20}
499 projectTitle={scope.title}
500 workspaceRoot={scope.representative.workspaceRoot}
501 />
502 </View>
503 <View className="min-w-0 flex-1">
504 <Text className={cn("text-base leading-snug", "font-t3-bold")}>
505 {scope.title}
506 </Text>
507 <Text
508 className="text-xs leading-snug text-foreground-muted"
509 ellipsizeMode="middle"
510 numberOfLines={1}
511 >
512 {hasMultipleProjects
513 ? `${scope.projects.length} workspaces`
514 : selectionTarget.workspaceRoot}
515 </Text>
516 </View>
517 <SymbolView
518 name="chevron.right"
519 size={14}
520 tintColorClassName="accent-chevron"
521 type="monochrome"
522 />
523 </Pressable>
524 </View>
525 );
526 })}
527 </View>
528 )}
529 </ScrollView>
530 </MaterialScreenContent>
531 </View>
532 );