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

NewTaskContextPickerScreens.tsx

469 lines15.4 KB

1import type { VcsRef } from "@t3tools/client-runtime/state/vcs";
2import { resolveEnvironmentMachineKind } from "@t3tools/contracts";
3import { LegendList } from "@legendapp/list/react-native";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import * as Haptics from "expo-haptics";
9import { useNavigation } from "@react-navigation/native";
10import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
11import {
12 ActivityIndicator,
13 Alert,
14 Platform,
15 Pressable,
16 ScrollView,
17 TextInput,
18 View,
19} from "react-native";
20import { useSafeAreaInsets } from "react-native-safe-area-context";
21​
22import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
23import { SymbolView } from "../../components/AppSymbol";
24import { AppText as Text } from "../../components/AppText";
25import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
26import { ThemedSwitch } from "../../components/ThemedSwitch";
27import { cn } from "../../lib/cn";
28import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
29import { useServerConfigs } from "../../state/entities";
30import { useAtomCommand } from "../../state/use-atom-command";
31import { vcsEnvironment } from "../../state/vcs";
32import {
33 createNativeMailSearchToolbarItem,
34 NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET,
35 NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
36} from "../layout/native-mail-search-toolbar";
37import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
38import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
39​
40function SelectionRow(props: {
41 readonly icon?: "arrow.triangle.branch" | ReactNode;
42 readonly onPress: () => void;
43 readonly disabled?: boolean;
44 readonly selected: boolean;
45 readonly isLast?: boolean;
46 readonly subtitle?: string;
47 readonly title: string;
48}) {
49 return (
50 <Pressable
51 accessibilityLabel={[props.title, props.subtitle].filter(Boolean).join(", ")}
52 accessibilityRole="radio"
53 accessibilityState={{ checked: props.selected }}
54 className={cn(
55 "min-h-14 flex-row items-center gap-3 bg-card px-4 py-3 active:bg-subtle",
56 !props.isLast && "border-b border-border-subtle",
57 )}
58 disabled={props.disabled}
59 onPress={props.onPress}
60 style={{ opacity: props.disabled ? 0.45 : 1 }}
61 >
62 {props.icon === "arrow.triangle.branch" ? (
63 <SymbolView
64 name="arrow.triangle.branch"
65 size={17}
66 tintColorClassName={"accent-icon-muted"}
67 type="monochrome"
68 />
69 ) : (
70 (props.icon ?? null)
71 )}
72 <View className="min-w-0 flex-1 gap-0.5">
73 <Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>
74 {props.title}
75 </Text>
76 {props.subtitle ? (
77 <Text className="text-xs text-foreground-muted" numberOfLines={1}>
78 {props.subtitle}
79 </Text>
80 ) : null}
81 </View>
82 {props.selected ? (
83 <SymbolView
84 name="checkmark"
85 size={16}
86 tintColorClassName={"accent-icon"}
87 type="monochrome"
88 weight="semibold"
89 />
90 ) : null}
91 </Pressable>
92 );
94​
95function ToggleRow(props: {
96 readonly title: string;
97 readonly value: boolean;
98 readonly onValueChange: (value: boolean) => void;
99}) {
100 return (
101 <View className="min-h-14 flex-row items-center gap-3 bg-card px-4 py-3">
102 <Text className="min-w-0 flex-1 text-base font-t3-medium text-foreground" numberOfLines={1}>
103 {props.title}
104 </Text>
105 <ThemedSwitch
106 accessibilityLabel={props.title}
107 onValueChange={props.onValueChange}
108 value={props.value}
109 />
110 </View>
111 );
113​
114function BranchSelectionRow(props: {
115 readonly badge: string | null;
116 readonly branch: VcsRef;
117 readonly disabled: boolean;
118 readonly isFirst: boolean;
119 readonly isLast: boolean;
120 readonly onSelect: (branch: VcsRef) => void;
121 readonly selected: boolean;
122}) {
123 const onPress = useCallback(() => props.onSelect(props.branch), [props.branch, props.onSelect]);
124​
125 return (
126 <View
127 className={cn(
128 props.isFirst && "overflow-hidden rounded-t-2xl",
129 props.isLast && "overflow-hidden rounded-b-2xl",
130 )}
131 >
132 <SelectionRow
133 icon="arrow.triangle.branch"
134 disabled={props.disabled}
135 isLast={props.isLast}
136 onPress={onPress}
137 selected={props.selected}
138 subtitle={props.badge ? props.badge.toUpperCase() : undefined}
139 title={props.branch.name}
140 />
141 </View>
142 );
144​
145function PickerSurface(props: { readonly children: ReactNode }) {
146 return <View className="overflow-hidden rounded-2xl bg-card">{props.children}</View>;
148​
149export function NewTaskEnvironmentPickerRouteScreen() {
150 const flow = useNewTaskFlow();
151 const navigation = useNavigation();
152 const insets = useSafeAreaInsets();
153 const serverConfigs = useServerConfigs();
154​
155 return (
156 <View className="flex-1 bg-sheet" collapsable={false}>
157 <NativeStackScreenOptions
158 options={{
159 headerShown: Platform.OS !== "android",
160 title: "Environment",
161 }}
162 />
163 {Platform.OS === "android" ? (
164 <AndroidScreenHeader title="Environment" onBack={() => navigation.goBack()} />
165 ) : null}
166 <ScrollView
167 contentInsetAdjustmentBehavior="automatic"
168 contentContainerStyle={{
169 paddingBottom: Math.max(insets.bottom, 16) + 16,
170 paddingHorizontal: 16,
171 paddingTop: 16,
172 }}
173 showsVerticalScrollIndicator={false}
174 >
175 <PickerSurface>
176 {flow.environments.map((environment, index) => (
177 <SelectionRow
178 key={String(environment.environmentId)}
179 icon={
180 <EnvironmentMachineSymbol
181 kind={resolveEnvironmentMachineKind(
182 serverConfigs.get(environment.environmentId) ?? null,
183 )}
184 size={17}
185 tintColorClassName="accent-icon-muted"
186 />
187 }
188 isLast={index === flow.environments.length - 1}
189 onPress={() => {
190 void Haptics.selectionAsync();
191 flow.selectEnvironment(environment.environmentId);
192 navigation.goBack();
193 }}
194 selected={flow.selectedEnvironmentId === environment.environmentId}
195 title={environment.environmentLabel}
196 />
197 ))}
198 </PickerSurface>
199 </ScrollView>
200 </View>
201 );
203​
204export function NewTaskBranchPickerRouteScreen() {
205 const flow = useNewTaskFlow();
206 const navigation = useNavigation();
207 const insets = useSafeAreaInsets();
208 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
209 const [switchingBranchName, setSwitchingBranchName] = useState<string | null>(null);
210 const selectingBranchNameRef = useRef<string | null>(null);
211 const allowSelectionNavigationRef = useRef(false);
212 const mountedRef = useRef(true);
213 const screenTitle = flow.workspaceMode === "worktree" ? "Base branch" : "Branch";
214 const usesNativeMailSearchToolbar = Platform.OS === "ios" && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED;
215 const selectedBranchName =
216 flow.selectedBranchName ??
217 flow.availableBranches.find((branch) => branch.current)?.name ??
218 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
219 null;
220 const branchListContentStyle = useMemo(
221 () => ({
222 paddingBottom: usesNativeMailSearchToolbar
223 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
224 : Platform.OS === "ios"
225 ? 16
226 : Math.max(insets.bottom, 16) + 16,
227 paddingHorizontal: 16,
228 paddingTop: 12,
229 }),
230 [insets.bottom, usesNativeMailSearchToolbar],
231 );
232​
233 useEffect(() => {
234 mountedRef.current = true;
235 return () => {
236 mountedRef.current = false;
237 flow.setBranchQuery("");
238 };
239 }, [flow.setBranchQuery]);
240​
241 useEffect(
242 () =>
243 navigation.addListener("beforeRemove", (event) => {
244 if (selectingBranchNameRef.current !== null && !allowSelectionNavigationRef.current) {
245 event.preventDefault();
246 }
247 }),
248 [navigation],
249 );
250​
251 const selectBranch = useCallback(
252 async (branch: VcsRef) => {
253 if (selectingBranchNameRef.current !== null) {
254 return;
255 }
256 selectingBranchNameRef.current = branch.name;
257 void Haptics.selectionAsync();
258​
259 try {
260 if (!flow.selectedProject) return;
261 setSwitchingBranchName(branch.name);
262 const result = await checkoutNewTaskBranch({
263 branch,
264 project: flow.selectedProject,
265 workspaceMode: flow.workspaceMode,
266 switchRef,
267 });
268 if (result._tag === "Failure") {
269 if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
270 const error = squashAtomCommandFailure(result);
271 Alert.alert(
272 "Could not switch branch",
273 error instanceof Error ? error.message : "The branch could not be checked out.",
274 );
275 }
276 return;
277 }
278​
279 // The checkout has already changed the repository. Persist the matching
280 // draft selection even if the native sheet was dismissed while the
281 // command was in flight; only visible-screen work is focus-gated below.
282 flow.selectBranch(result.value);
283 if (!mountedRef.current || !navigation.isFocused()) {
284 return;
285 }
286 flow.setBranchQuery("");
287 allowSelectionNavigationRef.current = true;
288 navigation.goBack();
289 } finally {
290 selectingBranchNameRef.current = null;
291 allowSelectionNavigationRef.current = false;
292 if (mountedRef.current) {
293 setSwitchingBranchName(null);
294 }
295 }
296 },
297 [
298 flow.selectBranch,
299 flow.selectedProject,
300 flow.setBranchQuery,
301 flow.workspaceMode,
302 navigation,
303 switchRef,
304 ],
305 );
306​
307 const renderBranch = useCallback(
308 ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
309 <BranchSelectionRow
310 badge={branchBadgeLabel({ branch: item, project: flow.selectedProject })}
311 branch={item}
312 disabled={switchingBranchName !== null}
313 isFirst={index === 0}
314 isLast={index === flow.filteredBranches.length - 1}
315 onSelect={selectBranch}
316 selected={selectedBranchName === item.name}
317 />
318 ),
319 [
320 flow.filteredBranches.length,
321 flow.selectedProject,
322 selectBranch,
323 selectedBranchName,
324 switchingBranchName,
325 ],
326 );
327​
328 const branchListHeader =
329 flow.workspaceMode === "worktree" ? (
330 <View className="mb-3 overflow-hidden rounded-2xl">
331 <ToggleRow
332 onValueChange={flow.setStartFromOrigin}
333 title="Start from origin"
334 value={flow.startFromOrigin}
335 />
336 </View>
337 ) : null;
338​
339 const branchContent =
340 flow.filteredBranches.length === 0 ? (
341 <ScrollView
342 className="flex-1 bg-sheet"
343 contentInsetAdjustmentBehavior="automatic"
344 contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 16, paddingTop: 12 }}
345 scrollEnabled={false}
346 showsVerticalScrollIndicator={false}
347 >
348 {branchListHeader}
349 <View
350 className="flex-1 items-center justify-center gap-3 px-4"
351 style={{
352 marginBottom: usesNativeMailSearchToolbar
353 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET
354 : 0,
355 }}
356 >
357 {flow.branchesLoading ? <ActivityIndicator /> : null}
358 <Text className="text-center text-sm text-foreground-muted">
359 {flow.branchesLoading
360 ? "Loading branches…"
361 : flow.branchesError
362 ? flow.branchesError
363 : flow.branchQuery
364 ? "No matching branches"
365 : "No branches available"}
366 </Text>
367 {!flow.branchesLoading && flow.branchesError ? (
368 <Pressable
369 accessibilityRole="button"
370 className="rounded-full bg-card px-4 py-2 active:opacity-70"
371 onPress={flow.loadBranches}
372 >
373 <Text className="text-sm font-t3-medium text-foreground">Try again</Text>
374 </Pressable>
375 ) : null}
376 </View>
377 </ScrollView>
378 ) : (
379 <LegendList
380 alwaysBounceVertical={false}
381 automaticallyAdjustsScrollIndicatorInsets
382 automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
383 className="flex-1 bg-sheet"
384 contentInsetAdjustmentBehavior="automatic"
385 contentContainerStyle={branchListContentStyle}
386 data={flow.filteredBranches}
387 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
388 keyboardShouldPersistTaps="handled"
389 keyExtractor={(branch) =>
390 `${branch.remoteName ?? "local"}:${branch.name}:${branch.worktreePath ?? ""}`
391 }
392 ListHeaderComponent={branchListHeader}
393 ListFooterComponent={
394 flow.branchesFetchingNextPage ? (
395 <View className="items-center py-4">
396 <ActivityIndicator />
397 </View>
398 ) : null
399 }
400 onEndReached={flow.hasMoreBranches ? flow.loadMoreBranches : undefined}
401 onEndReachedThreshold={0.35}
402 renderItem={renderBranch}
403 showsVerticalScrollIndicator={false}
404 />
405 );
406​
407 if (Platform.OS === "android") {
408 return (
409 <View className="flex-1 bg-sheet" collapsable={false}>
410 <NativeStackScreenOptions options={{ headerShown: false }} />
411 <AndroidScreenHeader title={screenTitle} onBack={() => navigation.goBack()} />
412 <View className="px-4 pb-2 pt-3">
413 <TextInput
414 autoCapitalize="none"
415 autoCorrect={false}
416 className="h-11 rounded-xl bg-card px-4 font-sans text-base text-foreground"
417 onChangeText={flow.setBranchQuery}
418 placeholder="Find a branch"
419 placeholderTextColorClassName={"accent-placeholder"}
420 value={flow.branchQuery}
421 />
422 </View>
423 {branchContent}
424 </View>
425 );
426 }
427​
428 return (
429 <>
430 <NativeStackScreenOptions
431 options={{
432 headerShown: true,
433 title: screenTitle,
434 unstable_headerToolbarItems: usesNativeMailSearchToolbar
435 ? () => [
436 createNativeMailSearchToolbarItem({
437 onSearchTextChange: flow.setBranchQuery,
438 placeholder: "Find a branch",
439 searchTextChangeId: "new-task-branch-search-text",
440 showsSearchDismissButton: true,
441 }),
442 ]
443 : undefined,
444 headerSearchBarOptions: usesNativeMailSearchToolbar
445 ? undefined
446 : {
447 allowToolbarIntegration: true,
448 autoCapitalize: "none",
449 hideNavigationBar: false,
450 obscureBackground: false,
451 placeholder: "Find a branch",
452 onChangeText: (event) => {
453 flow.setBranchQuery(event.nativeEvent.text);
454 },
455 onCancelButtonPress: () => {
456 flow.setBranchQuery("");
457 },
458 },
459 }}
460 />
461 {usesNativeMailSearchToolbar ? null : (
462 <NativeHeaderToolbar placement="bottom">
463 <NativeHeaderToolbar.SearchBarSlot />
464 </NativeHeaderToolbar>
465 )}
466 {branchContent}
467 </>
468 );