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

NewTaskRouteScreen.tsx

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