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

NewTaskRouteScreen.tsx

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