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 hideBottomBorder
102 onBack={() => navigation.goBack()}
103 actions={[
104 ...(Platform.OS === "ios" && layout.usesSplitView
105 ? [
106 {
107 accessibilityLabel: "Close new task",
108 icon: "xmark" as const,
109 onPress: () => navigation.goBack(),
110 },
111 ]
112 : []),
113 ...(props.canAddProject
114 ? [
115 {
116 accessibilityLabel: "Add project",
117 icon: "plus" as const,
118 onPress: () => navigation.dispatch(StackActions.push("AddProject")),
119 },
120 ]
121 : []),
122 ]}
123 search={{
124 value: props.searchText,
125 onChangeText: props.onSearchTextChange,
126 placeholder: "Search projects",
127 }}
128 />
129 );
130}
131
132export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
133 const projects = useProjects();
134 const [searchText, setSearchText] = useState("");
135 const { projectScopes, selectedEnvironmentId, setProject } = useNewTaskFlow();
136 const { state: catalogState } = useWorkspaceState();
137 const navigation = useNavigation();
138 const isFocused = useIsFocused();
139 const insets = useSafeAreaInsets();
140 const { getShare, releaseShareReservation } = useIncomingShare();
141 const routeShareId = Array.isArray(route.params?.incomingShareId)
142 ? route.params.incomingShareId[0]
143 : route.params?.incomingShareId;
144 const incomingShare = routeShareId ? getShare(routeShareId) : null;
145 const incomingShareSubtitle = incomingShare
146 ? incomingShare.attachments.length === 0
147 ? "Choose a project for what you shared"
148 : incomingShare.attachments.length === 1
149 ? `Choose a project for the ${incomingShare.attachments[0]?.type === "image" ? "image" : "file"} you shared`
150 : `Choose a project for the ${incomingShare.attachments.length} ${incomingShare.attachments.every((attachment) => attachment.type === "image") ? "images" : "files"} you shared`
151 : null;
152 const screenTitle = incomingShare ? "Start a task" : "Choose project";
153 const projectEmptyState = deriveProjectEmptyState(catalogState);
154 const visibleScopes = filterProjectScopes(projectScopes, searchText);
155 const resumedDestinationKeyRef = useRef<string | null>(null);
156 const reservedDestinationProject = incomingShare?.destination
157 ? (projects.find(
158 (project) =>
159 project.environmentId === incomingShare.destination?.environmentId &&
160 project.id === incomingShare.destination?.projectId,
161 ) ?? null)
162 : null;
163
164 async function selectProject(project: EnvironmentProject): Promise<void> {
165 if (incomingShare?.destination && !reservedDestinationProject) {
166 try {
167 await releaseShareReservation(incomingShare.id, incomingShare.destination);
168 } catch (error) {
169 Alert.alert(
170 "Could not change project",
171 error instanceof Error
172 ? error.message
173 : "The shared content reservation could not be updated.",
174 );
175 return;
176 }
177 }
178 const state = navigation.getState();
179 const previousRoute = state?.routes[state.index - 1];
180 if (previousRoute?.name === "NewTaskDraft") {
181 setProject(project);
182 navigation.goBack();
183 return;
184 }
185
186 navigation.dispatch(
187 StackActions.push("NewTaskDraft", {
188 environmentId: project.environmentId,
189 projectId: project.id,
190 title: project.title,
191 incomingShareId: incomingShare?.id,
192 }),
193 );
194 }
195
196 useEffect(() => {
197 const destination = incomingShare?.destination;
198 if (!destination) {
199 resumedDestinationKeyRef.current = null;
200 return;
201 }
202 if (!isFocused) {
203 // Returning from the reserved draft is a fresh resume attempt. Keeping
204 // this latch set would leave every project row disabled with no route.
205 resumedDestinationKeyRef.current = null;
206 return;
207 }
208 const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`;
209 if (resumedDestinationKeyRef.current === destinationKey) {
210 return;
211 }
212 if (!reservedDestinationProject) {
213 return;
214 }
215 resumedDestinationKeyRef.current = destinationKey;
216 navigation.dispatch(
217 StackActions.push("NewTaskDraft", {
218 environmentId: reservedDestinationProject.environmentId,
219 projectId: reservedDestinationProject.id,
220 title: reservedDestinationProject.title,
221 incomingShareId: incomingShare.id,
222 }),
223 );
224 }, [incomingShare, isFocused, navigation, reservedDestinationProject]);
225
226 return (
227 <View collapsable={false} className="flex-1 bg-sheet">
228 <NewTaskHeader
229 title={screenTitle}
230 subtitle={incomingShareSubtitle}
231 canAddProject={catalogState.hasReadyEnvironment}
232 searchText={searchText}
233 onSearchTextChange={setSearchText}
234 />
235
236 <MaterialScreenContent>
237 <ScrollView
238 contentInsetAdjustmentBehavior="automatic"
239 showsVerticalScrollIndicator={false}
240 keyboardShouldPersistTaps="handled"
241 keyboardDismissMode="on-drag"
242 className="flex-1"
243 contentContainerStyle={{
244 gap: Platform.OS === "android" ? 8 : 12,
245 paddingBottom: Math.max(insets.bottom, 18) + 18,
246 paddingHorizontal: Platform.OS === "android" ? 16 : 20,
247 paddingTop: Platform.OS === "android" ? 16 : 8,
248 ...(Platform.OS === "android" && visibleScopes.length === 0
249 ? { flexGrow: 1, justifyContent: "center" as const }
250 : {}),
251 }}
252 >
253 {projectScopes.length === 0 ? (
254 <View
255 collapsable={false}
256 className={cn(
257 "items-center gap-3 px-6 py-8",
258 Platform.OS !== "android" && "rounded-[24px] bg-card",
259 )}
260 >
261 {projectEmptyState.loading ? (
262 <ActivityIndicator colorClassName="accent-icon-muted" />
263 ) : null}
264 <Text className="text-center text-lg font-t3-bold text-foreground">
265 {projectEmptyState.title}
266 </Text>
267 <Text className="text-center text-sm leading-normal text-foreground-muted">
268 {projectEmptyState.detail}
269 </Text>
270 {Platform.OS === "android" ? (
271 <MaterialButton
272 label={catalogState.hasReadyEnvironment ? "Add new project" : "Add environment"}
273 tone="primary"
274 onPress={() =>
275 catalogState.hasReadyEnvironment
276 ? navigation.dispatch(StackActions.push("AddProject"))
277 : navigation.navigate("ConnectionsNew")
278 }
279 />
280 ) : !catalogState.hasReadyEnvironment ? (
281 <Pressable
282 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
283 onPress={() => navigation.navigate("ConnectionsNew")}
284 >
285 <Text className="text-sm font-t3-bold text-primary-foreground">
286 Add environment
287 </Text>
288 </Pressable>
289 ) : (
290 <Pressable
291 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
292 onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
293 >
294 <Text className="text-sm font-t3-bold text-primary-foreground">
295 Add new project
296 </Text>
297 </Pressable>
298 )}
299 </View>
300 ) : visibleScopes.length === 0 ? (
301 <View className="items-center gap-2 px-6 py-8">
302 <Text className="text-center text-lg font-t3-bold text-foreground">
303 No matching projects
304 </Text>
305 <Text className="text-center text-sm leading-normal text-foreground-muted">
306 Try a different project name or workspace path.
307 </Text>
308 </View>
309 ) : (
310 <View
311 collapsable={false}
312 className={
313 Platform.OS === "android"
314 ? "overflow-hidden rounded-[28px] bg-card"
315 : "overflow-hidden rounded-[24px] bg-card"
316 }
317 >
318 {visibleScopes.map((scope, scopeIndex) => {
319 const hasMultipleProjects = scope.projects.length > 1;
320 const selectionTarget = getProjectScopeSelectionTarget(
321 scope,
322 selectedEnvironmentId,
323 );
324 if (Platform.OS === "android") {
325 return (
326 <MaterialListRow
327 key={scope.key}
328 title={scope.title}
329 subtitle={
330 hasMultipleProjects
331 ? `${scope.projects.length} workspaces`
332 : selectionTarget.workspaceRoot
333 }
334 disabled={reservedDestinationProject !== null}
335 onPress={() => void selectProject(selectionTarget)}
336 leading={
337 <ProjectFavicon
338 environmentId={scope.representative.environmentId}
339 faviconPath={scope.representative.faviconPath}
340 size={24}
341 projectTitle={scope.title}
342 workspaceRoot={scope.representative.workspaceRoot}
343 />
344 }
345 />
346 );
347 }
348 return (
349 <View
350 key={scope.key}
351 className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
352 >
353 <Pressable
354 accessibilityRole="button"
355 accessibilityLabel={scope.title}
356 disabled={reservedDestinationProject !== null}
357 onPress={() => void selectProject(selectionTarget)}
358 className="flex-row items-center gap-3 bg-card px-4 py-3.5"
359 >
360 <View className="h-7 w-7 items-center justify-center">
361 <ProjectFavicon
362 environmentId={scope.representative.environmentId}
363 faviconPath={scope.representative.faviconPath}
364 size={20}
365 projectTitle={scope.title}
366 workspaceRoot={scope.representative.workspaceRoot}
367 />
368 </View>
369 <View className="min-w-0 flex-1">
370 <Text className={cn("text-base leading-snug", "font-t3-bold")}>
371 {scope.title}
372 </Text>
373 <Text
374 className="text-xs leading-snug text-foreground-muted"
375 ellipsizeMode="middle"
376 numberOfLines={1}
377 >
378 {hasMultipleProjects
379 ? `${scope.projects.length} workspaces`
380 : selectionTarget.workspaceRoot}
381 </Text>
382 </View>
383 <SymbolView
384 name="chevron.right"
385 size={14}
386 tintColorClassName="accent-chevron"
387 type="monochrome"
388 />
389 </Pressable>
390 </View>
391 );
392 })}
393 </View>
394 )}
395 </ScrollView>
396 </MaterialScreenContent>
397 </View>
398 );
399}