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

GitOverviewSheet.tsx

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