Open History to see the last commit
1import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
2import {
3 StackActions,
4 useIsFocused,
5 useNavigation,
6 type StaticScreenProps,
7} from "@react-navigation/native";
8import { SymbolView } from "../../components/AppSymbol";
9import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
10import { useEffect, useRef } from "react";
11import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
12import { useSafeAreaInsets } from "react-native-safe-area-context";
13import { useThemeColor } from "../../lib/useThemeColor";
14import { cn } from "../../lib/cn";
15
16import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
17import { AppText as Text } from "../../components/AppText";
18import { ProjectFavicon } from "../../components/ProjectFavicon";
19import { useProjects } from "../../state/entities";
20import type { WorkspaceState } from "../../state/workspaceModel";
21import { useWorkspaceState } from "../../state/workspace";
22import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
23import { useIncomingShare } from "../sharing/IncomingShareProvider";
24import { useNewTaskFlow } from "./new-task-flow-provider";
25import { getProjectScopeSelectionTarget } from "./new-task-project-selection";
26
27type NewTaskRouteParams = {
28 readonly incomingShareId?: string | string[];
29};
30
31function deriveProjectEmptyState(catalogState: WorkspaceState): {
32 readonly title: string;
33 readonly detail: string;
34 readonly loading: boolean;
35} {
36 if (catalogState.isLoadingConnections) {
37 return {
38 title: "Loading environments",
39 detail: "Checking saved environments on this device.",
40 loading: true,
41 };
42 }
43
44 if (!catalogState.hasConnections) {
45 return {
46 title: "No environments connected",
47 detail: "Add an environment before creating a task.",
48 loading: false,
49 };
50 }
51
52 if (
53 (catalogState.connectionState === "available" ||
54 catalogState.connectionState === "offline" ||
55 catalogState.connectionState === "error") &&
56 !catalogState.hasLoadedShellSnapshot
57 ) {
58 return {
59 title: "Environment unavailable",
60 detail:
61 catalogState.connectionError ??
62 "The saved environment is offline. Check the URL or start the environment, then retry.",
63 loading: false,
64 };
65 }
66
67 if (
68 catalogState.hasConnectingEnvironment &&
69 !catalogState.hasLoadedShellSnapshot &&
70 catalogState.connectionError === null
71 ) {
72 return {
73 title: "Connecting to environment",
74 detail: "Loading projects from the saved environment.",
75 loading: true,
76 };
77 }
78
79 return {
80 title: "No projects found",
81 detail: "The connected environment did not report any projects.",
82 loading: false,
83 };
84}
85
86export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
87 const projects = useProjects();
88 const { projectScopes, selectedEnvironmentId, setProject } = useNewTaskFlow();
89 const { state: catalogState } = useWorkspaceState();
90 const navigation = useNavigation();
91 const isFocused = useIsFocused();
92 const { layout } = useAdaptiveWorkspaceLayout();
93 const insets = useSafeAreaInsets();
94 const chevronColor = useThemeColor("--color-chevron");
95 const accentColor = useThemeColor("--color-icon-muted");
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 image you shared"
106 : `Choose a project for the ${incomingShare.attachments.length} images 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 subtitle={incomingShareSubtitle}
190 onBack={layout.usesSplitView ? () => navigation.goBack() : undefined}
191 actions={
192 catalogState.hasReadyEnvironment
193 ? [
194 {
195 accessibilityLabel: "Add project",
196 icon: "plus",
197 onPress: () => navigation.dispatch(StackActions.push("AddProject")),
198 },
199 ]
200 : []
201 }
202 />
203 </>
204 ) : (
205 <>
206 <NativeStackScreenOptions
207 options={{
208 title: screenTitle,
209 unstable_headerSubtitle: incomingShareSubtitle ?? undefined,
210 }}
211 />
212 <NativeHeaderToolbar placement="right">
213 {layout.usesSplitView ? (
214 <NativeHeaderToolbar.Button
215 accessibilityLabel="Close new task"
216 icon="xmark"
217 onPress={() => navigation.goBack()}
218 separateBackground
219 />
220 ) : null}
221 {catalogState.hasReadyEnvironment ? (
222 <NativeHeaderToolbar.Button
223 icon="plus"
224 onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
225 separateBackground
226 />
227 ) : null}
228 </NativeHeaderToolbar>
229 </>
230 )}
231
232 <ScrollView
233 contentInsetAdjustmentBehavior="automatic"
234 showsVerticalScrollIndicator={false}
235 className="flex-1"
236 contentContainerStyle={{
237 gap: 12,
238 paddingBottom: Math.max(insets.bottom, 18) + 18,
239 paddingHorizontal: 20,
240 paddingTop: 8,
241 }}
242 >
243 {projectScopes.length === 0 ? (
244 <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
245 {projectEmptyState.loading ? <ActivityIndicator color={accentColor} /> : null}
246 <Text className="text-center text-lg font-t3-bold text-foreground">
247 {projectEmptyState.title}
248 </Text>
249 <Text className="text-center text-sm leading-normal text-foreground-muted">
250 {projectEmptyState.detail}
251 </Text>
252 {!catalogState.hasReadyEnvironment ? (
253 <Pressable
254 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
255 onPress={() => navigation.navigate("ConnectionsNew")}
256 >
257 <Text className="text-sm font-t3-bold text-primary-foreground">
258 Add environment
259 </Text>
260 </Pressable>
261 ) : (
262 <Pressable
263 className="mt-1 rounded-full bg-primary px-4 py-2.5 active:opacity-70"
264 onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
265 >
266 <Text className="text-sm font-t3-bold text-primary-foreground">
267 Add new project
268 </Text>
269 </Pressable>
270 )}
271 </View>
272 ) : (
273 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
274 {projectScopes.map((scope, scopeIndex) => {
275 const hasMultipleProjects = scope.projects.length > 1;
276 const selectionTarget = getProjectScopeSelectionTarget(scope, selectedEnvironmentId);
277 return (
278 <View
279 key={scope.key}
280 className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
281 >
282 <Pressable
283 disabled={reservedDestinationProject !== null}
284 onPress={() => void selectProject(selectionTarget)}
285 className="flex-row items-center gap-3 bg-card px-4 py-3.5"
286 >
287 <View className="h-7 w-7 items-center justify-center">
288 <ProjectFavicon
289 environmentId={scope.representative.environmentId}
290 faviconPath={scope.representative.faviconPath}
291 size={20}
292 projectTitle={scope.title}
293 workspaceRoot={scope.representative.workspaceRoot}
294 />
295 </View>
296 <View className="min-w-0 flex-1">
297 <Text className="text-base leading-snug font-t3-bold">{scope.title}</Text>
298 <Text
299 className="text-xs leading-snug text-foreground-muted"
300 ellipsizeMode="middle"
301 numberOfLines={1}
302 >
303 {hasMultipleProjects
304 ? `${scope.projects.length} workspaces`
305 : selectionTarget.workspaceRoot}
306 </Text>
307 </View>
308 <SymbolView
309 name="chevron.right"
310 size={14}
311 tintColor={chevronColor}
312 type="monochrome"
313 />
314 </Pressable>
315 </View>
316 );
317 })}
318 </View>
319 )}
320 </ScrollView>
321 </View>
322 );
323}