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