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