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

NewTaskContextPickerScreens.tsx

603 lines19.8 KB

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