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

NewTaskContextPickerScreens.tsx

579 lines19.2 KB

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