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