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

NewTaskContextPickerScreens.tsx

609 lines19.8 KB

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