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

GitOverviewSheet.tsx

549 lines19.9 KB

1import {
2 type GitActionRequestInput,
3 buildMenuItems,
4 getGitActionDisabledReason,
5 requiresDefaultBranchConfirmation,
6} from "@t3tools/client-runtime/state/vcs";
7import {
8 resolveThreadPullRequestChains,
9 threadPullRequestKeyOf,
10} from "@t3tools/shared/threadPullRequests";
11import { EnvironmentId, ThreadId } from "@t3tools/contracts";
12import {
13 CommonActions,
14 StackActions,
15 useNavigation,
16 type StaticScreenProps,
17} from "@react-navigation/native";
18import { SymbolView } from "../../../components/AppSymbol";
19import { useCallback, useEffect, useMemo, useState } from "react";
20import { Alert, Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
21​
22import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
23import { useSafeAreaInsets } from "react-native-safe-area-context";
24import { useUniwindTheme } from "../../../lib/useUniwindTheme";
25import {
26 AndroidHeaderIconButton,
27 AndroidSheetHeader,
28} from "../../../components/AndroidScreenHeader";
29import { AndroidAnchoredMenu } from "../../../components/AndroidAnchoredMenu";
30import { MaterialScreenContent } from "../../../components/MaterialScreenContent";
31import { useAdaptiveWorkspaceLayout } from "../../layout/AdaptiveWorkspaceLayout";
32import { AppText as Text } from "../../../components/AppText";
33import {
34 NativeStackScreenOptions,
35 nativeHeaderScrollEdgeEffects,
36} from "../../../native/StackHeader";
37import { tryOpenExternalUrl } from "../../../lib/openExternalUrl";
38import { useEnvironmentQuery } from "../../../state/query";
39import { useThreadSelection } from "../../../state/use-thread-selection";
40import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
41import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
42import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
43import { vcsEnvironment } from "../../../state/vcs";
44import { resolveGitOverviewReviewNavigationAction } from "./git-overview-navigation";
45import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
46​
47const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
48​
49type GitOverviewSheetProps = StaticScreenProps<{
50 readonly environmentId: string;
51 readonly threadId: string;
52}> & {
53 readonly headerInset?: number;
54 readonly presentation?: "sheet" | "inspector";
55};
56​
57export function GitOverviewSheet(props: GitOverviewSheetProps) {
58 const { layout } = useAdaptiveWorkspaceLayout();
59 const navigation = useNavigation();
60 const insets = useSafeAreaInsets();
61 const presentation = props.presentation ?? "sheet";
62 const isInspector = presentation === "inspector";
63 const environmentId = EnvironmentId.make(props.route.params.environmentId);
64 const threadId = ThreadId.make(props.route.params.threadId);
65 const { selectedThread, selectedEnvironmentRuntime } = useThreadSelection();
66 const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
67 const supportsLinkedPrSnapshots =
68 selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.threadPullRequests === true;
69 const linkedPrChains = useMemo(
70 () =>
71 resolveThreadPullRequestChains(
72 supportsLinkedPrSnapshots ? (selectedThread?.pullRequests ?? []) : [],
73 ),
74 [selectedThread?.pullRequests, supportsLinkedPrSnapshots],
75 );
76 const gitState = useSelectedThreadGitState();
77 const gitActions = useSelectedThreadGitActions();
78 const theme = useUniwindTheme();
79 const foregroundColor = theme["--color-foreground"];
80 const sheetColor = theme["--color-sheet"];
81​
82 const gitStatus = useEnvironmentQuery(
83 selectedThread !== null && selectedThreadCwd !== null
84 ? vcsEnvironment.status({
85 environmentId: selectedThread.environmentId,
86 input: { cwd: selectedThreadCwd },
87 })
88 : null,
89 );
90​
91 const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD";
92 const currentStatusSummary = statusSummary(gitStatus.data);
93 const currentWorktreePath = selectedThreadWorktreePath;
94 const gitOperationLabel = gitState.gitOperationLabel;
95 const busy = gitOperationLabel !== null;
96 const isRepo = gitStatus.data?.isRepo ?? true;
97 const hasPrimaryRemote = gitStatus.data?.hasPrimaryRemote ?? false;
98 const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
99​
100 const menuItems = useMemo(
101 () => (isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote) : []),
102 [busy, gitStatus.data, hasPrimaryRemote, isRepo],
103 );
104​
105 const sheetMenuItems = useMemo(
106 () =>
107 menuItems.map((item) => ({
108 item,
109 disabledReason: getGitActionDisabledReason({
110 item,
111 gitStatus: gitStatus.data,
112 isBusy: busy,
113 hasOriginRemote: hasPrimaryRemote,
114 }),
115 })),
116 [busy, gitStatus.data, hasPrimaryRemote, menuItems],
117 );
118​
119 useEffect(() => {
120 void gitActions.refreshSelectedThreadGitStatus({ quiet: true });
121 }, [gitActions]);
122​
123 const openExistingPr = useCallback(async () => {
124 const prUrl = gitStatus.data?.pr?.state === "open" ? gitStatus.data.pr.url : null;
125 if (!prUrl) {
126 Alert.alert("No open PR", "This branch does not have an open pull request.");
127 return;
128 }
129 if (!(await tryOpenExternalUrl(prUrl, "pull-request"))) {
130 Alert.alert("Unable to open PR", "The pull request could not be opened.");
131 }
132 }, [gitStatus.data]);
133​
134 const runActionWithPrompt = useCallback(
135 async (input: GitActionRequestInput) => {
136 const confirmableAction =
137 input.action === "push" ||
138 input.action === "create_pr" ||
139 input.action === "commit_push" ||
140 input.action === "commit_push_pr"
141 ? input.action
142 : null;
143 const branchName = gitStatus.data?.refName;
144 if (
145 branchName &&
146 confirmableAction &&
147 !input.featureBranch &&
148 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
149 ) {
150 navigation.navigate("GitConfirm", {
151 environmentId: String(environmentId),
152 threadId: String(threadId),
153 confirmAction: confirmableAction,
154 branchName,
155 includesCommit: String(
156 input.action === "commit_push" || input.action === "commit_push_pr",
157 ),
158 });
159 return;
160 }
161​
162 if (!isInspector) {
163 navigation.goBack();
164 }
165 await gitActions.onRunSelectedThreadGitAction(input);
166 },
167 [environmentId, gitActions, gitStatus.data, isDefaultRef, isInspector, navigation, threadId],
168 );
169​
170 const onPressMenuItem = useCallback(
171 async (item: (typeof menuItems)[number]) => {
172 if (item.disabled) return;
173 if (item.kind === "open_pr") {
174 await openExistingPr();
175 return;
176 }
177 if (item.dialogAction === "commit") {
178 navigation.navigate("GitCommit", {
179 environmentId: String(environmentId),
180 threadId: String(threadId),
181 });
182 return;
183 }
184 if (item.dialogAction === "push") {
185 await runActionWithPrompt({ action: "push" });
186 return;
187 }
188 if (item.dialogAction === "create_pr") {
189 await runActionWithPrompt({ action: "create_pr" });
190 }
191 },
192 [environmentId, openExistingPr, navigation, runActionWithPrompt, threadId],
193 );
194​
195 // Status facts live on the relevant rows instead of crowding the header
196 // subtitle: files changed → Commit, ahead → Push, PR → View PR, behind → Pull.
197 const rowStatusDetail = useCallback(
198 (item: (typeof menuItems)[number]): string | undefined => {
199 const status = gitStatus.data;
200 if (status == null) {
201 return undefined;
202 }
203 if (item.dialogAction === "commit" && status.hasWorkingTreeChanges) {
204 const fileCount = status.workingTree?.files.length ?? 0;
205 return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
206 }
207 if (item.dialogAction === "push" && (status.aheadCount ?? 0) > 0) {
208 const ahead = status.aheadCount ?? 0;
209 return `${ahead} commit${ahead === 1 ? "" : "s"} ahead`;
210 }
211 if (item.kind === "open_pr" && status.pr?.number != null) {
212 return `PR #${status.pr.number} ${status.pr.state ?? "open"}`;
213 }
214 return undefined;
215 },
216 [gitStatus.data, menuItems],
217 );
218​
219 const behindCount = gitStatus.data?.behindCount ?? 0;
220​
221 // Deterministic pull-to-refresh state. Tying RefreshControl to the query's
222 // isPending flag left the spinner stuck (the status query reports pending
223 // during quiet background refreshes too).
224 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
225 const handlePullRefresh = useCallback(async () => {
226 setIsPullRefreshing(true);
227 try {
228 await gitActions.refreshSelectedThreadGitStatus();
229 } finally {
230 setIsPullRefreshing(false);
231 }
232 }, [gitActions]);
233​
234 const content = (
235 <ScrollView
236 alwaysBounceVertical
237 className={Platform.OS === "android" ? "flex-1 bg-sheet-solid" : "flex-1 bg-screen"}
238 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
239 showsVerticalScrollIndicator={false}
240 contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
241 contentContainerStyle={{
242 paddingHorizontal: Platform.OS === "android" ? 8 : isInspector ? 12 : 20,
243 paddingTop: 8,
244 gap: Platform.OS === "android" ? 8 : 14,
245 }}
246 refreshControl={
247 <RefreshControl refreshing={isPullRefreshing} onRefresh={() => void handlePullRefresh()} />
248 }
249 >
250 <View
251 className={
252 Platform.OS === "android"
253 ? "overflow-hidden rounded-[20px] bg-card"
254 : isInspector
255 ? "overflow-hidden rounded-2xl border border-border bg-card px-3 py-1"
256 : "overflow-hidden rounded-[22px] border border-border bg-card px-4 py-1"
257 }
258 >
259 {sheetMenuItems.map(({ item, disabledReason }, index) => (
260 <View key={`${item.id}-${item.label}`}>
261 {index > 0 && Platform.OS !== "android" ? (
262 <View className="ml-12 h-px bg-border" />
263 ) : null}
264 <SheetListRow
265 icon={menuItemIconName(item.icon)}
266 title={item.label}
267 subtitle={disabledReason ?? rowStatusDetail(item)}
268 disabled={item.disabled}
269 onPress={() => void onPressMenuItem(item)}
270 />
271 </View>
272 ))}
273 {behindCount > 0 ? (
274 <>
275 {Platform.OS !== "android" ? <View className="ml-12 h-px bg-border" /> : null}
276 <SheetListRow
277 icon="arrow.down.circle"
278 title="Pull latest"
279 subtitle={`${behindCount} commit${behindCount === 1 ? "" : "s"} behind upstream`}
280 disabled={busy || !isRepo}
281 onPress={() => void gitActions.onPullSelectedThreadBranch()}
282 />
283 </>
284 ) : null}
285 {Platform.OS !== "android" ? <View className="ml-12 h-px bg-border" /> : null}
286 <SheetListRow
287 icon="text.bubble"
288 title="Review changes"
289 subtitle="Inspect turn diffs, worktree changes, and base branch diff"
290 disabled={busy || !isRepo}
291 onPress={() => {
292 const params = { environmentId, threadId };
293 navigation.dispatch(
294 resolveGitOverviewReviewNavigationAction(presentation) === "replace"
295 ? StackActions.replace("ThreadReview", params)
296 : CommonActions.navigate("ThreadReview", params),
297 );
298 }}
299 />
300 {Platform.OS !== "android" ? <View className="ml-12 h-px bg-border" /> : null}
301 <SheetListRow
302 icon="point.topleft.down.curvedto.point.bottomright.up"
303 title="Branches & worktrees"
304 subtitle="Switch branch, create branch, or move to a worktree"
305 disabled={busy || !isRepo}
306 onPress={() =>
307 navigation.navigate("GitBranches", {
308 environmentId: String(environmentId),
309 threadId: String(threadId),
310 })
311 }
312 />
313 </View>
314​
315 {linkedPrChains.length > 0 ? (
316 <View className="gap-2">
317 <Text className="px-1 text-xs font-t3-bold text-foreground-muted">
318 Linked pull requests
319 </Text>
320 {linkedPrChains.map((chain) => (
321 <View
322 key={threadPullRequestKeyOf(chain.layers[0]!)}
323 className={
324 Platform.OS === "android"
325 ? "overflow-hidden rounded-[20px] bg-card"
326 : "overflow-hidden rounded-2xl border border-border bg-card px-3 py-1"
327 }
328 >
329 {chain.layers.length > 1 ? (
330 <View className="flex-row items-center gap-2 px-1 pt-2 pb-1">
331 <SymbolView
332 name="square.3.layers.3d"
333 size={14}
334 tintColorClassName="accent-foreground-muted"
335 />
336 <Text className="text-xs text-foreground-muted">
337 {chain.kind === "native" ? "Stack" : "Branch stack"} · {chain.layers.length} PRs
338 · bottom to top
339 </Text>
340 </View>
341 ) : null}
342 {chain.layers.map((link, index) => (
343 <View key={threadPullRequestKeyOf(link)}>
344 {index > 0 && Platform.OS !== "android" ? (
345 <View className="ml-12 h-px bg-border" />
346 ) : null}
347 <SheetListRow
348 icon="arrow.triangle.pull"
349 title={`#${link.number} ${link.snapshot?.title ?? "Pull request"}`}
350 subtitle={`${link.repository} · ${link.snapshot === null ? "Status pending" : link.snapshot.isDraft && link.snapshot.state === "open" ? "Draft" : link.snapshot.state}`}
351 onPress={() => {
352 void tryOpenExternalUrl(link.url, "pull-request").then((opened) => {
353 if (!opened)
354 Alert.alert("Unable to open PR", "The pull request could not be opened.");
355 });
356 }}
357 />
358 </View>
359 ))}
360 </View>
361 ))}
362 </View>
363 ) : null}
364​
365 {currentWorktreePath ? <MetaCard label="Worktree" value={currentWorktreePath} /> : null}
366 </ScrollView>
367 );
368​
369 if (isInspector && Platform.OS === "ios") {
370 return (
371 <View collapsable={false} className="flex-1 border-l border-border bg-sheet">
372 <ScreenStack style={{ flex: 1 }}>
373 <Screen
374 activityState={2}
375 enabled
376 isNativeStack
377 screenId="thread-git-inspector-native"
378 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
379 style={{ backgroundColor: sheetColor, flex: 1 }}
380 >
381 {content}
382 <ScreenStackHeaderConfig
383 backgroundColor="rgba(0,0,0,0)"
384 color={foregroundColor}
385 hideBackButton
386 hideShadow={false}
387 navigationItemStyle="editor"
388 title={currentBranchLabel}
389 titleColor={foregroundColor}
390 titleFontSize={17}
391 titleFontWeight="700"
392 translucent
393 />
394 </Screen>
395 </ScreenStack>
396 </View>
397 );
398 }
399​
400 if (Platform.OS === "ios") {
401 // Compact form sheet: a plain screen presented as formSheet never renders a
402 // stack header, so — like the Settings sheet — the header must come from a
403 // nested native stack INSIDE the sheet. This reuses the exact structure of the
404 // inspector branch below: branch as the title, status summary as the native
405 // subtitle, and content that owns pull-to-refresh.
406 return (
407 <View collapsable={false} className="flex-1 bg-sheet">
408 <ScreenStack style={{ flex: 1 }}>
409 <Screen
410 activityState={2}
411 enabled
412 isNativeStack
413 screenId="thread-git-sheet-native"
414 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
415 style={{ backgroundColor: sheetColor, flex: 1 }}
416 >
417 {content}
418 <ScreenStackHeaderConfig
419 backgroundColor="rgba(0,0,0,0)"
420 color={foregroundColor}
421 hideBackButton
422 hideShadow={false}
423 navigationItemStyle="editor"
424 title={currentBranchLabel}
425 titleColor={foregroundColor}
426 titleFontSize={18}
427 titleFontWeight="800"
428 translucent
429 />
430 </Screen>
431 </ScreenStack>
432 </View>
433 );
434 }
435​
436 const refreshMenu = (
437 <AndroidAnchoredMenu
438 title="Repository options"
439 actions={[
440 {
441 id: "refresh",
442 title: "Refresh repository status",
443 attributes: { disabled: busy || isPullRefreshing },
444 },
445 ]}
446 onPressAction={({ nativeEvent }) => {
447 if (nativeEvent.event === "refresh") void handlePullRefresh();
448 }}
449 >
450 {(open) => (
451 <AndroidHeaderIconButton
452 accessibilityLabel="Repository options"
453 icon="ellipsis"
454 onPress={open}
455 />
456 )}
457 </AndroidAnchoredMenu>
458 );
459​
460 return (
461 <View
462 collapsable={false}
463 className={
464 Platform.OS === "android"
465 ? "flex-1 bg-header"
466 : isInspector
467 ? "flex-1 border-l border-border bg-sheet"
468 : "flex-1 bg-sheet"
469 }
470 >
471 {!isInspector ? (
472 <NativeStackScreenOptions
473 options={{ sheetCornerRadius: Platform.OS === "android" ? 28 : undefined }}
474 />
475 ) : null}
476 {isInspector ? (
477 <View
478 style={{
479 minHeight: props.headerInset ?? 0,
480 paddingTop: props.headerInset ?? 0,
481 }}
482 />
483 ) : null}
484​
485 {isInspector ? (
486 <View
487 className={
488 Platform.OS === "android"
489 ? "gap-1 bg-header px-4 pb-4 pt-3"
490 : "gap-1 border-b border-border px-4 pb-4 pt-3"
491 }
492 >
493 {Platform.OS === "android" ? (
494 <View className="absolute right-3 top-4 z-[1]">{refreshMenu}</View>
495 ) : (
496 <Pressable
497 className={
498 busy
499 ? "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle opacity-[0.45]"
500 : "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle"
501 }
502 disabled={busy}
503 onPress={() => void gitActions.refreshSelectedThreadGitStatus()}
504 >
505 <SymbolView
506 name="arrow.clockwise"
507 size={16}
508 tintColorClassName="accent-icon"
509 type="monochrome"
510 weight="medium"
511 />
512 </Pressable>
513 )}
514 <Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
515 Repository
516 </Text>
517 <Text className="pr-10 text-xl font-t3-bold">{currentBranchLabel}</Text>
518 <Text className="text-foreground-secondary text-sm font-medium leading-normal">
519 {currentStatusSummary}
520 </Text>
521 </View>
522 ) : (
523 <AndroidSheetHeader
524 title={currentBranchLabel}
525 hideBottomBorder={Platform.OS === "android"}
526 subtitle={currentStatusSummary}
527 onBack={() => navigation.goBack()}
528 trailing={Platform.OS === "android" ? refreshMenu : undefined}
529 actions={
530 Platform.OS === "android"
531 ? undefined
532 : [
533 {
534 accessibilityLabel: "Refresh repository status",
535 disabled: busy,
536 icon: "arrow.clockwise",
537 onPress: () => void gitActions.refreshSelectedThreadGitStatus(),
538 },
539 ]
540 }
541 />
542 )}
543​
544 <MaterialScreenContent insetHorizontal={layout.usesSplitView}>
545 {content}
546 </MaterialScreenContent>
547 </View>
548 );