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

GitOverviewSheet.tsx

361 lines13.2 KB

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