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

NewTaskRouteScreen.tsx

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