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

GitOverviewSheet.tsx

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