Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NewTaskContextPickerScreens.tsx

542 lines19.6 KB

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