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