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