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 const isBlankLink = environmentId.trim().length === 0 || threadId.trim().length === 0;
63 useEffect(() => {
64 if (isBlankLink) navigation.goBack();
65 }, [isBlankLink, navigation]);
66 if (isBlankLink) return null;
67 return <GitOverviewSheetContent {...props} />;
68}
69
70function GitOverviewSheetContent(props: GitOverviewSheetProps) {
71 const { layout } = useAdaptiveWorkspaceLayout();
72 const navigation = useNavigation();
73 const insets = useSafeAreaInsets();
74 const presentation = props.presentation ?? "sheet";
75 const openPullRequest = useOpenPullRequest({ replace: presentation === "sheet" });
76 const isInspector = presentation === "inspector";
77 const environmentId = EnvironmentId.make(props.route.params.environmentId);
78 const threadId = ThreadId.make(props.route.params.threadId);
79 const { selectedThread, selectedEnvironmentRuntime } = useThreadSelection();
80 const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
81 const supportsLinkedPrSnapshots =
82 selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.threadPullRequests === true;
83 const linkedPrChains = useMemo(
84 () =>
85 resolveThreadPullRequestChains(
86 supportsLinkedPrSnapshots ? (selectedThread?.pullRequests ?? []) : [],
87 ),
88 [selectedThread?.pullRequests, supportsLinkedPrSnapshots],
89 );
90 const gitState = useSelectedThreadGitState();
91 const gitActions = useSelectedThreadGitActions();
92 const { canWriteSourceControl, canChangeThreadBranch } = gitActions;
93 const theme = useUniwindTheme();
94 const foregroundColor = theme["--color-foreground"];
95 const sheetColor = theme["--color-sheet"];
96
97 const gitStatus = useEnvironmentQuery(
98 selectedThread !== null && selectedThreadCwd !== null
99 ? vcsEnvironment.status({
100 environmentId: selectedThread.environmentId,
101 input: { cwd: selectedThreadCwd },
102 })
103 : null,
104 );
105
106 const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD";
107 const currentStatusSummary = statusSummary(gitStatus.data);
108 const currentWorktreePath = selectedThreadWorktreePath;
109 const gitOperationLabel = gitState.gitOperationLabel;
110 const busy = gitOperationLabel !== null;
111 const isRepo = gitStatus.data?.isRepo ?? true;
112 const hasPrimaryRemote = gitStatus.data?.hasPrimaryRemote ?? false;
113 const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
114
115 const menuItems = useMemo(
116 () => (isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote) : []),
117 [busy, gitStatus.data, hasPrimaryRemote, isRepo],
118 );
119
120 const sheetMenuItems = useMemo(
121 () =>
122 menuItems.map((item) => ({
123 item: {
124 ...item,
125 disabled: item.disabled || (!canWriteSourceControl && item.kind !== "open_pr"),
126 },
127 disabledReason:
128 !canWriteSourceControl && item.kind !== "open_pr"
129 ? "This connection cannot change source control."
130 : getGitActionDisabledReason({
131 item,
132 gitStatus: gitStatus.data,
133 isBusy: busy,
134 hasOriginRemote: hasPrimaryRemote,
135 }),
136 })),
137 [busy, canWriteSourceControl, gitStatus.data, hasPrimaryRemote, menuItems],
138 );
139
140 const openExistingPr = useCallback(async () => {
141 const prUrl = gitStatus.data?.pr?.state === "open" ? gitStatus.data.pr.url : null;
142 if (!prUrl) {
143 Dialog.alert("No open PR", "This branch does not have an open pull request.");
144 return;
145 }
146 if (!(await openPullRequest(prUrl))) {
147 Dialog.alert("Unable to open PR", "The pull request could not be opened.");
148 }
149 }, [gitStatus.data, openPullRequest]);
150
151 const runActionWithPrompt = useCallback(
152 async (input: GitActionRequestInput) => {
153 if (!canWriteSourceControl) return;
154 const confirmableAction =
155 input.action === "push" ||
156 input.action === "create_pr" ||
157 input.action === "commit_push" ||
158 input.action === "commit_push_pr"
159 ? input.action
160 : null;
161 const branchName = gitStatus.data?.refName;
162 if (
163 branchName &&
164 confirmableAction &&
165 !input.featureBranch &&
166 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
167 ) {
168 navigation.navigate("GitConfirm", {
169 environmentId: String(environmentId),
170 threadId: String(threadId),
171 confirmAction: confirmableAction,
172 branchName,
173 includesCommit: String(
174 input.action === "commit_push" || input.action === "commit_push_pr",
175 ),
176 });
177 return;
178 }
179
180 if (!isInspector) {
181 navigation.goBack();
182 }
183 await gitActions.onRunSelectedThreadGitAction(input);
184 },
185 [
186 canWriteSourceControl,
187 environmentId,
188 gitActions,
189 gitStatus.data,
190 isDefaultRef,
191 isInspector,
192 navigation,
193 threadId,
194 ],
195 );
196
197 const onPressMenuItem = useCallback(
198 async (item: (typeof menuItems)[number]) => {
199 if (item.disabled) return;
200 if (item.kind === "open_pr") {
201 await openExistingPr();
202 return;
203 }
204 if (!canWriteSourceControl) return;
205 if (item.dialogAction === "commit") {
206 navigation.navigate("GitCommit", {
207 environmentId: String(environmentId),
208 threadId: String(threadId),
209 });
210 return;
211 }
212 if (item.dialogAction === "push") {
213 await runActionWithPrompt({ action: "push" });
214 return;
215 }
216 if (item.dialogAction === "create_pr") {
217 await runActionWithPrompt({ action: "create_pr" });
218 }
219 },
220 [
221 canWriteSourceControl,
222 environmentId,
223 openExistingPr,
224 navigation,
225 runActionWithPrompt,
226 threadId,
227 ],
228 );
229
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 // Tying RefreshControl to the query's isPending flag left the spinner stuck
255 // (the status query reports pending during quiet background refreshes too).
256 const [isRefreshing, setIsRefreshing] = useState(false);
257 const handleRefresh = useCallback(async () => {
258 setIsRefreshing(true);
259 try {
260 await gitActions.refreshSelectedThreadGitStatus();
261 } finally {
262 setIsRefreshing(false);
263 }
264 }, [gitActions]);
265
266 const content = (
267 <ScrollView
268 nestedScrollEnabled
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 Platform.OS === "ios" || isInspector ? (
281 <RefreshControl refreshing={isRefreshing} onRefresh={() => void handleRefresh()} />
282 ) : undefined
283 }
284 >
285 <View
286 className={`overflow-hidden bg-card android:rounded-[20px] ios:border ios:border-border ${
287 isInspector ? "ios:rounded-2xl ios:px-3 ios:py-1" : "ios:rounded-[22px] ios:px-4 ios:py-1"
288 }`}
289 >
290 {sheetMenuItems.map(({ item, disabledReason }, index) => (
291 <View key={`${item.id}-${item.label}`}>
292 {index > 0 && Platform.OS !== "android" ? (
293 <View className="ml-12 h-px bg-border" />
294 ) : null}
295 <SheetListRow
296 icon={menuItemIconName(item.icon)}
297 title={item.label}
298 subtitle={disabledReason ?? rowStatusDetail(item)}
299 disabled={item.disabled}
300 onPress={() => void onPressMenuItem(item)}
301 />
302 </View>
303 ))}
304 {behindCount > 0 ? (
305 <>
306 {Platform.OS !== "android" ? <View className="ml-12 h-px bg-border" /> : null}
307 <SheetListRow
308 icon="arrow.down.circle"
309 title="Pull latest"
310 subtitle={
311 canWriteSourceControl
312 ? `${behindCount} commit${behindCount === 1 ? "" : "s"} behind upstream`
313 : "This connection cannot change source control."
314 }
315 disabled={!canWriteSourceControl || busy || !isRepo}
316 onPress={() => void gitActions.onPullSelectedThreadBranch()}
317 />
318 </>
319 ) : null}
320 {Platform.OS !== "android" ? <View className="ml-12 h-px bg-border" /> : null}
321 <SheetListRow
322 icon="text.bubble"
323 title="Review changes"
324 subtitle="Inspect changes, uncommitted edits, and turn diffs"
325 disabled={busy || !isRepo}
326 onPress={() => {
327 const params = { environmentId, threadId };
328 navigation.dispatch(
329 resolveGitOverviewReviewNavigationAction(presentation) === "replace"
330 ? StackActions.replace("ThreadReview", params)
331 : CommonActions.navigate("ThreadReview", params),
332 );
333 }}
334 />
335 {Platform.OS !== "android" ? <View className="ml-12 h-px bg-border" /> : null}
336 <SheetListRow
337 icon="point.topleft.down.curvedto.point.bottomright.up"
338 title="Branches & worktrees"
339 subtitle={
340 canChangeThreadBranch
341 ? "Switch branch, create branch, or move to a worktree"
342 : "View branches and worktrees"
343 }
344 disabled={busy || !isRepo}
345 onPress={() =>
346 navigation.navigate("GitBranches", {
347 environmentId: String(environmentId),
348 threadId: String(threadId),
349 })
350 }
351 />
352 </View>
353
354 {linkedPrChains.length > 0 ? (
355 <View className="gap-2">
356 <Text className="px-1 text-xs font-t3-bold text-foreground-muted">
357 Linked pull requests
358 </Text>
359 {linkedPrChains.map((chain) => (
360 <View
361 key={threadPullRequestKeyOf(chain.layers[0]!)}
362 className="overflow-hidden bg-card android:rounded-[20px] ios:rounded-2xl ios:border ios:border-border ios:px-3 ios:py-1"
363 >
364 {chain.layers.length > 1 ? (
365 <View className="flex-row items-center gap-2 px-1 pt-2 pb-1">
366 <SymbolView
367 name="square.3.layers.3d"
368 size={14}
369 tintColorClassName="accent-foreground-muted"
370 />
371 <Text className="text-xs text-foreground-muted">
372 {chain.kind === "native" ? "Stack" : "Branch stack"} · {chain.layers.length} PRs
373 · bottom to top
374 </Text>
375 </View>
376 ) : null}
377 {chain.layers.map((link, index) => (
378 <View
379 key={threadPullRequestKeyOf(link)}
380 // Steps in per layer like the web list, capped so deep stacks keep their width.
381 style={{ paddingLeft: Math.min(chain.depths[index]!, 3) * 16 }}
382 >
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.
446 return (
447 <View collapsable={false} className="flex-1 bg-sheet">
448 <ScreenStack style={{ flex: 1 }}>
449 <Screen
450 activityState={2}
451 enabled
452 isNativeStack
453 screenId="thread-git-sheet-native"
454 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
455 style={{ backgroundColor: sheetColor, flex: 1 }}
456 >
457 <NativeSheetContent>{content}</NativeSheetContent>
458 <ScreenStackHeaderConfig
459 backgroundColor="rgba(0,0,0,0)"
460 color={foregroundColor}
461 hideBackButton
462 hideShadow={false}
463 navigationItemStyle="editor"
464 title={currentBranchLabel}
465 titleColor={foregroundColor}
466 titleFontSize={18}
467 titleFontWeight="800"
468 translucent
469 />
470 </Screen>
471 </ScreenStack>
472 </View>
473 );
474 }
475
476 const refreshMenu = (
477 <AndroidAnchoredMenu
478 title="Repository options"
479 actions={[
480 {
481 id: "refresh",
482 title: "Refresh repository status",
483 attributes: { disabled: busy || isRefreshing },
484 },
485 ]}
486 onPressAction={({ nativeEvent }) => {
487 if (nativeEvent.event === "refresh") void handleRefresh();
488 }}
489 >
490 {(open) => (
491 <AndroidHeaderIconButton
492 accessibilityLabel="Repository options"
493 icon="ellipsis"
494 onPress={open}
495 />
496 )}
497 </AndroidAnchoredMenu>
498 );
499
500 return (
501 <View
502 collapsable={false}
503 className={
504 Platform.OS === "android"
505 ? "flex-1 bg-header"
506 : isInspector
507 ? "flex-1 border-l border-border bg-sheet"
508 : "flex-1 bg-sheet"
509 }
510 >
511 {!isInspector ? (
512 <NativeStackScreenOptions
513 options={{ sheetCornerRadius: Platform.OS === "android" ? 28 : undefined }}
514 />
515 ) : null}
516 {isInspector ? (
517 <View
518 style={{
519 minHeight: props.headerInset ?? 0,
520 paddingTop: props.headerInset ?? 0,
521 }}
522 />
523 ) : null}
524
525 {isInspector ? (
526 <View className="gap-1 px-4 pb-4 pt-3 android:bg-header ios:border-b ios:border-border">
527 {Platform.OS === "android" ? (
528 <View className="absolute right-3 top-4 z-[1]">{refreshMenu}</View>
529 ) : (
530 <Pressable
531 className={
532 busy
533 ? "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle opacity-[0.45]"
534 : "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle"
535 }
536 disabled={busy}
537 onPress={() => void gitActions.refreshSelectedThreadGitStatus()}
538 >
539 <SymbolView
540 name="arrow.clockwise"
541 size={16}
542 tintColorClassName="accent-icon"
543 type="monochrome"
544 weight="medium"
545 />
546 </Pressable>
547 )}
548 <Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
549 Repository
550 </Text>
551 <Text className="pr-10 text-xl font-t3-bold">{currentBranchLabel}</Text>
552 <Text className="text-foreground-secondary text-sm font-medium leading-normal">
553 {currentStatusSummary}
554 </Text>
555 </View>
556 ) : (
557 <AndroidSheetHeader
558 title={currentBranchLabel}
559 hideBottomBorder={Platform.OS === "android"}
560 subtitle={currentStatusSummary}
561 onBack={() => navigation.goBack()}
562 trailing={Platform.OS === "android" ? refreshMenu : undefined}
563 actions={
564 Platform.OS === "android"
565 ? undefined
566 : [
567 {
568 accessibilityLabel: "Refresh repository status",
569 disabled: busy,
570 icon: "arrow.clockwise",
571 onPress: () => void gitActions.refreshSelectedThreadGitStatus(),
572 },
573 ]
574 }
575 />
576 )}
577
578 <ScreenContent insetHorizontal={layout.usesSplitView}>{content}</ScreenContent>
579 </View>
580 );
581}