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

NewTaskContextPickerScreens.tsx

540 lines17.4 KB

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