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