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

GitOverviewSheet.tsx

394 lines14.2 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 { use, useEffect, useState } from "react";
19import { Platform, RefreshControl, View } from "react-native";
20import { NativeScrollView } from "../../../native/NativeScrollViewMarker";
21​
22import { useSafeAreaInsets } from "react-native-safe-area-context";
23import { AppBar } from "../../../components/ui/AppBar";
24import { ListRow } from "../../../components/ui/ListRow";
25import { ListSection } from "../../../components/ui/ListSection";
26import { ScreenContent } from "../../../components/ui/ScreenContent";
27import { useAdaptiveWorkspaceLayout } from "../../layout/AdaptiveWorkspaceLayout";
28import { InspectorSheetContext } from "../../layout/workspace-inspector-sheet";
29import { AppText as Text } from "../../../components/ui/AppText";
30import { NativeStackScreenOptions } from "../../../native/StackHeader";
31import { useEnvironmentQuery } from "../../../state/query";
32import { useThreadSelection } from "../../../state/use-thread-selection";
33import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
34import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
35import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
36import { vcsEnvironment } from "../../../state/vcs";
37import { menuItemIconName, statusSummary } from "./gitSheetComponents";
38import {
39 LinkedPullRequestRow,
40 linkedPullRequestKey,
41 useLinkedPullRequestLines,
42} from "../LinkedPullRequestList";
43import { useLinkedPullRequestActions } from "../useLinkedPullRequestActions";
44​
45type GitOverviewSheetProps = StaticScreenProps<{
46 readonly environmentId: string;
47 readonly threadId: string;
48}> & {
49 readonly presentation?: "sheet" | "inspector";
50};
51​
52export function GitOverviewSheet(props: GitOverviewSheetProps) {
53 const navigation = useNavigation();
54 const { environmentId, threadId } = props.route.params;
55 const isBlankLink = environmentId.trim().length === 0 || threadId.trim().length === 0;
56 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pops the navigator when the route link names a blank environment or thread
57 useEffect(() => {
58 if (isBlankLink) navigation.goBack();
59 }, [isBlankLink, navigation]);
60 if (isBlankLink) return null;
61 return <GitOverviewSheetContent {...props} />;
63​
64function GitOverviewSheetContent(props: GitOverviewSheetProps) {
65 const { layout } = useAdaptiveWorkspaceLayout();
66 const navigation = useNavigation();
67 const insets = useSafeAreaInsets();
68 const presentation = props.presentation ?? "sheet";
69 const isInspector = presentation === "inspector";
70 const closeInspectorSheet = use(InspectorSheetContext);
71 const presentRoute = (present: () => void) =>
72 closeInspectorSheet ? closeInspectorSheet(present) : present();
73 const environmentId = EnvironmentId.make(props.route.params.environmentId);
74 const threadId = ThreadId.make(props.route.params.threadId);
75 const { selectedThread, selectedThreadProject, selectedEnvironmentRuntime } =
76 useThreadSelection();
77 const openPullRequest = useOpenPullRequest({
78 replace: presentation === "sheet",
79 context: selectedThread ?? undefined,
80 });
81 const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
82 const linkedPrLines = useLinkedPullRequestLines(selectedThread, selectedEnvironmentRuntime);
83 const linkedPrActions = useLinkedPullRequestActions({
84 thread: selectedThread,
85 project: selectedThreadProject,
86 runtime: selectedEnvironmentRuntime,
87 });
88 const gitState = useSelectedThreadGitState();
89 const gitActions = useSelectedThreadGitActions();
90 const { canWriteSourceControl, canChangeThreadBranch } = gitActions;
91​
92 const gitStatus = useEnvironmentQuery(
93 selectedThread !== null && selectedThreadCwd !== null
94 ? vcsEnvironment.status({
95 environmentId: selectedThread.environmentId,
96 input: { cwd: selectedThreadCwd },
97 })
98 : null,
99 );
100​
101 const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD";
102 const currentStatusSummary = statusSummary(gitStatus.data);
103 const currentWorktreePath = selectedThreadWorktreePath;
104 const gitOperationLabel = gitState.gitOperationLabel;
105 const busy = gitOperationLabel !== null;
106 const isRepo = gitStatus.data?.isRepo ?? true;
107 const hasPrimaryRemote = gitStatus.data?.hasPrimaryRemote ?? false;
108 const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
109​
110 const menuItems = isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote) : [];
111​
112 const sheetMenuItems = menuItems.map((item) => ({
113 item: {
114 ...item,
115 disabled: item.disabled || (!canWriteSourceControl && item.kind !== "open_pr"),
116 },
117 disabledReason:
118 !canWriteSourceControl && item.kind !== "open_pr"
119 ? "This connection cannot change source control."
120 : getGitActionDisabledReason({
121 item,
122 gitStatus: gitStatus.data,
123 isBusy: busy,
124 hasOriginRemote: hasPrimaryRemote,
125 }),
126 }));
127​
128 const { shortLabel, singular } = sourceControlClients.get(
129 gitStatus.data?.sourceControlProvider?.kind,
130 ).changeRequest;
131​
132 const openExistingPr = async () => {
133 const prUrl = gitStatus.data?.pr?.state === "open" ? gitStatus.data.pr.url : null;
134 if (!prUrl) {
135 Dialog.alert(`No open ${shortLabel}`, `This branch does not have an open ${singular}.`);
136 return;
137 }
138 if (!(await openPullRequest(prUrl))) {
139 Dialog.alert(`Unable to open ${shortLabel}`, `The ${singular} could not be opened.`);
140 }
141 };
142​
143 const runActionWithPrompt = async (input: GitActionRequestInput) => {
144 if (!canWriteSourceControl) return;
145 const confirmableAction =
146 input.action === "push" ||
147 input.action === "create_pr" ||
148 input.action === "commit_push" ||
149 input.action === "commit_push_pr"
150 ? input.action
151 : null;
152 const branchName = gitStatus.data?.refName;
153 if (
154 branchName &&
155 confirmableAction &&
156 !input.featureBranch &&
157 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
158 ) {
159 presentRoute(() =>
160 navigation.navigate("GitConfirm", {
161 environmentId: String(environmentId),
162 threadId: String(threadId),
163 confirmAction: confirmableAction,
164 branchName,
165 includesCommit: String(
166 input.action === "commit_push" || input.action === "commit_push_pr",
167 ),
168 }),
169 );
170 return;
171 }
172​
173 // Close a sheet so the thread shows the action's progress.
174 if (!isInspector) navigation.goBack();
175 else closeInspectorSheet?.();
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 presentRoute(() =>
188 navigation.navigate("GitCommit", {
189 environmentId: String(environmentId),
190 threadId: String(threadId),
191 }),
192 );
193 return;
194 }
195 if (item.dialogAction === "push") {
196 await runActionWithPrompt({ action: "push" });
197 return;
198 }
199 if (item.dialogAction === "create_pr") {
200 await runActionWithPrompt({ action: "create_pr" });
201 }
202 };
203​
204 const rowStatusDetail = (item: (typeof menuItems)[number]): string | undefined => {
205 const status = gitStatus.data;
206 if (status == null) {
207 return undefined;
208 }
209 if (item.dialogAction === "commit" && status.hasWorkingTreeChanges) {
210 const fileCount = status.workingTree?.files.length ?? 0;
211 return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
212 }
213 if (item.dialogAction === "push" && (status.aheadCount ?? 0) > 0) {
214 const ahead = status.aheadCount ?? 0;
215 return `${ahead} commit${ahead === 1 ? "" : "s"} ahead`;
216 }
217 if (item.kind === "open_pr" && status.pr?.number != null) {
218 return `${shortLabel} #${status.pr.number} ${status.pr.state ?? "open"}`;
219 }
220 return undefined;
221 };
222​
223 const behindCount = gitStatus.data?.behindCount ?? 0;
224​
225 // Background refreshes also report pending; using that query flag would stick the RefreshControl spinner.
226 const [isRefreshing, setIsRefreshing] = useState(false);
227 const handleRefresh = async () => {
228 setIsRefreshing(true);
229 await gitActions.refreshSelectedThreadGitStatus();
230 setIsRefreshing(false);
231 };
232​
233 const content = (
234 <NativeScrollView
235 nestedScrollEnabled
236 alwaysBounceVertical
237 className="flex-1 android:bg-sheet-solid ios:bg-screen"
238 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
239 showsVerticalScrollIndicator={false}
240 contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
241 contentContainerStyle={{
242 paddingHorizontal: Platform.OS === "android" ? 8 : isInspector ? 12 : 20,
243 paddingTop: 8,
244 gap: Platform.OS === "android" ? 8 : 14,
245 }}
246 refreshControl={
247 Platform.OS === "ios" || isInspector ? (
248 <RefreshControl refreshing={isRefreshing} onRefresh={() => void handleRefresh()} />
249 ) : undefined
250 }
251 >
252 <ListSection>
253 {sheetMenuItems.map(({ item, disabledReason }) => (
254 <ListRow
255 key={`${item.id}-${item.label}`}
256 icon={menuItemIconName(item.icon)}
257 label={item.label}
258 description={disabledReason ?? rowStatusDetail(item)}
259 disabled={item.disabled}
260 onPress={() => void onPressMenuItem(item)}
261 />
262 ))}
263 {behindCount > 0 ? (
264 <ListRow
265 icon="arrow.down.circle"
266 label="Pull latest"
267 description={
268 canWriteSourceControl
269 ? `${behindCount} commit${behindCount === 1 ? "" : "s"} behind upstream`
270 : "This connection cannot change source control."
271 }
272 disabled={!canWriteSourceControl || busy || !isRepo}
273 onPress={() => void gitActions.onPullSelectedThreadBranch()}
274 />
275 ) : null}
276 <ListRow
277 icon="text.bubble"
278 label="Review changes"
279 description="Inspect changes, uncommitted edits, and turn diffs"
280 disabled={busy || !isRepo}
281 onPress={() => {
282 const params = { environmentId, threadId };
283 if (presentation === "sheet") {
284 navigation.dispatch(StackActions.replace("ThreadReview", params));
285 } else {
286 presentRoute(() =>
287 navigation.dispatch(CommonActions.navigate("ThreadReview", params)),
288 );
289 }
290 }}
291 />
292 <ListRow
293 icon="point.topleft.down.curvedto.point.bottomright.up"
294 label="Branches & worktrees"
295 description={
296 canChangeThreadBranch
297 ? "Switch branch, create branch, or move to a worktree"
298 : "View branches and worktrees"
299 }
300 disabled={busy || !isRepo}
301 onPress={() =>
302 presentRoute(() =>
303 navigation.navigate("GitBranches", {
304 environmentId: String(environmentId),
305 threadId: String(threadId),
306 }),
307 )
308 }
309 />
310 {linkedPrActions.canLink ? (
311 <ListRow
312 icon="link"
313 label={`Link ${linkedPrActions.terminology.singular}`}
314 description={`Attach a ${linkedPrActions.terminology.singular} by URL or number`}
315 onPress={linkedPrActions.promptLink}
316 />
317 ) : null}
318 </ListSection>
319​
320 {linkedPrLines.length > 0 ? (
321 <ListSection title={`Linked ${linkedPrActions.terminology.plural}`}>
322 {linkedPrLines.map((line, index) => (
323 <LinkedPullRequestRow
324 key={linkedPullRequestKey(line)}
325 line={line}
326 separator={index < linkedPrLines.length - 1}
327 surfaceClassName="text-grouped-card"
328 openPullRequest={openPullRequest}
329 actions={linkedPrActions}
330 />
331 ))}
332 </ListSection>
333 ) : null}
334​
335 {currentWorktreePath ? (
336 <ListSection title="Worktree">
337 <Text selectable textRole="footnote" className="p-4 text-foreground-muted">
338 {currentWorktreePath}
339 </Text>
340 </ListSection>
341 ) : null}
342 </NativeScrollView>
343 );
344​
345 const refresh = {
346 accessibilityLabel: "Refresh repository status",
347 disabled: busy || isRefreshing,
348 onPress: () => void handleRefresh(),
349 };
350​
351 if (isInspector) {
352 return (
353 <View collapsable={false} className="flex-1 ios:bg-screen android:bg-header">
354 <AppBar title={currentBranchLabel} subtitle={currentStatusSummary} refresh={refresh} />
355 <ScreenContent insetHorizontal>{content}</ScreenContent>
356 </View>
357 );
358 }
359​
360 if (Platform.OS === "ios") {
361 return (
362 <View collapsable={false} className="flex-1 bg-sheet">
363 <SheetHeader
364 presentation="native"
365 title={currentBranchLabel}
366 subtitle={currentStatusSummary}
367 onClose={() => navigation.goBack()}
368 />
369 {content}
370 </View>
371 );
372 }
373​
374 return (
375 <View
376 collapsable={false}
377 className={Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 bg-sheet"}
378 >
379 <NativeStackScreenOptions
380 options={{ sheetCornerRadius: Platform.OS === "android" ? 28 : undefined }}
381 />
382 <AppBar
383 sheet
384 title={currentBranchLabel}
385 hideBottomBorder={Platform.OS === "android"}
386 subtitle={currentStatusSummary}
387 onBack={() => navigation.goBack()}
388 refresh={refresh}
389 />
390​
391 <ScreenContent insetHorizontal={layout.usesSplitView}>{content}</ScreenContent>
392 </View>
393 );