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

GitOverviewSheet.tsx

577 lines20.8 KB

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} />;
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 key={threadPullRequestKeyOf(link)}>
379 {index > 0 && Platform.OS !== "android" ? (
380 <View className="ml-12 h-px bg-border" />
381 ) : null}
382 <SheetListRow
383 icon="arrow.triangle.pull"
384 title={`#${link.number} ${link.snapshot?.title ?? "Pull request"}`}
385 subtitle={`${link.repository} · ${link.snapshot === null ? "Status pending" : link.snapshot.isDraft && link.snapshot.state === "open" ? "Draft" : link.snapshot.state}${link.watch === undefined ? "" : " · Watching"}`}
386 onPress={() => {
387 void openPullRequest(link.url).then((opened) => {
388 if (!opened)
389 Dialog.alert(
390 "Unable to open PR",
391 "The pull request could not be opened.",
392 );
393 });
394 }}
395 />
396 </View>
397 ))}
398 </View>
399 ))}
400 </View>
401 ) : null}
402​
403 {currentWorktreePath ? <MetaCard label="Worktree" value={currentWorktreePath} /> : null}
404 </ScrollView>
405 );
406​
407 if (isInspector && Platform.OS === "ios") {
408 return (
409 <View collapsable={false} className="flex-1 border-l border-border bg-sheet">
410 <ScreenStack style={{ flex: 1 }}>
411 <Screen
412 activityState={2}
413 enabled
414 isNativeStack
415 screenId="thread-git-inspector-native"
416 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
417 style={{ backgroundColor: sheetColor, flex: 1 }}
418 >
419 <NativeSheetContent>{content}</NativeSheetContent>
420 <ScreenStackHeaderConfig
421 backgroundColor="rgba(0,0,0,0)"
422 color={foregroundColor}
423 hideBackButton
424 hideShadow={false}
425 navigationItemStyle="editor"
426 title={currentBranchLabel}
427 titleColor={foregroundColor}
428 titleFontSize={17}
429 titleFontWeight="700"
430 translucent
431 />
432 </Screen>
433 </ScreenStack>
434 </View>
435 );
436 }
437​
438 if (Platform.OS === "ios") {
439 // Compact form sheet: a plain screen presented as formSheet never renders a
440 // stack header, so — like the Settings sheet — the header must come from a
441 // nested native stack INSIDE the sheet.
442 return (
443 <View collapsable={false} className="flex-1 bg-sheet">
444 <ScreenStack style={{ flex: 1 }}>
445 <Screen
446 activityState={2}
447 enabled
448 isNativeStack
449 screenId="thread-git-sheet-native"
450 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
451 style={{ backgroundColor: sheetColor, flex: 1 }}
452 >
453 <NativeSheetContent>{content}</NativeSheetContent>
454 <ScreenStackHeaderConfig
455 backgroundColor="rgba(0,0,0,0)"
456 color={foregroundColor}
457 hideBackButton
458 hideShadow={false}
459 navigationItemStyle="editor"
460 title={currentBranchLabel}
461 titleColor={foregroundColor}
462 titleFontSize={18}
463 titleFontWeight="800"
464 translucent
465 />
466 </Screen>
467 </ScreenStack>
468 </View>
469 );
470 }
471​
472 const refreshMenu = (
473 <AndroidAnchoredMenu
474 title="Repository options"
475 actions={[
476 {
477 id: "refresh",
478 title: "Refresh repository status",
479 attributes: { disabled: busy || isRefreshing },
480 },
481 ]}
482 onPressAction={({ nativeEvent }) => {
483 if (nativeEvent.event === "refresh") void handleRefresh();
484 }}
485 >
486 {(open) => (
487 <AndroidHeaderIconButton
488 accessibilityLabel="Repository options"
489 icon="ellipsis"
490 onPress={open}
491 />
492 )}
493 </AndroidAnchoredMenu>
494 );
495​
496 return (
497 <View
498 collapsable={false}
499 className={
500 Platform.OS === "android"
501 ? "flex-1 bg-header"
502 : isInspector
503 ? "flex-1 border-l border-border bg-sheet"
504 : "flex-1 bg-sheet"
505 }
506 >
507 {!isInspector ? (
508 <NativeStackScreenOptions
509 options={{ sheetCornerRadius: Platform.OS === "android" ? 28 : undefined }}
510 />
511 ) : null}
512 {isInspector ? (
513 <View
514 style={{
515 minHeight: props.headerInset ?? 0,
516 paddingTop: props.headerInset ?? 0,
517 }}
518 />
519 ) : null}
520​
521 {isInspector ? (
522 <View className="gap-1 px-4 pb-4 pt-3 android:bg-header ios:border-b ios:border-border">
523 {Platform.OS === "android" ? (
524 <View className="absolute right-3 top-4 z-[1]">{refreshMenu}</View>
525 ) : (
526 <Pressable
527 className={
528 busy
529 ? "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle opacity-[0.45]"
530 : "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle"
531 }
532 disabled={busy}
533 onPress={() => void gitActions.refreshSelectedThreadGitStatus()}
534 >
535 <SymbolView
536 name="arrow.clockwise"
537 size={16}
538 tintColorClassName="accent-icon"
539 type="monochrome"
540 weight="medium"
541 />
542 </Pressable>
543 )}
544 <Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
545 Repository
546 </Text>
547 <Text className="pr-10 text-xl font-t3-bold">{currentBranchLabel}</Text>
548 <Text className="text-foreground-secondary text-sm font-medium leading-normal">
549 {currentStatusSummary}
550 </Text>
551 </View>
552 ) : (
553 <AndroidSheetHeader
554 title={currentBranchLabel}
555 hideBottomBorder={Platform.OS === "android"}
556 subtitle={currentStatusSummary}
557 onBack={() => navigation.goBack()}
558 trailing={Platform.OS === "android" ? refreshMenu : undefined}
559 actions={
560 Platform.OS === "android"
561 ? undefined
562 : [
563 {
564 accessibilityLabel: "Refresh repository status",
565 disabled: busy,
566 icon: "arrow.clockwise",
567 onPress: () => void gitActions.refreshSelectedThreadGitStatus(),
568 },
569 ]
570 }
571 />
572 )}
573​
574 <ScreenContent insetHorizontal={layout.usesSplitView}>{content}</ScreenContent>
575 </View>
576 );