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 { useEffect, useRef, useState, type ReactNode } from "react";
24import { Platform, Pressable, ScrollView, View } from "react-native";
25import { useSafeAreaInsets } from "react-native-safe-area-context";
26
27import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
28import { ScreenContent } from "../../components/ui/ScreenContent";
29import { SymbolView } from "../../components/ui/AppSymbol";
30import { AppText as Text } from "../../components/ui/AppText";
31import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
32import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
33import { cn } from "../../lib/cn";
34import { NativeStackScreenOptions } from "../../native/StackHeader";
35import { useEnvironmentScope } from "../../state/session";
36import { useAtomCommand } from "../../state/use-atom-command";
37import { vcsEnvironment } from "../../state/vcs";
38import {
39 createNativeMailSearchToolbarItem,
40 NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET,
41} from "../layout/native-mail-search-toolbar";
42import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-toolbar";
43import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
44import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
45
46import { useEnvironmentPresentation } from "../../state/presentation";
47import { useRemoteConnections } from "../../state/use-remote-environment-registry";
48import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
49import {
50 ConnectionDiagnosisDetails,
51 useConnectionDiagnosis,
52} from "../connection/ConnectionDiagnosisDetails";
53import { environmentStatusText } from "../connection/environmentStatusText";
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 <NativeStackScreenOptions
186 options={{
187 headerShown: Platform.OS !== "android",
188 title: "Environment",
189 }}
190 />
191 {Platform.OS === "android" ? (
192 <AndroidScreenHeader
193 title="Environment"
194 hideBottomBorder
195 onBack={() => navigation.goBack()}
196 />
197 ) : null}
198 <ScreenContent>
199 <ScrollView
200 contentInsetAdjustmentBehavior="automatic"
201 contentContainerStyle={{
202 paddingBottom: Math.max(insets.bottom, 16) + 16,
203 paddingHorizontal: 16,
204 paddingTop: 16,
205 }}
206 showsVerticalScrollIndicator={false}
207 >
208 <PickerSurface>
209 {flow.environments.map((environment, index) => (
210 <EnvironmentPickerRow
211 key={String(environment.environmentId)}
212 environmentId={environment.environmentId}
213 isLast={index === flow.environments.length - 1}
214 disabled={flow.switchingToEnvironmentId !== null}
215 onPress={() => {
216 void Haptics.selectionAsync();
217 void flow.switchEnvironment(environment.environmentId).then((switched) => {
218 if (switched) navigation.goBack();
219 });
220 }}
221 selected={flow.selectedEnvironmentId === environment.environmentId}
222 title={environment.environmentLabel}
223 />
224 ))}
225 </PickerSurface>
226 </ScrollView>
227 </ScreenContent>
228 </View>
229 );
230}
231
232export function NewTaskBranchPickerRouteScreen() {
233 const flow = useNewTaskFlow();
234 const canWriteSourceControl = useEnvironmentScope(
235 flow.selectedProject?.environmentId ?? null,
236 AuthSourceControlWriteScope,
237 );
238 const navigation = useNavigation();
239 const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false });
240 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
241 const [switchingBranchName, setSwitchingBranchName] = useState<string | null>(null);
242 const selectingBranchNameRef = useRef<string | null>(null);
243 const allowSelectionNavigationRef = useRef(false);
244 const mountedRef = useRef(true);
245
246 useEffect(() => {
247 mountedRef.current = true;
248 return () => {
249 mountedRef.current = false;
250 flow.setBranchQuery("");
251 };
252 }, [flow.setBranchQuery]);
253
254 useEffect(
255 () =>
256 navigation.addListener("beforeRemove", (event) => {
257 if (selectingBranchNameRef.current !== null && !allowSelectionNavigationRef.current) {
258 event.preventDefault();
259 }
260 }),
261 [navigation],
262 );
263
264 const selectBranch = async (branch: VcsRef) => {
265 const needsCheckout = shouldCheckoutNewTaskBranch({
266 branchIsCurrent: branch.current,
267 branchWorktreePath: branch.worktreePath,
268 workspaceMode: flow.workspaceMode,
269 });
270 if (selectingBranchNameRef.current !== null || (needsCheckout && !canWriteSourceControl)) {
271 return;
272 }
273 selectingBranchNameRef.current = branch.name;
274 void Haptics.selectionAsync();
275
276 const project = flow.selectedProject;
277 if (!project) {
278 selectingBranchNameRef.current = null;
279 return;
280 }
281 setSwitchingBranchName(branch.name);
282 const result = await checkoutNewTaskBranch({
283 branch,
284 project,
285 workspaceMode: flow.workspaceMode,
286 readRefs,
287 switchRef,
288 });
289 if (mountedRef.current) setSwitchingBranchName(null);
290 if (result._tag === "Failure") {
291 selectingBranchNameRef.current = null;
292 if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
293 const error = squashAtomCommandFailure(result);
294 Dialog.alert(
295 "Could not switch branch",
296 error instanceof Error ? error.message : "The branch could not be checked out.",
297 );
298 }
299 return;
300 }
301
302 // Checkout already changed Git; persist the draft selection even if the sheet dismissed mid-command.
303 flow.selectBranch(result.value);
304 if (!mountedRef.current || !navigation.isFocused()) {
305 selectingBranchNameRef.current = null;
306 return;
307 }
308 flow.setBranchQuery("");
309 // beforeRemove blocks dismissal while a switch is in flight; this one is ours.
310 allowSelectionNavigationRef.current = true;
311 navigation.goBack();
312 allowSelectionNavigationRef.current = false;
313 selectingBranchNameRef.current = null;
314 };
315
316 return (
317 <BranchPickerScreen
318 title={flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}
319 project={flow.selectedProject}
320 branches={flow.filteredBranches}
321 selectedBranchName={
322 flow.selectedBranchName ??
323 flow.availableBranches.find((branch) => branch.current)?.name ??
324 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
325 null
326 }
327 query={flow.branchQuery}
328 onQueryChange={flow.setBranchQuery}
329 loading={flow.branchesLoading}
330 error={flow.branchesError}
331 refreshing={flow.branchesFetchingNextPage}
332 hasMore={flow.hasMoreBranches}
333 onRefresh={flow.loadBranches}
334 onLoadMore={flow.loadMoreBranches}
335 selectionDisabled={switchingBranchName !== null}
336 onSelect={selectBranch}
337 worktree={
338 flow.workspaceMode === "worktree"
339 ? {
340 startFromOrigin: flow.startFromOrigin,
341 onChangeStartFromOrigin: flow.setStartFromOrigin,
342 }
343 : undefined
344 }
345 />
346 );
347}
348
349export function BranchPickerScreen(props: {
350 readonly title: string;
351 readonly project: EnvironmentProject | null;
352 readonly branches: readonly VcsRef[];
353 readonly selectedBranchName: string | null;
354 readonly query: string;
355 readonly onQueryChange: (query: string) => void;
356 readonly loading: boolean;
357 readonly error: string | null;
358 readonly refreshing: boolean;
359 readonly hasMore: boolean;
360 readonly onRefresh: () => void;
361 readonly onLoadMore: () => void;
362 readonly selectionDisabled?: boolean;
363 readonly onSelect: (branch: VcsRef) => void;
364 readonly worktree?: {
365 readonly startFromOrigin: boolean;
366 readonly onChangeStartFromOrigin: (value: boolean) => void;
367 };
368}) {
369 const searchRef = useRef<import("react-native").TextInputInstance>(null);
370 const navigation = useNavigation();
371 const insets = useSafeAreaInsets();
372 const usesNativeMailSearchToolbar = useNativeMailSearchToolbar();
373 const selectedBranchName =
374 props.selectedBranchName ??
375 props.branches.find((branch) => branch.current)?.name ??
376 props.branches.find((branch) => branch.isDefault)?.name ??
377 null;
378 const branchListContentStyle = {
379 paddingBottom: usesNativeMailSearchToolbar
380 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
381 : Platform.OS === "ios"
382 ? 16
383 : Math.max(insets.bottom, 16) + 16,
384 paddingHorizontal: 16,
385 paddingTop: 16,
386 };
387
388 const renderBranch = ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
389 <SelectionRow
390 icon="arrow.triangle.branch"
391 disabled={props.selectionDisabled ?? false}
392 isFirst={index === 0}
393 isLast={index === props.branches.length - 1}
394 onPress={() => props.onSelect(item)}
395 selected={selectedBranchName === item.name}
396 subtitle={branchBadgeLabel({ branch: item, project: props.project })?.toUpperCase()}
397 title={item.name}
398 />
399 );
400
401 const branchListHeader = props.worktree ? (
402 <View
403 className={cn(
404 "mb-3 overflow-hidden",
405 Platform.OS === "android" ? "rounded-[28px]" : "rounded-2xl",
406 )}
407 >
408 <ToggleRow
409 onValueChange={props.worktree.onChangeStartFromOrigin}
410 title="Start from remote"
411 value={props.worktree.startFromOrigin}
412 />
413 </View>
414 ) : null;
415
416 const branchContent =
417 props.branches.length === 0 ? (
418 <ScrollView
419 className="flex-1 bg-sheet android:bg-sheet-solid"
420 contentInsetAdjustmentBehavior="automatic"
421 contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 16, paddingTop: 16 }}
422 scrollEnabled={false}
423 showsVerticalScrollIndicator={false}
424 >
425 {branchListHeader}
426 <View
427 className="flex-1 items-center justify-center gap-3 px-4"
428 style={{
429 marginBottom: usesNativeMailSearchToolbar
430 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET
431 : 0,
432 }}
433 >
434 {props.loading ? <AppActivityIndicator /> : null}
435 <Text className="text-center text-sm text-foreground-muted">
436 {props.loading
437 ? "Loading branches…"
438 : props.error
439 ? props.error
440 : props.query
441 ? "No matching branches"
442 : "No branches available"}
443 </Text>
444 {!props.loading && props.error ? (
445 <View className="self-center">
446 <Button label="Try again" tone="secondary" onPress={props.onRefresh} />
447 </View>
448 ) : null}
449 </View>
450 </ScrollView>
451 ) : (
452 <LegendList
453 renderScrollComponent={Platform.OS === "ios" ? NativeScrollView : undefined}
454 alwaysBounceVertical={false}
455 automaticallyAdjustsScrollIndicatorInsets
456 automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
457 className="flex-1 bg-sheet android:bg-sheet-solid"
458 contentInsetAdjustmentBehavior="automatic"
459 contentContainerStyle={branchListContentStyle}
460 data={props.branches}
461 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
462 keyboardShouldPersistTaps="handled"
463 keyExtractor={(branch) =>
464 `${branch.remoteName ?? "local"}:${branch.name}:${branch.worktreePath ?? ""}`
465 }
466 ListHeaderComponent={branchListHeader}
467 ListFooterComponent={
468 props.refreshing ? (
469 <View className="items-center py-4">
470 <AppActivityIndicator />
471 </View>
472 ) : null
473 }
474 onEndReached={props.hasMore ? props.onLoadMore : undefined}
475 onEndReachedThreshold={0.35}
476 renderItem={renderBranch}
477 showsVerticalScrollIndicator={false}
478 />
479 );
480
481 if (Platform.OS === "android") {
482 return (
483 <View className="flex-1 bg-sheet" collapsable={false}>
484 <NativeStackScreenOptions options={{ headerShown: false }} />
485 <AndroidScreenHeader
486 title={props.title}
487 hideBottomBorder
488 onBack={() => navigation.goBack()}
489 />
490 <View className="bg-header px-4 pb-3 pt-1">
491 <SearchField
492 inputRef={searchRef}
493 autoFocus={false}
494 accessibilityLabel="Find a branch"
495 clearAccessibilityLabel="Clear branch search"
496 onChangeText={props.onQueryChange}
497 placeholder="Find a branch"
498 value={props.query}
499 />
500 </View>
501 <ScreenContent>{branchContent}</ScreenContent>
502 </View>
503 );
504 }
505
506 return (
507 <>
508 <NativeStackScreenOptions
509 options={{
510 headerShown: true,
511 title: props.title,
512 unstable_headerToolbarItems: usesNativeMailSearchToolbar
513 ? () => [
514 createNativeMailSearchToolbarItem({
515 onSearchTextChange: props.onQueryChange,
516 placeholder: "Find a branch",
517 searchTextChangeId: "new-task-branch-search-text",
518 showsSearchDismissButton: true,
519 }),
520 ]
521 : undefined,
522 headerSearchBarOptions: usesNativeMailSearchToolbar
523 ? undefined
524 : {
525 allowToolbarIntegration: true,
526 autoCapitalize: "none",
527 hideNavigationBar: false,
528 obscureBackground: false,
529 placeholder: "Find a branch",
530 onChangeText: (event) => {
531 props.onQueryChange(event.nativeEvent.text);
532 },
533 onCancelButtonPress: () => {
534 props.onQueryChange("");
535 },
536 },
537 }}
538 />
539 {usesNativeMailSearchToolbar ? null : (
540 <Toolbar placement="bottom">
541 <Toolbar.SearchBarSlot />
542 </Toolbar>
543 )}
544 {branchContent}
545 </>
546 );
547}