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

NewTaskContextPickerScreens.tsx

469 lines15.3 KB

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