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

NewTaskRouteScreen.tsx

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