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

NewTaskRouteScreen.tsx

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