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