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

NewTaskRouteScreen.tsx

585 lines22.2 KB

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