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