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