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

GitOverviewSheet.tsx

419 lines14.9 KB

1import {
2 type GitActionRequestInput,
3 buildMenuItems,
4 getGitActionDisabledReason,
5 requiresDefaultBranchConfirmation,
6} from "@t3tools/client-runtime/state/vcs";
7import { EnvironmentId, ThreadId } from "@t3tools/contracts";
8import {
9 CommonActions,
10 StackActions,
11 useNavigation,
12 type StaticScreenProps,
13} from "@react-navigation/native";
14import { SymbolView } from "../../../components/AppSymbol";
15import { useCallback, useEffect, useMemo, useState } from "react";
16import { Alert, Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
17​
18import { Screen, ScreenStack, ScreenStackHeaderConfig } from "react-native-screens";
19import { useSafeAreaInsets } from "react-native-safe-area-context";
20import { useUniwindTheme } from "../../../lib/useUniwindTheme";
21​
22import { AndroidSheetHeader } from "../../../components/AndroidScreenHeader";
23import { AppText as Text } from "../../../components/AppText";
24import { nativeHeaderScrollEdgeEffects } from "../../../native/StackHeader";
25import { tryOpenExternalUrl } from "../../../lib/openExternalUrl";
26import { useEnvironmentQuery } from "../../../state/query";
27import { useThreadSelection } from "../../../state/use-thread-selection";
28import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
29import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
30import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
31import { vcsEnvironment } from "../../../state/vcs";
32import { resolveGitOverviewReviewNavigationAction } from "./git-overview-navigation";
33import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
34​
35const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
36​
37type GitOverviewSheetProps = StaticScreenProps<{
38 readonly environmentId: string;
39 readonly threadId: string;
40}> & {
41 readonly headerInset?: number;
42 readonly presentation?: "sheet" | "inspector";
43};
44​
45export function GitOverviewSheet(props: GitOverviewSheetProps) {
46 const navigation = useNavigation();
47 const insets = useSafeAreaInsets();
48 const presentation = props.presentation ?? "sheet";
49 const isInspector = presentation === "inspector";
50 const environmentId = EnvironmentId.make(props.route.params.environmentId);
51 const threadId = ThreadId.make(props.route.params.threadId);
52 const { selectedThread } = useThreadSelection();
53 const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
54 const gitState = useSelectedThreadGitState();
55 const gitActions = useSelectedThreadGitActions();
56 const theme = useUniwindTheme();
57 const foregroundColor = theme["--color-foreground"];
58 const sheetColor = theme["--color-sheet"];
59​
60 const gitStatus = useEnvironmentQuery(
61 selectedThread !== null && selectedThreadCwd !== null
62 ? vcsEnvironment.status({
63 environmentId: selectedThread.environmentId,
64 input: { cwd: selectedThreadCwd },
65 })
66 : null,
67 );
68​
69 const currentBranchLabel = gitStatus.data?.refName ?? selectedThread?.branch ?? "Detached HEAD";
70 const currentStatusSummary = statusSummary(gitStatus.data);
71 const currentWorktreePath = selectedThreadWorktreePath;
72 const gitOperationLabel = gitState.gitOperationLabel;
73 const busy = gitOperationLabel !== null;
74 const isRepo = gitStatus.data?.isRepo ?? true;
75 const hasPrimaryRemote = gitStatus.data?.hasPrimaryRemote ?? false;
76 const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
77​
78 const menuItems = useMemo(
79 () => (isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote) : []),
80 [busy, gitStatus.data, hasPrimaryRemote, isRepo],
81 );
82​
83 const sheetMenuItems = useMemo(
84 () =>
85 menuItems.map((item) => ({
86 item,
87 disabledReason: getGitActionDisabledReason({
88 item,
89 gitStatus: gitStatus.data,
90 isBusy: busy,
91 hasOriginRemote: hasPrimaryRemote,
92 }),
93 })),
94 [busy, gitStatus.data, hasPrimaryRemote, menuItems],
95 );
96​
97 useEffect(() => {
98 void gitActions.refreshSelectedThreadGitStatus({ quiet: true });
99 }, [gitActions]);
100​
101 const openExistingPr = useCallback(async () => {
102 const prUrl = gitStatus.data?.pr?.state === "open" ? gitStatus.data.pr.url : null;
103 if (!prUrl) {
104 Alert.alert("No open PR", "This branch does not have an open pull request.");
105 return;
106 }
107 if (!(await tryOpenExternalUrl(prUrl, "pull-request"))) {
108 Alert.alert("Unable to open PR", "The pull request could not be opened.");
109 }
110 }, [gitStatus.data]);
111​
112 const runActionWithPrompt = useCallback(
113 async (input: GitActionRequestInput) => {
114 const confirmableAction =
115 input.action === "push" ||
116 input.action === "create_pr" ||
117 input.action === "commit_push" ||
118 input.action === "commit_push_pr"
119 ? input.action
120 : null;
121 const branchName = gitStatus.data?.refName;
122 if (
123 branchName &&
124 confirmableAction &&
125 !input.featureBranch &&
126 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
127 ) {
128 navigation.navigate("GitConfirm", {
129 environmentId: String(environmentId),
130 threadId: String(threadId),
131 confirmAction: confirmableAction,
132 branchName,
133 includesCommit: String(
134 input.action === "commit_push" || input.action === "commit_push_pr",
135 ),
136 });
137 return;
138 }
139​
140 if (!isInspector) {
141 navigation.goBack();
142 }
143 await gitActions.onRunSelectedThreadGitAction(input);
144 },
145 [environmentId, gitActions, gitStatus.data, isDefaultRef, isInspector, navigation, threadId],
146 );
147​
148 const onPressMenuItem = useCallback(
149 async (item: (typeof menuItems)[number]) => {
150 if (item.disabled) return;
151 if (item.kind === "open_pr") {
152 await openExistingPr();
153 return;
154 }
155 if (item.dialogAction === "commit") {
156 navigation.navigate("GitCommit", {
157 environmentId: String(environmentId),
158 threadId: String(threadId),
159 });
160 return;
161 }
162 if (item.dialogAction === "push") {
163 await runActionWithPrompt({ action: "push" });
164 return;
165 }
166 if (item.dialogAction === "create_pr") {
167 await runActionWithPrompt({ action: "create_pr" });
168 }
169 },
170 [environmentId, openExistingPr, navigation, runActionWithPrompt, threadId],
171 );
172​
173 // Status facts live on the relevant rows instead of crowding the header
174 // subtitle: files changed → Commit, ahead → Push, PR → View PR, behind → Pull.
175 const rowStatusDetail = useCallback(
176 (item: (typeof menuItems)[number]): string | undefined => {
177 const status = gitStatus.data;
178 if (status == null) {
179 return undefined;
180 }
181 if (item.dialogAction === "commit" && status.hasWorkingTreeChanges) {
182 const fileCount = status.workingTree?.files.length ?? 0;
183 return `${fileCount} file${fileCount === 1 ? "" : "s"} changed`;
184 }
185 if (item.dialogAction === "push" && (status.aheadCount ?? 0) > 0) {
186 const ahead = status.aheadCount ?? 0;
187 return `${ahead} commit${ahead === 1 ? "" : "s"} ahead`;
188 }
189 if (item.kind === "open_pr" && status.pr?.number != null) {
190 return `PR #${status.pr.number} ${status.pr.state ?? "open"}`;
191 }
192 return undefined;
193 },
194 [gitStatus.data, menuItems],
195 );
196​
197 const behindCount = gitStatus.data?.behindCount ?? 0;
198​
199 // Deterministic pull-to-refresh state. Tying RefreshControl to the query's
200 // isPending flag left the spinner stuck (the status query reports pending
201 // during quiet background refreshes too).
202 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
203 const handlePullRefresh = useCallback(async () => {
204 setIsPullRefreshing(true);
205 try {
206 await gitActions.refreshSelectedThreadGitStatus();
207 } finally {
208 setIsPullRefreshing(false);
209 }
210 }, [gitActions]);
211​
212 const content = (
213 <ScrollView
214 className="flex-1 bg-screen"
215 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
216 showsVerticalScrollIndicator={false}
217 contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
218 contentContainerStyle={{
219 paddingHorizontal: isInspector ? 12 : 20,
220 paddingTop: 8,
221 gap: 14,
222 }}
223 refreshControl={
224 <RefreshControl refreshing={isPullRefreshing} onRefresh={() => void handlePullRefresh()} />
225 }
226 >
227 <View
228 className={
229 isInspector
230 ? "overflow-hidden rounded-2xl border border-border bg-card px-3 py-1"
231 : "overflow-hidden rounded-[22px] border border-border bg-card px-4 py-1"
232 }
233 >
234 {sheetMenuItems.map(({ item, disabledReason }, index) => (
235 <View key={`${item.id}-${item.label}`}>
236 {index > 0 ? <View className="ml-12 h-px bg-border" /> : null}
237 <SheetListRow
238 icon={menuItemIconName(item.icon)}
239 title={item.label}
240 subtitle={disabledReason ?? rowStatusDetail(item)}
241 disabled={item.disabled}
242 onPress={() => void onPressMenuItem(item)}
243 />
244 </View>
245 ))}
246 {behindCount > 0 ? (
247 <>
248 <View className="ml-12 h-px bg-border" />
249 <SheetListRow
250 icon="arrow.down.circle"
251 title="Pull latest"
252 subtitle={`${behindCount} commit${behindCount === 1 ? "" : "s"} behind upstream`}
253 disabled={busy || !isRepo}
254 onPress={() => void gitActions.onPullSelectedThreadBranch()}
255 />
256 </>
257 ) : null}
258 <View className="ml-12 h-px bg-border" />
259 <SheetListRow
260 icon="text.bubble"
261 title="Review changes"
262 subtitle="Inspect turn diffs, worktree changes, and base branch diff"
263 disabled={busy || !isRepo}
264 onPress={() => {
265 const params = { environmentId, threadId };
266 navigation.dispatch(
267 resolveGitOverviewReviewNavigationAction(presentation) === "replace"
268 ? StackActions.replace("ThreadReview", params)
269 : CommonActions.navigate("ThreadReview", params),
270 );
271 }}
272 />
273 <View className="ml-12 h-px bg-border" />
274 <SheetListRow
275 icon="point.topleft.down.curvedto.point.bottomright.up"
276 title="Branches & worktrees"
277 subtitle="Switch branch, create branch, or move to a worktree"
278 disabled={busy || !isRepo}
279 onPress={() =>
280 navigation.navigate("GitBranches", {
281 environmentId: String(environmentId),
282 threadId: String(threadId),
283 })
284 }
285 />
286 </View>
287​
288 {currentWorktreePath ? <MetaCard label="Worktree" value={currentWorktreePath} /> : null}
289 </ScrollView>
290 );
291​
292 if (isInspector && Platform.OS === "ios") {
293 return (
294 <View collapsable={false} className="flex-1 border-l border-border bg-sheet">
295 <ScreenStack style={{ flex: 1 }}>
296 <Screen
297 activityState={2}
298 enabled
299 isNativeStack
300 screenId="thread-git-inspector-native"
301 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
302 style={{ backgroundColor: sheetColor, flex: 1 }}
303 >
304 {content}
305 <ScreenStackHeaderConfig
306 backgroundColor="rgba(0,0,0,0)"
307 color={foregroundColor}
308 hideBackButton
309 hideShadow={false}
310 navigationItemStyle="editor"
311 title={currentBranchLabel}
312 titleColor={foregroundColor}
313 titleFontSize={17}
314 titleFontWeight="700"
315 translucent
316 />
317 </Screen>
318 </ScreenStack>
319 </View>
320 );
321 }
322​
323 if (Platform.OS === "ios") {
324 // Compact form sheet: a plain screen presented as formSheet never renders a
325 // stack header, so — like the Settings sheet — the header must come from a
326 // nested native stack INSIDE the sheet. This reuses the exact structure of the
327 // inspector branch below: branch as the title, status summary as the native
328 // subtitle, refresh as a header button.
329 return (
330 <View collapsable={false} className="flex-1 bg-sheet">
331 <ScreenStack style={{ flex: 1 }}>
332 <Screen
333 activityState={2}
334 enabled
335 isNativeStack
336 screenId="thread-git-sheet-native"
337 scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}
338 style={{ backgroundColor: sheetColor, flex: 1 }}
339 >
340 {content}
341 <ScreenStackHeaderConfig
342 backgroundColor="rgba(0,0,0,0)"
343 color={foregroundColor}
344 hideBackButton
345 hideShadow={false}
346 navigationItemStyle="editor"
347 title={currentBranchLabel}
348 titleColor={foregroundColor}
349 titleFontSize={18}
350 titleFontWeight="800"
351 translucent
352 />
353 </Screen>
354 </ScreenStack>
355 </View>
356 );
357 }
358​
359 return (
360 <View
361 collapsable={false}
362 className={isInspector ? "flex-1 border-l border-border bg-sheet" : "flex-1 bg-sheet"}
363 >
364 {isInspector ? (
365 <View
366 style={{
367 minHeight: props.headerInset ?? 0,
368 paddingTop: props.headerInset ?? 0,
369 }}
370 />
371 ) : null}
372​
373 {isInspector ? (
374 <View className="gap-1 border-b border-border px-4 pb-4 pt-3">
375 <Pressable
376 className={
377 busy
378 ? "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle opacity-[0.45]"
379 : "absolute right-3 top-4 z-[1] h-9 w-9 items-center justify-center rounded-full bg-subtle"
380 }
381 disabled={busy}
382 onPress={() => void gitActions.refreshSelectedThreadGitStatus()}
383 >
384 <SymbolView
385 name="arrow.clockwise"
386 size={16}
387 tintColorClassName={"accent-icon"}
388 type="monochrome"
389 weight="medium"
390 />
391 </Pressable>
392 <Text className="text-xs font-t3-bold tracking-[1px] uppercase text-foreground-muted">
393 Repository
394 </Text>
395 <Text className="pr-10 text-xl font-t3-bold">{currentBranchLabel}</Text>
396 <Text className="text-foreground-secondary text-sm font-medium leading-normal">
397 {currentStatusSummary}
398 </Text>
399 </View>
400 ) : (
401 <AndroidSheetHeader
402 title={currentBranchLabel}
403 subtitle={currentStatusSummary}
404 onBack={() => navigation.goBack()}
405 actions={[
406 {
407 accessibilityLabel: "Refresh repository status",
408 disabled: busy,
409 icon: "arrow.clockwise",
410 onPress: () => void gitActions.refreshSelectedThreadGitStatus(),
411 },
412 ]}
413 />
414 )}
415​
416 {content}
417 </View>
418 );