Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitOverviewSheet.tsx

525 lines19.3 KB

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