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

NewTaskContextPickerScreens.tsx

582 lines19.3 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 { useEffect, 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 = () => props.onSelect(props.branch);
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 = async (branch: VcsRef) => {
294 const needsCheckout = shouldCheckoutNewTaskBranch({
295 branchIsCurrent: branch.current,
296 branchWorktreePath: branch.worktreePath,
297 workspaceMode: flow.workspaceMode,
298 });
299 if (selectingBranchNameRef.current !== null || (needsCheckout && !canWriteSourceControl)) {
300 return;
301 }
302 selectingBranchNameRef.current = branch.name;
303 void Haptics.selectionAsync();
304​
305 const project = flow.selectedProject;
306 if (!project) {
307 selectingBranchNameRef.current = null;
308 return;
309 }
310 setSwitchingBranchName(branch.name);
311 const result = await checkoutNewTaskBranch({
312 branch,
313 project,
314 workspaceMode: flow.workspaceMode,
315 switchRef,
316 });
317 if (mountedRef.current) setSwitchingBranchName(null);
318 if (result._tag === "Failure") {
319 selectingBranchNameRef.current = null;
320 if (mountedRef.current && navigation.isFocused() && !isAtomCommandInterrupted(result)) {
321 const error = squashAtomCommandFailure(result);
322 Dialog.alert(
323 "Could not switch branch",
324 error instanceof Error ? error.message : "The branch could not be checked out.",
325 );
326 }
327 return;
328 }
329​
330 // The checkout has already changed the repository. Persist the matching
331 // draft selection even if the native sheet was dismissed while the
332 // command was in flight; only visible-screen work is focus-gated below.
333 flow.selectBranch(result.value);
334 if (!mountedRef.current || !navigation.isFocused()) {
335 selectingBranchNameRef.current = null;
336 return;
337 }
338 flow.setBranchQuery("");
339 // beforeRemove blocks dismissal while a switch is in flight; this one is ours.
340 allowSelectionNavigationRef.current = true;
341 navigation.goBack();
342 allowSelectionNavigationRef.current = false;
343 selectingBranchNameRef.current = null;
344 };
345​
346 return (
347 <BranchPickerScreen
348 title={flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}
349 project={flow.selectedProject}
350 branches={flow.filteredBranches}
351 selectedBranchName={
352 flow.selectedBranchName ??
353 flow.availableBranches.find((branch) => branch.current)?.name ??
354 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
355 null
356 }
357 query={flow.branchQuery}
358 onQueryChange={flow.setBranchQuery}
359 loading={flow.branchesLoading}
360 error={flow.branchesError}
361 refreshing={flow.branchesFetchingNextPage}
362 hasMore={flow.hasMoreBranches}
363 onRefresh={flow.loadBranches}
364 onLoadMore={flow.loadMoreBranches}
365 selectionDisabled={switchingBranchName !== null}
366 onSelect={selectBranch}
367 worktree={
368 flow.workspaceMode === "worktree"
369 ? {
370 startFromOrigin: flow.startFromOrigin,
371 onChangeStartFromOrigin: flow.setStartFromOrigin,
372 }
373 : undefined
374 }
375 />
376 );
378​
379export function BranchPickerScreen(props: {
380 readonly title: string;
381 readonly project: EnvironmentProject | null;
382 readonly branches: readonly VcsRef[];
383 readonly selectedBranchName: string | null;
384 readonly query: string;
385 readonly onQueryChange: (query: string) => void;
386 readonly loading: boolean;
387 readonly error: string | null;
388 readonly refreshing: boolean;
389 readonly hasMore: boolean;
390 readonly onRefresh: () => void;
391 readonly onLoadMore: () => void;
392 readonly selectionDisabled?: boolean;
393 readonly onSelect: (branch: VcsRef) => void;
394 readonly worktree?: {
395 readonly startFromOrigin: boolean;
396 readonly onChangeStartFromOrigin: (value: boolean) => void;
397 };
398}) {
399 const navigation = useNavigation();
400 const insets = useSafeAreaInsets();
401 const usesNativeMailSearchToolbar = useNativeMailSearchToolbar();
402 const selectedBranchName =
403 props.selectedBranchName ??
404 props.branches.find((branch) => branch.current)?.name ??
405 props.branches.find((branch) => branch.isDefault)?.name ??
406 null;
407 const branchListContentStyle = {
408 paddingBottom: usesNativeMailSearchToolbar
409 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
410 : Platform.OS === "ios"
411 ? 16
412 : Math.max(insets.bottom, 16) + 16,
413 paddingHorizontal: 16,
414 paddingTop: 16,
415 };
416​
417 const renderBranch = ({ item, index }: { readonly item: VcsRef; readonly index: number }) => (
418 <BranchSelectionRow
419 badge={branchBadgeLabel({ branch: item, project: props.project })}
420 branch={item}
421 disabled={props.selectionDisabled ?? false}
422 isFirst={index === 0}
423 isLast={index === props.branches.length - 1}
424 onSelect={props.onSelect}
425 selected={selectedBranchName === item.name}
426 />
427 );
428​
429 const branchListHeader = props.worktree ? (
430 <View
431 className={cn(
432 "mb-3 overflow-hidden",
433 Platform.OS === "android" ? "rounded-[28px]" : "rounded-2xl",
434 )}
435 >
436 <ToggleRow
437 onValueChange={props.worktree.onChangeStartFromOrigin}
438 title="Start from origin"
439 value={props.worktree.startFromOrigin}
440 />
441 </View>
442 ) : null;
443​
444 const branchContent =
445 props.branches.length === 0 ? (
446 <ScrollView
447 className="flex-1 bg-sheet android:bg-sheet-solid"
448 contentInsetAdjustmentBehavior="automatic"
449 contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 16, paddingTop: 16 }}
450 scrollEnabled={false}
451 showsVerticalScrollIndicator={false}
452 >
453 {branchListHeader}
454 <View
455 className="flex-1 items-center justify-center gap-3 px-4"
456 style={{
457 marginBottom: usesNativeMailSearchToolbar
458 ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET
459 : 0,
460 }}
461 >
462 {props.loading ? <AppActivityIndicator /> : null}
463 <Text className="text-center text-sm text-foreground-muted">
464 {props.loading
465 ? "Loading branches…"
466 : props.error
467 ? props.error
468 : props.query
469 ? "No matching branches"
470 : "No branches available"}
471 </Text>
472 {!props.loading && props.error ? (
473 <Pressable
474 accessibilityRole="button"
475 className="rounded-full bg-card px-4 py-2 active:opacity-70"
476 onPress={props.onRefresh}
477 >
478 <Text className="text-sm font-t3-medium text-foreground">Try again</Text>
479 </Pressable>
480 ) : null}
481 </View>
482 </ScrollView>
483 ) : (
484 <LegendList
485 alwaysBounceVertical={false}
486 automaticallyAdjustsScrollIndicatorInsets
487 automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
488 className="flex-1 bg-sheet android:bg-sheet-solid"
489 contentInsetAdjustmentBehavior="automatic"
490 contentContainerStyle={branchListContentStyle}
491 data={props.branches}
492 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
493 keyboardShouldPersistTaps="handled"
494 keyExtractor={(branch) =>
495 `${branch.remoteName ?? "local"}:${branch.name}:${branch.worktreePath ?? ""}`
496 }
497 ListHeaderComponent={branchListHeader}
498 ListFooterComponent={
499 props.refreshing ? (
500 <View className="items-center py-4">
501 <AppActivityIndicator />
502 </View>
503 ) : null
504 }
505 onEndReached={props.hasMore ? props.onLoadMore : undefined}
506 onEndReachedThreshold={0.35}
507 renderItem={renderBranch}
508 showsVerticalScrollIndicator={false}
509 />
510 );
511​
512 if (Platform.OS === "android") {
513 return (
514 <View className="flex-1 bg-sheet" collapsable={false}>
515 <NativeStackScreenOptions options={{ headerShown: false }} />
516 <AndroidScreenHeader
517 title={props.title}
518 hideBottomBorder
519 onBack={() => navigation.goBack()}
520 />
521 <View className="bg-header px-4 pb-3 pt-1">
522 <TextInput
523 autoCapitalize="none"
524 autoCorrect={false}
525 accessibilityLabel="Find a branch"
526 className="h-12 rounded-full border border-input-border bg-input px-4 font-sans text-base text-foreground"
527 selectionColorClassName="accent-focus/32"
528 cursorColorClassName="accent-focus"
529 selectionHandleColorClassName="accent-focus"
530 onChangeText={props.onQueryChange}
531 placeholder="Find a branch"
532 placeholderTextColorClassName="accent-placeholder"
533 value={props.query}
534 />
535 </View>
536 <ScreenContent>{branchContent}</ScreenContent>
537 </View>
538 );
539 }
540​
541 return (
542 <>
543 <NativeStackScreenOptions
544 options={{
545 headerShown: true,
546 title: props.title,
547 unstable_headerToolbarItems: usesNativeMailSearchToolbar
548 ? () => [
549 createNativeMailSearchToolbarItem({
550 onSearchTextChange: props.onQueryChange,
551 placeholder: "Find a branch",
552 searchTextChangeId: "new-task-branch-search-text",
553 showsSearchDismissButton: true,
554 }),
555 ]
556 : undefined,
557 headerSearchBarOptions: usesNativeMailSearchToolbar
558 ? undefined
559 : {
560 allowToolbarIntegration: true,
561 autoCapitalize: "none",
562 hideNavigationBar: false,
563 obscureBackground: false,
564 placeholder: "Find a branch",
565 onChangeText: (event) => {
566 props.onQueryChange(event.nativeEvent.text);
567 },
568 onCancelButtonPress: () => {
569 props.onQueryChange("");
570 },
571 },
572 }}
573 />
574 {usesNativeMailSearchToolbar ? null : (
575 <Toolbar placement="bottom">
576 <Toolbar.SearchBarSlot />
577 </Toolbar>
578 )}
579 {branchContent}
580 </>
581 );