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

GitOverviewSheet.tsx

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