Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NewTaskRouteScreen.tsx

366 lines14.0 KB

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