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