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

GitOverviewSheet.tsx

521 lines20.2 KB

1import * as Dialog from "../../../components/ui/Dialog";
2import { useOpenPullRequest } from "../../../native/useOpenPullRequest";
3import {
4 type GitActionRequestInput,
5 buildMenuItems,
6 getGitActionDisabledReason,
7 requiresDefaultBranchConfirmation,
8} from "@t3tools/client-runtime/state/vcs";
9import type { ThreadRepositorySection } from "@t3tools/client-runtime/state/thread-repositories";
10import { EnvironmentId, ThreadId } from "@t3tools/contracts";
11import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
12import { changeRequestTermKind } from "../../../lib/changeRequestTerm";
13import {
14 CommonActions,
15 StackActions,
16 useNavigation,
17 type StaticScreenProps,
18} from "@react-navigation/native";
19import { useGT, useMessages } from "gt-react-native";
20import { use, useEffect, useState } from "react";
21import { RefreshControl } from "../../../components/ui/RefreshControl";
22import { NativeScrollView } from "../../../native/NativeScrollViewMarker";
23​
24import { useSafeAreaInsets } from "react-native-safe-area-context";
25import { AppBar } from "../../../components/ui/AppBar";
26import { ListRow } from "../../../components/ui/ListRow";
27import { ListSection } from "../../../components/ui/ListSection";
28import { groupedListInsets } from "../../../components/ui/listMetrics";
29import { ScreenContent } from "../../../components/ui/ScreenContent";
30import { SheetPane } from "../../../components/ui/SheetPane";
31import { InspectorSheetContext } from "../../layout/workspace-inspector-sheet";
32import { AppText as Text } from "../../../components/ui/AppText";
33import { filesystemEnvironment } from "../../../state/filesystem";
34import { useEnvironmentQuery } from "../../../state/query";
35import {
36 gitRepositoryRouteParams,
37 gitRepositoryTargetFromRoute,
38 type GitRepositoryRouteParams,
39} from "../../../state/thread-git-target";
40import {
41 unpinRepositoryFromThread,
42 useThreadRepositoryPins,
43} from "../../../state/thread-repository-pins";
44import { useThreadSelection } from "../../../state/use-thread-selection";
45import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions";
46import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state";
47import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree";
48import { vcsEnvironment } from "../../../state/vcs";
49import { menuItemIconName, statusSummary } from "./gitSheetComponents";
50import { ThreadRepositoryRows } from "./ThreadRepositoryRows";
51import {
52 LinkedPullRequestRow,
53 linkedPullRequestKey,
54 useLinkedPullRequestLines,
55} from "../LinkedPullRequestList";
56import { useLinkedPullRequestActions } from "../useLinkedPullRequestActions";
57​
58type GitOverviewSheetProps = StaticScreenProps<
59 {
60 readonly environmentId: string;
61 readonly threadId: string;
62 } & GitRepositoryRouteParams
63> & {
64 readonly presentation?: "sheet" | "inspector";
65};
66​
67export function GitOverviewSheet(props: GitOverviewSheetProps) {
68 const navigation = useNavigation();
69 const { environmentId, threadId } = props.route.params;
70 const isBlankLink = environmentId.trim().length === 0 || threadId.trim().length === 0;
71 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pops the navigator when the route link names a blank environment or thread
72 useEffect(() => {
73 if (isBlankLink) navigation.goBack();
74 }, [isBlankLink, navigation]);
75 if (isBlankLink) return null;
76 return <GitOverviewSheetContent {...props} />;
78​
79function GitOverviewSheetContent(props: GitOverviewSheetProps) {
80 const gt = useGT();
81 const m = useMessages();
82 const navigation = useNavigation();
83 const insets = useSafeAreaInsets();
84 const presentation = props.presentation ?? "sheet";
85 const isInspector = presentation === "inspector";
86 const closeInspectorSheet = use(InspectorSheetContext);
87 const presentRoute = (present: () => void) =>
88 closeInspectorSheet ? closeInspectorSheet(present) : present();
89 const environmentId = EnvironmentId.make(props.route.params.environmentId);
90 const threadId = ThreadId.make(props.route.params.threadId);
91 const { selectedThread, selectedThreadProject, selectedEnvironmentRuntime } =
92 useThreadSelection();
93 const openPullRequest = useOpenPullRequest({
94 replace: presentation === "sheet",
95 context: selectedThread ?? undefined,
96 });
97 // A tracked repository instead of the thread's own folder: thread-only rows stay off for it.
98 const repository = gitRepositoryTargetFromRoute(props.route.params);
99 const repositoryParams = gitRepositoryRouteParams(repository);
100 const threadWorktree = useSelectedThreadWorktree();
101 const { selectedThreadWorktreePath } = threadWorktree;
102 const selectedThreadCwd = repository?.cwd ?? threadWorktree.selectedThreadCwd;
103 const threadRef = { environmentId, threadId };
104 const pinnedRepositories = useThreadRepositoryPins(threadRef);
105 const isPinnedRepository =
106 repository !== undefined &&
107 pinnedRepositories.some((pin) => pin.repositoryPath === repository.key);
108 const linkedPrLines = useLinkedPullRequestLines(selectedThread, selectedEnvironmentRuntime);
109 const linkedPrActions = useLinkedPullRequestActions({
110 thread: selectedThread,
111 project: selectedThreadProject,
112 runtime: selectedEnvironmentRuntime,
113 });
114 const gitState = useSelectedThreadGitState(repository);
115 const gitActions = useSelectedThreadGitActions(repository);
116 const { canWriteSourceControl, canChangeThreadBranch } = gitActions;
117​
118 const gitStatus = useEnvironmentQuery(
119 selectedThread !== null && selectedThreadCwd !== null
120 ? vcsEnvironment.status({
121 environmentId: selectedThread.environmentId,
122 input: { cwd: selectedThreadCwd },
123 })
124 : null,
125 );
126​
127 const isRepo = gitStatus.data?.isRepo ?? true;
128 // A plain folder that tracks repositories has no branch of its own; its turns still have diffs.
129 const projectRepositoryCount = selectedThreadProject?.trackedFolders?.length ?? 0;
130 const trackedRepositoryCount = isRepo || repository !== undefined ? 0 : projectRepositoryCount;
131 // A worktree thread reaches tracked repositories only through its own task folder.
132 const taskFolderQuery = useEnvironmentQuery(
133 selectedThread !== null && selectedThreadWorktreePath !== null && projectRepositoryCount > 0
134 ? filesystemEnvironment.taskFolder({
135 environmentId: selectedThread.environmentId,
136 input: { worktreePath: selectedThreadWorktreePath },
137 })
138 : null,
139 );
140 const taskFolder = taskFolderQuery.data?.taskFolder ?? null;
141 // Also for a project that tracks nothing: a thread can change a submodule.
142 const listsRepositories = repository === undefined && selectedThreadProject !== null;
143 const reachesTracked =
144 projectRepositoryCount > 0 && (selectedThreadWorktreePath === null || taskFolder !== null);
145 const currentBranchLabel =
146 repository !== undefined
147 ? repository.name
148 : trackedRepositoryCount > 0
149 ? // A task folder's plain project folder has no branch; its repositories are on the thread's.
150 ((taskFolder === null ? null : selectedThread?.branch) ??
151 selectedThreadProject?.title ??
152 gt("Repositories"))
153 : (gitStatus.data?.refName ?? selectedThread?.branch ?? gt("Detached HEAD"));
154 const currentStatusSummary =
155 repository !== undefined
156 ? gitStatus.data?.isRepo
157 ? `${gitStatus.data.refName ?? gt("Detached HEAD")} · ${statusSummary(gitStatus.data, m)}`
158 : statusSummary(gitStatus.data, m)
159 : taskFolder !== null && trackedRepositoryCount > 0
160 ? gt(
161 "{count, plural, one {{count} repository worktree} other {{count} repository worktrees}}",
162 { count: taskFolder.repositories.length },
163 )
164 : trackedRepositoryCount > 0
165 ? gt("{count, plural, one {{count} repository} other {{count} repositories}}", {
166 count: trackedRepositoryCount,
167 })
168 : statusSummary(gitStatus.data, m);
169 const currentWorktreePath = repository === undefined ? selectedThreadWorktreePath : null;
170 const gitOperationLabel = gitState.gitOperationLabel;
171 const busy = gitOperationLabel !== null;
172 const hasPrimaryRemote = gitStatus.data?.hasPrimaryRemote ?? false;
173 const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
174​
175 const menuItems = isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote, m) : [];
176​
177 const sheetMenuItems = menuItems.map((item) => ({
178 item: {
179 ...item,
180 disabled: item.disabled || (!canWriteSourceControl && item.kind !== "open_pr"),
181 },
182 disabledReason:
183 !canWriteSourceControl && item.kind !== "open_pr"
184 ? gt("This connection cannot change source control.")
185 : getGitActionDisabledReason(
186 {
187 item,
188 gitStatus: gitStatus.data,
189 isBusy: busy,
190 hasOriginRemote: hasPrimaryRemote,
191 },
192 m,
193 ),
194 }));
195​
196 const term = changeRequestTermKind(
197 sourceControlClients.get(gitStatus.data?.sourceControlProvider?.kind).changeRequest,
198 );
199​
200 const openExistingPr = async () => {
201 const prUrl = gitStatus.data?.pr?.state === "open" ? gitStatus.data.pr.url : null;
202 if (!prUrl) {
203 Dialog.alert(
204 gt("{term, select, mr {No open MR} cr {No open change request} other {No open PR}}", {
205 term,
206 }),
207 gt(
208 "{term, select, mr {This branch does not have an open merge request.} cr {This branch does not have an open change request.} other {This branch does not have an open pull request.}}",
209 { term },
210 ),
211 );
212 return;
213 }
214 if (!(await openPullRequest(prUrl))) {
215 Dialog.alert(
216 gt(
217 "{term, select, mr {Unable to open MR} cr {Unable to open change request} other {Unable to open PR}}",
218 { term },
219 ),
220 gt(
221 "{term, select, mr {The merge request could not be opened.} cr {The change request could not be opened.} other {The pull request could not be opened.}}",
222 { term },
223 ),
224 );
225 }
226 };
227​
228 const runActionWithPrompt = async (input: GitActionRequestInput) => {
229 if (!canWriteSourceControl) return;
230 const confirmableAction =
231 input.action === "push" ||
232 input.action === "create_pr" ||
233 input.action === "commit_push" ||
234 input.action === "commit_push_pr"
235 ? input.action
236 : null;
237 const branchName = gitStatus.data?.refName;
238 if (
239 branchName &&
240 confirmableAction &&
241 !input.featureBranch &&
242 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
243 ) {
244 presentRoute(() =>
245 navigation.navigate("GitConfirm", {
246 environmentId: String(environmentId),
247 threadId: String(threadId),
248 ...repositoryParams,
249 confirmAction: confirmableAction,
250 branchName,
251 includesCommit: String(
252 input.action === "commit_push" || input.action === "commit_push_pr",
253 ),
254 }),
255 );
256 return;
257 }
258​
259 // Close a sheet so the thread shows the action's progress.
260 if (!isInspector) navigation.goBack();
261 else closeInspectorSheet?.();
262 await gitActions.onRunSelectedThreadGitAction(input);
263 };
264​
265 const onPressMenuItem = async (item: (typeof menuItems)[number]) => {
266 if (item.disabled) return;
267 if (item.kind === "open_pr") {
268 await openExistingPr();
269 return;
270 }
271 if (!canWriteSourceControl) return;
272 if (item.dialogAction === "commit") {
273 presentRoute(() =>
274 navigation.navigate("GitCommit", {
275 environmentId: String(environmentId),
276 threadId: String(threadId),
277 ...repositoryParams,
278 }),
279 );
280 return;
281 }
282 if (item.dialogAction === "push") {
283 await runActionWithPrompt({ action: "push" });
284 return;
285 }
286 if (item.dialogAction === "create_pr") {
287 await runActionWithPrompt({ action: "create_pr" });
288 }
289 };
290​
291 const rowStatusDetail = (item: (typeof menuItems)[number]): string | undefined => {
292 const status = gitStatus.data;
293 if (status == null) {
294 return undefined;
295 }
296 if (item.dialogAction === "commit" && status.hasWorkingTreeChanges) {
297 const fileCount = status.workingTree?.files.length ?? 0;
298 return gt("{count, plural, one {{count} file changed} other {{count} files changed}}", {
299 count: fileCount,
300 });
301 }
302 if (item.dialogAction === "push" && (status.aheadCount ?? 0) > 0) {
303 const ahead = status.aheadCount ?? 0;
304 return gt("{count, plural, one {{count} commit ahead} other {{count} commits ahead}}", {
305 count: ahead,
306 });
307 }
308 if (item.kind === "open_pr" && status.pr?.number != null) {
309 return gt(
310 "{term, select, mr {MR #{number} {state, select, open {open} closed {closed} merged {merged} other {{state}}}} cr {change request #{number} {state, select, open {open} closed {closed} merged {merged} other {{state}}}} other {PR #{number} {state, select, open {open} closed {closed} merged {merged} other {{state}}}}}",
311 {
312 term,
313 number: status.pr.number,
314 state: status.pr.state ?? "open",
315 },
316 );
317 }
318 return undefined;
319 };
320​
321 const behindCount = gitStatus.data?.behindCount ?? 0;
322​
323 const openRepository = (section: ThreadRepositorySection) => {
324 const params = {
325 environmentId: String(environmentId),
326 threadId: String(threadId),
327 repositoryCwd: section.cwd,
328 repositoryName: section.name,
329 };
330 // A sheet swaps in place, so closing the repository or running an action lands on the thread.
331 if (presentation === "sheet") {
332 navigation.dispatch(StackActions.replace("GitOverview", params));
333 } else {
334 presentRoute(() => navigation.dispatch(StackActions.push("GitOverview", params)));
335 }
336 };
337​
338 // Background refreshes also report pending; using that query flag would stick the RefreshControl spinner.
339 const [isRefreshing, setIsRefreshing] = useState(false);
340 const handleRefresh = async () => {
341 setIsRefreshing(true);
342 await gitActions.refreshSelectedThreadGitStatus();
343 setIsRefreshing(false);
344 };
345​
346 const content = (
347 <NativeScrollView
348 nestedScrollEnabled
349 alwaysBounceVertical
350 className="flex-1 bg-screen"
351 contentInsetAdjustmentBehavior="automatic"
352 showsVerticalScrollIndicator={false}
353 contentContainerStyle={{
354 ...groupedListInsets(isInspector),
355 paddingTop: 8,
356 paddingBottom: Math.max(insets.bottom, 18) + 18,
357 }}
358 refreshControl={
359 <RefreshControl refreshing={isRefreshing} onRefresh={() => void handleRefresh()} />
360 }
361 >
362 {sheetMenuItems.length > 0 || behindCount > 0 ? (
363 <ListSection>
364 {sheetMenuItems.map(({ item, disabledReason }) => (
365 <ListRow
366 key={`${item.id}-${item.label}`}
367 icon={menuItemIconName(item.icon)}
368 label={item.label}
369 description={disabledReason ?? rowStatusDetail(item)}
370 disabled={item.disabled}
371 onPress={() => void onPressMenuItem(item)}
372 />
373 ))}
374 {behindCount > 0 ? (
375 <ListRow
376 icon="arrow.down.circle"
377 label={gt("Pull latest")}
378 description={
379 canWriteSourceControl
380 ? gt(
381 "{count, plural, one {{count} commit behind upstream} other {{count} commits behind upstream}}",
382 { count: behindCount },
383 )
384 : gt("This connection cannot change source control.")
385 }
386 disabled={!canWriteSourceControl || busy || !isRepo}
387 onPress={() => void gitActions.onPullSelectedThreadBranch()}
388 />
389 ) : null}
390 </ListSection>
391 ) : null}
392​
393 {listsRepositories ? (
394 <ThreadRepositoryRows
395 threadRef={threadRef}
396 projectId={selectedThreadProject.id}
397 threadCwd={selectedThreadCwd}
398 taskFolder={taskFolder}
399 reachesTracked={reachesTracked}
400 onTaskFolderChange={taskFolderQuery.refresh}
401 explainsEmpty={!isRepo}
402 onOpen={openRepository}
403 />
404 ) : null}
405​
406 {repository === undefined || isPinnedRepository ? (
407 <ListSection>
408 {repository === undefined ? (
409 <>
410 <ListRow
411 icon="text.bubble"
412 label={gt("Review changes")}
413 description={
414 trackedRepositoryCount > 0
415 ? gt("Inspect turn diffs")
416 : gt("Inspect changes, uncommitted edits, and turn diffs")
417 }
418 disabled={busy || !(isRepo || trackedRepositoryCount > 0)}
419 onPress={() => {
420 const params = { environmentId, threadId };
421 if (presentation === "sheet") {
422 navigation.dispatch(StackActions.replace("ThreadReview", params));
423 } else {
424 presentRoute(() =>
425 navigation.dispatch(CommonActions.navigate("ThreadReview", params)),
426 );
427 }
428 }}
429 />
430 <ListRow
431 icon="point.topleft.down.curvedto.point.bottomright.up"
432 label={gt("Branches & worktrees")}
433 description={
434 canChangeThreadBranch
435 ? gt("Switch branch, create branch, or move to a worktree")
436 : gt("View branches and worktrees")
437 }
438 disabled={busy || !isRepo}
439 onPress={() =>
440 presentRoute(() =>
441 navigation.navigate("GitBranches", {
442 environmentId: String(environmentId),
443 threadId: String(threadId),
444 }),
445 )
446 }
447 />
448 {linkedPrActions.canLink ? (
449 <ListRow
450 icon="link"
451 label={gt(
452 "{term, select, mr {Link merge request} cr {Link change request} other {Link pull request}}",
453 { term: changeRequestTermKind(linkedPrActions.terminology) },
454 )}
455 description={gt(
456 "{term, select, mr {Attach a merge request by URL or number} cr {Attach a change request by URL or number} other {Attach a pull request by URL or number}}",
457 { term: changeRequestTermKind(linkedPrActions.terminology) },
458 )}
459 onPress={linkedPrActions.promptLink}
460 />
461 ) : null}
462 </>
463 ) : isPinnedRepository ? (
464 <ListRow
465 icon="pin.slash"
466 label={gt("Remove from this thread")}
467 description={gt("The repository stays tracked by the project")}
468 disabled={busy}
469 onPress={() => {
470 unpinRepositoryFromThread(threadRef, repository.key);
471 navigation.goBack();
472 }}
473 />
474 ) : null}
475 </ListSection>
476 ) : null}
477​
478 {repository === undefined && linkedPrLines.length > 0 ? (
479 <ListSection title={gt("Linked {terms}", { terms: linkedPrActions.terminology.plural })}>
480 {linkedPrLines.map((line, index) => (
481 <LinkedPullRequestRow
482 key={linkedPullRequestKey(line)}
483 line={line}
484 separator={index < linkedPrLines.length - 1}
485 surfaceClassName="text-grouped-card"
486 openPullRequest={openPullRequest}
487 actions={linkedPrActions}
488 />
489 ))}
490 </ListSection>
491 ) : null}
492​
493 {currentWorktreePath ? (
494 <ListSection title={gt("Worktree")}>
495 <Text selectable textRole="footnote" className="p-4 text-foreground-muted">
496 {currentWorktreePath}
497 </Text>
498 </ListSection>
499 ) : null}
500 </NativeScrollView>
501 );
502​
503 const refresh = {
504 accessibilityLabel: gt("Refresh repository status"),
505 disabled: busy || isRefreshing,
506 onPress: () => void handleRefresh(),
507 };
508​
509 return (
510 <SheetPane surface={isInspector ? "screen" : "sheet"}>
511 <AppBar
512 title={currentBranchLabel}
513 subtitle={currentStatusSummary}
514 hideBottomBorder={!isInspector}
515 onClose={isInspector ? undefined : () => navigation.goBack()}
516 refresh={refresh}
517 />
518 <ScreenContent insetHorizontal={isInspector ? true : undefined}>{content}</ScreenContent>
519 </SheetPane>
520 );