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

NewTaskRouteScreen.tsx

332 lines11.9 KB

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