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