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

NewTaskContextPickerScreens.tsx

595 lines21.5 KB

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