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