Open History to see the last commit
1import { SearchField } from "../../components/ui/SearchField";
2import { Button } from "../../components/ui/Button";
3import { Toolbar } from "../../components/ui/Toolbar";
4import * as Dialog from "../../components/ui/Dialog";
5import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
6import { NavigationRow } from "../../components/ui/NavigationRow";
7import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
8import { shouldCheckoutNewTaskBranch } from "./new-task-context-presentation";
9import type { VcsRef } from "@t3tools/client-runtime/state/vcs";
10import { AuthSourceControlWriteScope, resolveEnvironmentMachineKind } from "@t3tools/contracts";
11import { LegendList } from "@legendapp/list/react-native";
12import {
13 isAtomCommandInterrupted,
14 squashAtomCommandFailure,
15} from "@t3tools/client-runtime/state/runtime";
16import * as Haptics from "expo-haptics";
17import { useNavigation } from "@react-navigation/native";
18import { useEffect, useRef, useState, type ReactNode } from "react";
19import { Platform, Pressable, ScrollView, View } from "react-native";
20import { useSafeAreaInsets } from "react-native-safe-area-context";
21
22import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
23import { ScreenContent } from "../../components/ui/ScreenContent";
24import { SymbolView } from "../../components/ui/AppSymbol";
25import { AppText as Text } from "../../components/ui/AppText";
26import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
27import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
28import { cn } from "../../lib/cn";
29import { NativeStackScreenOptions } from "../../native/StackHeader";
30import { useServerConfigs } from "../../state/entities";
31import { useEnvironmentScope } from "../../state/session";
32import { useAtomCommand } from "../../state/use-atom-command";
33import { vcsEnvironment } from "../../state/vcs";
34import {
35 createNativeMailSearchToolbarItem,
36 NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET,
37} from "../layout/native-mail-search-toolbar";
38import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-toolbar";
39import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
40import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
41
42function SelectionRow(props: {
43 readonly icon?: "arrow.triangle.branch" | ReactNode;
44 readonly onPress: () => void;
45 readonly disabled?: boolean;
46 readonly selected: boolean;
47 readonly isLast?: boolean;
48 readonly subtitle?: string;
49 readonly title: string;
50}) {
51 if (Platform.OS === "android") {
52 return (
53 <NavigationRow
54 className="bg-grouped-card"
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-grouped-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-grouped-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 = () => props.onSelect(props.branch);
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-grouped-card"
194 : "overflow-hidden rounded-2xl bg-grouped-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 return (
208 <View className="flex-1 bg-sheet" collapsable={false}>
209 <NativeStackScreenOptions
210 options={{
211 headerShown: Platform.OS !== "android",
212 title: "Environment",
213 }}
214 />
215 {Platform.OS === "android" ? (
216 <AndroidScreenHeader
217 title="Environment"
218 hideBottomBorder
219 onBack={() => navigation.goBack()}
220 />
221 ) : null}
222 <ScreenContent>
223 <ScrollView
224 contentInsetAdjustmentBehavior="automatic"
225 contentContainerStyle={{
226 paddingBottom: Math.max(insets.bottom, 16) + 16,
227 paddingHorizontal: 16,
228 paddingTop: 16,
229 }}
230 showsVerticalScrollIndicator={false}
231 >
232 <PickerSurface>
233 {flow.environments.map((environment, index) => (
234 <SelectionRow
235 key={String(environment.environmentId)}
236 icon={
237 <EnvironmentMachineSymbol
238 kind={resolveEnvironmentMachineKind(
239 serverConfigs.get(environment.environmentId) ?? null,
240 )}
241 size={Platform.OS === "android" ? 24 : 17}
242 tintColorClassName="accent-icon-muted"
243 />
244 }
245 isLast={index === flow.environments.length - 1}
246 disabled={flow.switchingToEnvironmentId !== null}
247 onPress={() => {
248 void Haptics.selectionAsync();
249 void flow.switchEnvironment(environment.environmentId).then((switched) => {
250 if (switched) navigation.goBack();
251 });
252 }}
253 selected={flow.selectedEnvironmentId === environment.environmentId}
254 title={environment.environmentLabel}
255 />
256 ))}
257 </PickerSurface>
258 </ScrollView>
259 </ScreenContent>
260 </View>
261 );
262}
263
264export function NewTaskBranchPickerRouteScreen() {
265 const flow = useNewTaskFlow();
266 const canWriteSourceControl = useEnvironmentScope(
267 flow.selectedProject?.environmentId ?? null,
268 AuthSourceControlWriteScope,
269 );
270 const navigation = useNavigation();
271 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
272 const [switchingBranchName, setSwitchingBranchName] = useState<string | null>(null);
273 const selectingBranchNameRef = useRef<string | null>(null);
274 const allowSelectionNavigationRef = useRef(false);
275 const mountedRef = useRef(true);
276
277 useEffect(() => {
278 mountedRef.current = true;
279 return () => {
280 mountedRef.current = false;
281 flow.setBranchQuery("");
282 };
283 }, [flow.setBranchQuery]);
284
285 useEffect(
286 () =>
287 navigation.addListener("beforeRemove", (event) => {
288 if (selectingBranchNameRef.current !== null && !allowSelectionNavigationRef.current) {
289 event.preventDefault();
290 }
291 }),
292 [navigation],
293 );
294
295 const selectBranch = async (branch: VcsRef) => {
296 const needsCheckout = shouldCheckoutNewTaskBranch({
297 branchIsCurrent: branch.current,
298 branchWorktreePath: branch.worktreePath,
299 workspaceMode: flow.workspaceMode,
300 });
301 if (selectingBranchNameRef.current !== null || (needsCheckout && !canWriteSourceControl)) {
302 return;
303 }
304 selectingBranchNameRef.current = branch.name;
305 void Haptics.selectionAsync();
306
307 const project = flow.selectedProject;
308 if (!project) {
309 selectingBranchNameRef.current = null;
310 return;
311 }
312 setSwitchingBranchName(branch.name);
313 const result = await checkoutNewTaskBranch({
314 branch,
315 project,
316 workspaceMode: flow.workspaceMode,
317 switchRef,
318 });
319 if (mountedRef.current) setSwitchingBranchName(null);
320 if (result._tag === "Failure") {
321 selectingBranchNameRef.current = null;
322 if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
323 const error = squashAtomCommandFailure(result);
324 Dialog.alert(
325 "Could not switch branch",
326 error instanceof Error ? error.message : "The branch could not be checked out.",
327 );
328 }
329 return;
330 }
331
332 // The checkout has already changed the repository. Persist the matching
333 // draft selection even if the native sheet was dismissed while the
334 // command was in flight; only visible-screen work is focus-gated below.
335 flow.selectBranch(result.value);
336 if (!mountedRef.current || !navigation.isFocused()) {
337 selectingBranchNameRef.current = null;
338 return;
339 }
340 flow.setBranchQuery("");
341 // beforeRemove blocks dismissal while a switch is in flight; this one is ours.
342 allowSelectionNavigationRef.current = true;
343 navigation.goBack();
344 allowSelectionNavigationRef.current = false;
345 selectingBranchNameRef.current = null;
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
381export function BranchPickerScreen(props: {
382 readonly title: string;
383 readonly project: EnvironmentProject | null;
384 readonly branches: readonly VcsRef[];
385 readonly selectedBranchName: string | null;
386 readonly query: string;
387 readonly onQueryChange: (query: string) => void;
388 readonly loading: boolean;
389 readonly error: string | null;
390 readonly refreshing: boolean;
391 readonly hasMore: boolean;
392 readonly onRefresh: () => void;
393 readonly onLoadMore: () => void;
394 readonly selectionDisabled?: boolean;
395 readonly onSelect: (branch: VcsRef) => void;
396 readonly worktree?: {
397 readonly startFromOrigin: boolean;
398 readonly onChangeStartFromOrigin: (value: boolean) => void;
399 };
400}) {
401 const searchRef = useRef<import("react-native").TextInputInstance>(null);
402 const navigation = useNavigation();
403 const insets = useSafeAreaInsets();
404 const usesNativeMailSearchToolbar = useNativeMailSearchToolbar();
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 = {
411 paddingBottom: usesNativeMailSearchToolbar
412 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
413 : Platform.OS === "ios"
414 ? 16
415 : Math.max(insets.bottom, 16) + 16,
416 paddingHorizontal: 16,
417 paddingTop: 16,
418 };
419
420 const renderBranch = ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
421 <BranchSelectionRow
422 badge={branchBadgeLabel({ branch: item, project: props.project })}
423 branch={item}
424 disabled={props.selectionDisabled ?? false}
425 isFirst={index === 0}
426 isLast={index === props.branches.length - 1}
427 onSelect={props.onSelect}
428 selected={selectedBranchName === item.name}
429 />
430 );
431
432 const branchListHeader = props.worktree ? (
433 <View
434 className={cn(
435 "mb-3 overflow-hidden",
436 Platform.OS === "android" ? "rounded-[28px]" : "rounded-2xl",
437 )}
438 >
439 <ToggleRow
440 onValueChange={props.worktree.onChangeStartFromOrigin}
441 title="Start from remote"
442 value={props.worktree.startFromOrigin}
443 />
444 </View>
445 ) : null;
446
447 const branchContent =
448 props.branches.length === 0 ? (
449 <ScrollView
450 className="flex-1 bg-sheet android:bg-sheet-solid"
451 contentInsetAdjustmentBehavior="automatic"
452 contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 16, paddingTop: 16 }}
453 scrollEnabled={false}
454 showsVerticalScrollIndicator={false}
455 >
456 {branchListHeader}
457 <View
458 className="flex-1 items-center justify-center gap-3 px-4"
459 style={{
460 marginBottom: usesNativeMailSearchToolbar
461 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET
462 : 0,
463 }}
464 >
465 {props.loading ? <AppActivityIndicator /> : null}
466 <Text className="text-center text-sm text-foreground-muted">
467 {props.loading
468 ? "Loading branches…"
469 : props.error
470 ? props.error
471 : props.query
472 ? "No matching branches"
473 : "No branches available"}
474 </Text>
475 {!props.loading && props.error ? (
476 <View className="self-center">
477 <Button label="Try again" tone="secondary" onPress={props.onRefresh} />
478 </View>
479 ) : null}
480 </View>
481 </ScrollView>
482 ) : (
483 <LegendList
484 alwaysBounceVertical={false}
485 automaticallyAdjustsScrollIndicatorInsets
486 automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
487 className="flex-1 bg-sheet android:bg-sheet-solid"
488 contentInsetAdjustmentBehavior="automatic"
489 contentContainerStyle={branchListContentStyle}
490 data={props.branches}
491 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
492 keyboardShouldPersistTaps="handled"
493 keyExtractor={(branch) =>
494 `${branch.remoteName ?? "local"}:${branch.name}:${branch.worktreePath ?? ""}`
495 }
496 ListHeaderComponent={branchListHeader}
497 ListFooterComponent={
498 props.refreshing ? (
499 <View className="items-center py-4">
500 <AppActivityIndicator />
501 </View>
502 ) : null
503 }
504 onEndReached={props.hasMore ? props.onLoadMore : undefined}
505 onEndReachedThreshold={0.35}
506 renderItem={renderBranch}
507 showsVerticalScrollIndicator={false}
508 />
509 );
510
511 if (Platform.OS === "android") {
512 return (
513 <View className="flex-1 bg-sheet" collapsable={false}>
514 <NativeStackScreenOptions options={{ headerShown: false }} />
515 <AndroidScreenHeader
516 title={props.title}
517 hideBottomBorder
518 onBack={() => navigation.goBack()}
519 />
520 <View className="bg-header px-4 pb-3 pt-1">
521 <SearchField
522 inputRef={searchRef}
523 autoFocus={false}
524 accessibilityLabel="Find a branch"
525 clearAccessibilityLabel="Clear branch search"
526 onChangeText={props.onQueryChange}
527 placeholder="Find a branch"
528 value={props.query}
529 />
530 </View>
531 <ScreenContent>{branchContent}</ScreenContent>
532 </View>
533 );
534 }
535
536 return (
537 <>
538 <NativeStackScreenOptions
539 options={{
540 headerShown: true,
541 title: props.title,
542 unstable_headerToolbarItems: usesNativeMailSearchToolbar
543 ? () => [
544 createNativeMailSearchToolbarItem({
545 onSearchTextChange: props.onQueryChange,
546 placeholder: "Find a branch",
547 searchTextChangeId: "new-task-branch-search-text",
548 showsSearchDismissButton: true,
549 }),
550 ]
551 : undefined,
552 headerSearchBarOptions: usesNativeMailSearchToolbar
553 ? undefined
554 : {
555 allowToolbarIntegration: true,
556 autoCapitalize: "none",
557 hideNavigationBar: false,
558 obscureBackground: false,
559 placeholder: "Find a branch",
560 onChangeText: (event) => {
561 props.onQueryChange(event.nativeEvent.text);
562 },
563 onCancelButtonPress: () => {
564 props.onQueryChange("");
565 },
566 },
567 }}
568 />
569 {usesNativeMailSearchToolbar ? null : (
570 <Toolbar placement="bottom">
571 <Toolbar.SearchBarSlot />
572 </Toolbar>
573 )}
574 {branchContent}
575 </>
576 );
577}