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

NewTaskRouteScreen.tsx

545 lines21.1 KB

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