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

GitOverviewSheet.tsx

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