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 type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
11import { useEffect, useRef, useState } from "react";
12import { ActivityIndicator, Alert, Platform, Pressable, View } from "react-native";
13import { useSafeAreaInsets } from "react-native-safe-area-context";
14import { cn } from "../../lib/cn";
15import { MaterialScreenContent } from "../../components/MaterialScreenContent";
16import { MaterialButton } from "../../components/MaterialButton";
17import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
18import { AppText as Text } from "../../components/AppText";
19import { ProjectFavicon } from "../../components/ProjectFavicon";
20import { useProjects } from "../../state/entities";
21import type { WorkspaceState } from "../../state/workspaceModel";
22import { useWorkspaceState } from "../../state/workspace";
23import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
24import { useIncomingShare } from "../sharing/IncomingShareProvider";
25import { useNewTaskFlow } from "./new-task-flow-provider";
26import { filterProjectScopes, getProjectScopeSelectionTarget } from "./new-task-project-selection";
27
28type NewTaskRouteParams = {
29 readonly incomingShareId?: string | string[];
30};
31
32function deriveProjectEmptyState(catalogState: WorkspaceState): {
33 readonly title: string;
34 readonly detail: string;
35 readonly loading: boolean;
36} {
37 if (catalogState.isLoadingConnections) {
38 return {
39 title: "Loading environments",
40 detail: "Checking saved environments on this device.",
41 loading: true,
42 };
43 }
44
45 if (!catalogState.hasConnections) {
46 return {
47 title: "No environments connected",
48 detail: "Add an environment before creating a task.",
49 loading: false,
50 };
51 }
52
53 if (
54 (catalogState.connectionState === "available" ||
55 catalogState.connectionState === "offline" ||
56 catalogState.connectionState === "error") &&
57 !catalogState.hasLoadedShellSnapshot
58 ) {
59 return {
60 title: "Environment unavailable",
61 detail:
62 catalogState.connectionError ??
63 "The saved environment is offline. Check the URL or start the environment, then retry.",
64 loading: false,
65 };
66 }
67
68 if (
69 catalogState.hasConnectingEnvironment &&
70 !catalogState.hasLoadedShellSnapshot &&
71 catalogState.connectionError === null
72 ) {
73 return {
74 title: "Connecting to environment",
75 detail: "Loading projects from the saved environment.",
76 loading: true,
77 };
78 }
79
80 return {
81 title: "No projects found",
82 detail: "The connected environment did not report any projects.",
83 loading: false,
84 };
85}
86
87function NewTaskHeader(props: {
88 readonly title: string;
89 readonly subtitle: string | null;
90 readonly canAddProject: boolean;
91 readonly searchText: string;
92 readonly onSearchTextChange: (text: string) => void;
93}) {
94 const navigation = useNavigation();
95 const { layout } = useAdaptiveWorkspaceLayout();
96 return (
97 <ScreenHeader
98 title={props.title}
99 subtitle={props.subtitle ?? undefined}
100 sidebar={false}
101 backInSplitView={{
102 accessibilityLabel: "Go back",
103 icon: "chevron.left",
104 }}
105 options={{ headerBackVisible: !layout.usesSplitView }}
106 hideBottomBorder
107 onBack={() => navigation.goBack()}
108 actions={
109 props.canAddProject
110 ? [
111 {
112 accessibilityLabel: "Add project",
113 icon: "plus",
114 onPress: () => navigation.dispatch(StackActions.push("AddProject")),
115 },
116 ]
117 : []
118 }
119 search={{
120 value: props.searchText,
121 onChangeText: props.onSearchTextChange,
122 placeholder: "Search projects",
123 }}
124 />
125 );
126}
127
128export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
129 const projects = useProjects();
130 const [searchText, setSearchText] = useState("");
131 const { projectScopes, selectedEnvironmentId, setProject } = useNewTaskFlow();
132 const { state: catalogState } = useWorkspaceState();
133 const navigation = useNavigation();
134 const isFocused = useIsFocused();
135 const insets = useSafeAreaInsets();
136 const { getShare, releaseShareReservation } = useIncomingShare();
137 const routeShareId = Array.isArray(route.params?.incomingShareId)
138 ? route.params.incomingShareId[0]
139 : route.params?.incomingShareId;
140 const incomingShare = routeShareId ? getShare(routeShareId) : null;
141 const incomingShareSubtitle = incomingShare
142 ? incomingShare.attachments.length === 0
143 ? "Choose a project for what you shared"
144 : incomingShare.attachments.length === 1
145 ? `Choose a project for the ${incomingShare.attachments[0]?.type === "image" ? "image" : "file"} you shared`
146 : `Choose a project for the ${incomingShare.attachments.length} ${incomingShare.attachments.every((attachment) => attachment.type === "image") ? "images" : "files"} you shared`
147 : null;
148 const screenTitle = incomingShare ? "Start a task" : "Choose project";
149 const projectEmptyState = deriveProjectEmptyState(catalogState);
150 const visibleScopes = filterProjectScopes(projectScopes, searchText);
151 const resumedDestinationKeyRef = useRef<string | null>(null);
152 const reservedDestinationProject = incomingShare?.destination
153 ? (projects.find(
154 (project) =>
155 project.environmentId === incomingShare.destination?.environmentId &&
156 project.id === incomingShare.destination?.projectId,
157 ) ?? null)
158 : null;
159
160 async function selectProject(project: EnvironmentProject): Promise<void> {
161 if (incomingShare?.destination && !reservedDestinationProject) {
162 try {
163 await releaseShareReservation(incomingShare.id, incomingShare.destination);
164 } catch (error) {
165 Alert.alert(
166 "Could not change project",
167 error instanceof Error
168 ? error.message
169 : "The shared content reservation could not be updated.",
170 );
171 return;
172 }
173 }
174 const state = navigation.getState();
175 const previousRoute = state?.routes[state.index - 1];
176 if (previousRoute?.name === "NewTaskDraft") {
177 setProject(project);
178 navigation.goBack();
179 return;
180 }
181
182 navigation.dispatch(
183 StackActions.push("NewTaskDraft", {
184 environmentId: project.environmentId,
185 projectId: project.id,
186 title: project.title,
187 incomingShareId: incomingShare?.id,
188 }),
189 );
190 }
191
192 useEffect(() => {
193 const destination = incomingShare?.destination;
194 if (!destination) {
195 resumedDestinationKeyRef.current = null;
196 return;
197 }
198 if (!isFocused) {
199 // Returning from the reserved draft is a fresh resume attempt. Keeping
200 // this latch set would leave every project row disabled with no route.
201 resumedDestinationKeyRef.current = null;
202 return;
203 }
204 const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`;
205 if (resumedDestinationKeyRef.current === destinationKey) {
206 return;
207 }
208 if (!reservedDestinationProject) {
209 return;
210 }
211 resumedDestinationKeyRef.current = destinationKey;
212 navigation.dispatch(
213 StackActions.push("NewTaskDraft", {
214 environmentId: reservedDestinationProject.environmentId,
215 projectId: reservedDestinationProject.id,
216 title: reservedDestinationProject.title,
217 incomingShareId: incomingShare.id,
218 }),
219 );
220 }, [incomingShare, isFocused, navigation, reservedDestinationProject]);
221
222 return (
223 <View collapsable={false} className="flex-1 bg-sheet">
224 <NewTaskHeader
225 title={screenTitle}
226 subtitle={incomingShareSubtitle}
227 canAddProject={catalogState.hasReadyEnvironment}
228 searchText={searchText}
229 onSearchTextChange={setSearchText}
230 />
231
232 <MaterialScreenContent>
233 <ScrollView
234 contentInsetAdjustmentBehavior="automatic"
235 showsVerticalScrollIndicator={false}
236 keyboardShouldPersistTaps="handled"
237 keyboardDismissMode="on-drag"
238 className="flex-1"
239 contentContainerStyle={{
240 gap: Platform.OS === "android" ? 8 : 12,
241 paddingBottom: Math.max(insets.bottom, 18) + 18,
242 paddingHorizontal: Platform.OS === "android" ? 16 : 20,
243 paddingTop: Platform.OS === "android" ? 16 : 8,
244 ...(Platform.OS === "android" && visibleScopes.length === 0
245 ? { flexGrow: 1, justifyContent: "center" as const }
246 : {}),
247 }}
248 >
249 {projectScopes.length === 0 ? (
250 <View
251 collapsable={false}
252 className={cn(
253 "items-center gap-3 px-6 py-8",
254 Platform.OS !== "android" && "rounded-[24px] bg-card",
255 )}
256 >
257 {projectEmptyState.loading ? (
258 <ActivityIndicator colorClassName="accent-icon-muted" />
259 ) : null}
260 <Text className="text-center text-lg font-t3-bold text-foreground">
261 {projectEmptyState.title}
262 </Text>
263 <Text className="text-center text-sm leading-normal text-foreground-muted">
264 {projectEmptyState.detail}
265 </Text>
266 {Platform.OS === "android" ? (
267 <MaterialButton
268 label={catalogState.hasReadyEnvironment ? "Add new project" : "Add environment"}
269 tone="primary"
270 onPress={() =>
271 catalogState.hasReadyEnvironment
272 ? navigation.dispatch(StackActions.push("AddProject"))
273 : navigation.navigate("ConnectionsNew")
274 }
275 />
276 ) : !catalogState.hasReadyEnvironment ? (
277 <Pressable
278 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
279 onPress={() => navigation.navigate("ConnectionsNew")}
280 >
281 <Text className="text-sm font-t3-bold text-primary-foreground">
282 Add environment
283 </Text>
284 </Pressable>
285 ) : (
286 <Pressable
287 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
288 onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
289 >
290 <Text className="text-sm font-t3-bold text-primary-foreground">
291 Add new project
292 </Text>
293 </Pressable>
294 )}
295 </View>
296 ) : visibleScopes.length === 0 ? (
297 <View className="items-center gap-2 px-6 py-8">
298 <Text className="text-center text-lg font-t3-bold text-foreground">
299 No matching projects
300 </Text>
301 <Text className="text-center text-sm leading-normal text-foreground-muted">
302 Try a different project name or workspace path.
303 </Text>
304 </View>
305 ) : (
306 <View
307 collapsable={false}
308 className={
309 Platform.OS === "android"
310 ? "overflow-hidden rounded-[28px] bg-card"
311 : "overflow-hidden rounded-[24px] bg-card"
312 }
313 >
314 {visibleScopes.map((scope, scopeIndex) => {
315 const hasMultipleProjects = scope.projects.length > 1;
316 const selectionTarget = getProjectScopeSelectionTarget(
317 scope,
318 selectedEnvironmentId,
319 );
320 if (Platform.OS === "android") {
321 return (
322 <MaterialListRow
323 key={scope.key}
324 title={scope.title}
325 subtitle={
326 hasMultipleProjects
327 ? `${scope.projects.length} workspaces`
328 : selectionTarget.workspaceRoot
329 }
330 disabled={reservedDestinationProject !== null}
331 onPress={() => void selectProject(selectionTarget)}
332 leading={
333 <ProjectFavicon
334 environmentId={scope.representative.environmentId}
335 faviconPath={scope.representative.faviconPath}
336 projectIcon={scope.representative.projectIcon}
337 size={24}
338 projectTitle={scope.title}
339 workspaceRoot={scope.representative.workspaceRoot}
340 />
341 }
342 />
343 );
344 }
345 return (
346 <View
347 key={scope.key}
348 className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
349 >
350 <Pressable
351 accessibilityRole="button"
352 accessibilityLabel={scope.title}
353 disabled={reservedDestinationProject !== null}
354 onPress={() => void selectProject(selectionTarget)}
355 className="flex-row items-center gap-3 bg-card px-4 py-3.5"
356 >
357 <View className="h-7 w-7 items-center justify-center">
358 <ProjectFavicon
359 environmentId={scope.representative.environmentId}
360 faviconPath={scope.representative.faviconPath}
361 projectIcon={scope.representative.projectIcon}
362 size={20}
363 projectTitle={scope.title}
364 workspaceRoot={scope.representative.workspaceRoot}
365 />
366 </View>
367 <View className="min-w-0 flex-1">
368 <Text className={cn("text-base leading-snug", "font-t3-bold")}>
369 {scope.title}
370 </Text>
371 <Text
372 className="text-xs leading-snug text-foreground-muted"
373 ellipsizeMode="middle"
374 numberOfLines={1}
375 >
376 {hasMultipleProjects
377 ? `${scope.projects.length} workspaces`
378 : selectionTarget.workspaceRoot}
379 </Text>
380 </View>
381 <SymbolView
382 name="chevron.right"
383 size={14}
384 tintColorClassName="accent-chevron"
385 type="monochrome"
386 />
387 </Pressable>
388 </View>
389 );
390 })}
391 </View>
392 )}
393 </ScrollView>
394 </MaterialScreenContent>
395 </View>
396 );
397}