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