Open History to see the last commit
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 { shouldCheckoutNewTaskBranch } from "./new-task-context-presentation";
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 );
93}
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 );
112}
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 );
143}
144
145function PickerSurface(props: { readonly children: ReactNode }) {
146 return <View className="overflow-hidden rounded-2xl bg-card">{props.children}</View>;
147}
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 );
202}
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 let selectedBranch = branch;
261 const needsCheckout = shouldCheckoutNewTaskBranch({
262 branchIsCurrent: branch.current,
263 branchWorktreePath: branch.worktreePath,
264 workspaceMode: flow.workspaceMode,
265 });
266 if (needsCheckout && flow.selectedProject) {
267 setSwitchingBranchName(branch.name);
268 const result = await switchRef({
269 environmentId: flow.selectedProject.environmentId,
270 input: {
271 cwd: flow.selectedProject.workspaceRoot,
272 refName: branch.name,
273 },
274 });
275 if (result._tag === "Failure") {
276 if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
277 const error = squashAtomCommandFailure(result);
278 Alert.alert(
279 "Could not switch branch",
280 error instanceof Error ? error.message : "The branch could not be checked out.",
281 );
282 }
283 return;
284 }
285 selectedBranch = {
286 ...branch,
287 current: true,
288 isRemote: false,
289 name: result.value.refName ?? branch.name,
290 };
291 }
292
293 // The checkout has already changed the repository. Persist the matching
294 // draft selection even if the native sheet was dismissed while the
295 // command was in flight; only visible-screen work is focus-gated below.
296 flow.selectBranch(selectedBranch);
297 if (!mountedRef.current || !navigation.isFocused()) {
298 return;
299 }
300 flow.setBranchQuery("");
301 allowSelectionNavigationRef.current = true;
302 navigation.goBack();
303 } finally {
304 selectingBranchNameRef.current = null;
305 allowSelectionNavigationRef.current = false;
306 if (mountedRef.current) {
307 setSwitchingBranchName(null);
308 }
309 }
310 },
311 [
312 flow.selectBranch,
313 flow.selectedProject,
314 flow.setBranchQuery,
315 flow.workspaceMode,
316 navigation,
317 switchRef,
318 ],
319 );
320
321 const renderBranch = useCallback(
322 ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
323 <BranchSelectionRow
324 badge={branchBadgeLabel({ branch: item, project: flow.selectedProject })}
325 branch={item}
326 disabled={switchingBranchName !== null}
327 isFirst={index === 0}
328 isLast={index === flow.filteredBranches.length - 1}
329 onSelect={selectBranch}
330 selected={selectedBranchName === item.name}
331 />
332 ),
333 [
334 flow.filteredBranches.length,
335 flow.selectedProject,
336 selectBranch,
337 selectedBranchName,
338 switchingBranchName,
339 ],
340 );
341
342 const branchListHeader =
343 flow.workspaceMode === "worktree" ? (
344 <View className="mb-3 overflow-hidden rounded-2xl">
345 <ToggleRow
346 onValueChange={flow.setStartFromOrigin}
347 title="Start from origin"
348 value={flow.startFromOrigin}
349 />
350 </View>
351 ) : null;
352
353 const branchContent =
354 flow.filteredBranches.length === 0 ? (
355 <ScrollView
356 className="flex-1 bg-sheet"
357 contentInsetAdjustmentBehavior="automatic"
358 contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 16, paddingTop: 12 }}
359 scrollEnabled={false}
360 showsVerticalScrollIndicator={false}
361 >
362 {branchListHeader}
363 <View
364 className="flex-1 items-center justify-center gap-3 px-4"
365 style={{
366 marginBottom: usesNativeMailSearchToolbar
367 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET
368 : 0,
369 }}
370 >
371 {flow.branchesLoading ? <ActivityIndicator /> : null}
372 <Text className="text-center text-sm text-foreground-muted">
373 {flow.branchesLoading
374 ? "Loading branches…"
375 : flow.branchesError
376 ? flow.branchesError
377 : flow.branchQuery
378 ? "No matching branches"
379 : "No branches available"}
380 </Text>
381 {!flow.branchesLoading && flow.branchesError ? (
382 <Pressable
383 accessibilityRole="button"
384 className="rounded-full bg-card px-4 py-2 active:opacity-70"
385 onPress={flow.loadBranches}
386 >
387 <Text className="text-sm font-t3-medium text-foreground">Try again</Text>
388 </Pressable>
389 ) : null}
390 </View>
391 </ScrollView>
392 ) : (
393 <LegendList
394 alwaysBounceVertical={false}
395 automaticallyAdjustsScrollIndicatorInsets
396 automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
397 className="flex-1 bg-sheet"
398 contentInsetAdjustmentBehavior="automatic"
399 contentContainerStyle={branchListContentStyle}
400 data={flow.filteredBranches}
401 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
402 keyboardShouldPersistTaps="handled"
403 keyExtractor={(branch) =>
404 `${branch.remoteName ?? "local"}:${branch.name}:${branch.worktreePath ?? ""}`
405 }
406 ListHeaderComponent={branchListHeader}
407 ListFooterComponent={
408 flow.branchesFetchingNextPage ? (
409 <View className="items-center py-4">
410 <ActivityIndicator />
411 </View>
412 ) : null
413 }
414 onEndReached={flow.hasMoreBranches ? flow.loadMoreBranches : undefined}
415 onEndReachedThreshold={0.35}
416 renderItem={renderBranch}
417 showsVerticalScrollIndicator={false}
418 />
419 );
420
421 if (Platform.OS === "android") {
422 return (
423 <View className="flex-1 bg-sheet" collapsable={false}>
424 <NativeStackScreenOptions options={{ headerShown: false }} />
425 <AndroidScreenHeader title={screenTitle} onBack={() => navigation.goBack()} />
426 <View className="px-4 pb-2 pt-3">
427 <TextInput
428 autoCapitalize="none"
429 autoCorrect={false}
430 className="h-11 rounded-xl bg-card px-4 font-sans text-base text-foreground"
431 onChangeText={flow.setBranchQuery}
432 placeholder="Find a branch"
433 placeholderTextColorClassName={"accent-placeholder"}
434 value={flow.branchQuery}
435 />
436 </View>
437 {branchContent}
438 </View>
439 );
440 }
441
442 return (
443 <>
444 <NativeStackScreenOptions
445 options={{
446 headerShown: true,
447 title: screenTitle,
448 unstable_headerToolbarItems: usesNativeMailSearchToolbar
449 ? () => [
450 createNativeMailSearchToolbarItem({
451 onSearchTextChange: flow.setBranchQuery,
452 placeholder: "Find a branch",
453 searchTextChangeId: "new-task-branch-search-text",
454 showsSearchDismissButton: true,
455 }),
456 ]
457 : undefined,
458 headerSearchBarOptions: usesNativeMailSearchToolbar
459 ? undefined
460 : {
461 allowToolbarIntegration: true,
462 autoCapitalize: "none",
463 hideNavigationBar: false,
464 obscureBackground: false,
465 placeholder: "Find a branch",
466 onChangeText: (event) => {
467 flow.setBranchQuery(event.nativeEvent.text);
468 },
469 onCancelButtonPress: () => {
470 flow.setBranchQuery("");
471 },
472 },
473 }}
474 />
475 {usesNativeMailSearchToolbar ? null : (
476 <NativeHeaderToolbar placement="bottom">
477 <NativeHeaderToolbar.SearchBarSlot />
478 </NativeHeaderToolbar>
479 )}
480 {branchContent}
481 </>
482 );
483}