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

GitOverviewSheet.tsx

490 lines17.1 KB

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