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