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