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