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

GitOverviewSheet.tsx

517 lines20.1 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 }),
251 );
252 return;
253 }
254​
255 // Close a sheet so the thread shows the action's progress.
256 if (!isInspector) navigation.goBack();
257 else closeInspectorSheet?.();
258 await gitActions.onRunSelectedThreadGitAction(input);
259 };
260​
261 const onPressMenuItem = async (item: (typeof menuItems)[number]) => {
262 if (item.disabled) return;
263 if (item.kind === "open_pr") {
264 await openExistingPr();
265 return;
266 }
267 if (!canWriteSourceControl) return;
268 if (item.dialogAction === "commit") {
269 presentRoute(() =>
270 navigation.navigate("GitCommit", {
271 environmentId: String(environmentId),
272 threadId: String(threadId),
273 ...repositoryParams,
274 }),
275 );
276 return;
277 }
278 if (item.dialogAction === "push") {
279 await runActionWithPrompt({ action: "push" });
280 return;
281 }
282 if (item.dialogAction === "create_pr") {
283 await runActionWithPrompt({ action: "create_pr" });
284 }
285 };
286​
287 const rowStatusDetail = (item: (typeof menuItems)[number]): string | undefined => {
288 const status = gitStatus.data;
289 if (status == null) {
290 return undefined;
291 }
292 if (item.dialogAction === "commit" && status.hasWorkingTreeChanges) {
293 const fileCount = status.workingTree?.files.length ?? 0;
294 return gt("{count, plural, one {{count} file changed} other {{count} files changed}}", {
295 count: fileCount,
296 });
297 }
298 if (item.dialogAction === "push" && (status.aheadCount ?? 0) > 0) {
299 const ahead = status.aheadCount ?? 0;
300 return gt("{count, plural, one {{count} commit ahead} other {{count} commits ahead}}", {
301 count: ahead,
302 });
303 }
304 if (item.kind === "open_pr" && status.pr?.number != null) {
305 return gt(
306 "{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}}}}}",
307 {
308 term,
309 number: status.pr.number,
310 state: status.pr.state ?? "open",
311 },
312 );
313 }
314 return undefined;
315 };
316​
317 const behindCount = gitStatus.data?.behindCount ?? 0;
318​
319 const openRepository = (section: ThreadRepositorySection) => {
320 const params = {
321 environmentId: String(environmentId),
322 threadId: String(threadId),
323 repositoryCwd: section.cwd,
324 repositoryName: section.name,
325 };
326 // A sheet swaps in place, so closing the repository or running an action lands on the thread.
327 if (presentation === "sheet") {
328 navigation.dispatch(StackActions.replace("GitOverview", params));
329 } else {
330 presentRoute(() => navigation.dispatch(StackActions.push("GitOverview", params)));
331 }
332 };
333​
334 // Background refreshes also report pending; using that query flag would stick the RefreshControl spinner.
335 const [isRefreshing, setIsRefreshing] = useState(false);
336 const handleRefresh = async () => {
337 setIsRefreshing(true);
338 await gitActions.refreshSelectedThreadGitStatus();
339 setIsRefreshing(false);
340 };
341​
342 const content = (
343 <NativeScrollView
344 nestedScrollEnabled
345 alwaysBounceVertical
346 className="flex-1 bg-screen"
347 contentInsetAdjustmentBehavior="automatic"
348 showsVerticalScrollIndicator={false}
349 contentContainerStyle={{
350 ...groupedListInsets(isInspector),
351 paddingTop: 8,
352 paddingBottom: Math.max(insets.bottom, 18) + 18,
353 }}
354 refreshControl={
355 <RefreshControl refreshing={isRefreshing} onRefresh={() => void handleRefresh()} />
356 }
357 >
358 {sheetMenuItems.length > 0 || behindCount > 0 ? (
359 <ListSection>
360 {sheetMenuItems.map(({ item, disabledReason }) => (
361 <ListRow
362 key={`${item.id}-${item.label}`}
363 icon={menuItemIconName(item.icon)}
364 label={item.label}
365 description={disabledReason ?? rowStatusDetail(item)}
366 disabled={item.disabled}
367 onPress={() => void onPressMenuItem(item)}
368 />
369 ))}
370 {behindCount > 0 ? (
371 <ListRow
372 icon="arrow.down.circle"
373 label={gt("Pull latest")}
374 description={
375 canWriteSourceControl
376 ? gt(
377 "{count, plural, one {{count} commit behind upstream} other {{count} commits behind upstream}}",
378 { count: behindCount },
379 )
380 : gt("This connection cannot change source control.")
381 }
382 disabled={!canWriteSourceControl || busy || !isRepo}
383 onPress={() => void gitActions.onPullSelectedThreadBranch()}
384 />
385 ) : null}
386 </ListSection>
387 ) : null}
388​
389 {listsRepositories ? (
390 <ThreadRepositoryRows
391 threadRef={threadRef}
392 projectId={selectedThreadProject.id}
393 threadCwd={selectedThreadCwd}
394 taskFolder={taskFolder}
395 reachesTracked={reachesTracked}
396 onTaskFolderChange={taskFolderQuery.refresh}
397 explainsEmpty={!isRepo}
398 onOpen={openRepository}
399 />
400 ) : null}
401​
402 {repository === undefined || isPinnedRepository ? (
403 <ListSection>
404 {repository === undefined ? (
405 <>
406 <ListRow
407 icon="text.bubble"
408 label={gt("Review changes")}
409 description={
410 trackedRepositoryCount > 0
411 ? gt("Inspect turn diffs")
412 : gt("Inspect changes, uncommitted edits, and turn diffs")
413 }
414 disabled={busy || !(isRepo || trackedRepositoryCount > 0)}
415 onPress={() => {
416 const params = { environmentId, threadId };
417 if (presentation === "sheet") {
418 navigation.dispatch(StackActions.replace("ThreadReview", params));
419 } else {
420 presentRoute(() =>
421 navigation.dispatch(CommonActions.navigate("ThreadReview", params)),
422 );
423 }
424 }}
425 />
426 <ListRow
427 icon="point.topleft.down.curvedto.point.bottomright.up"
428 label={gt("Branches & worktrees")}
429 description={
430 canChangeThreadBranch
431 ? gt("Switch branch, create branch, or move to a worktree")
432 : gt("View branches and worktrees")
433 }
434 disabled={busy || !isRepo}
435 onPress={() =>
436 presentRoute(() =>
437 navigation.navigate("GitBranches", {
438 environmentId: String(environmentId),
439 threadId: String(threadId),
440 }),
441 )
442 }
443 />
444 {linkedPrActions.canLink ? (
445 <ListRow
446 icon="link"
447 label={gt(
448 "{term, select, mr {Link merge request} cr {Link change request} other {Link pull request}}",
449 { term: changeRequestTermKind(linkedPrActions.terminology) },
450 )}
451 description={gt(
452 "{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}}",
453 { term: changeRequestTermKind(linkedPrActions.terminology) },
454 )}
455 onPress={linkedPrActions.promptLink}
456 />
457 ) : null}
458 </>
459 ) : isPinnedRepository ? (
460 <ListRow
461 icon="pin.slash"
462 label={gt("Remove from this thread")}
463 description={gt("The repository stays tracked by the project")}
464 disabled={busy}
465 onPress={() => {
466 unpinRepositoryFromThread(threadRef, repository.key);
467 navigation.goBack();
468 }}
469 />
470 ) : null}
471 </ListSection>
472 ) : null}
473​
474 {repository === undefined && linkedPrLines.length > 0 ? (
475 <ListSection title={gt("Linked {terms}", { terms: linkedPrActions.terminology.plural })}>
476 {linkedPrLines.map((line, index) => (
477 <LinkedPullRequestRow
478 key={linkedPullRequestKey(line)}
479 line={line}
480 separator={index < linkedPrLines.length - 1}
481 surfaceClassName="text-grouped-card"
482 openPullRequest={openPullRequest}
483 actions={linkedPrActions}
484 />
485 ))}
486 </ListSection>
487 ) : null}
488​
489 {currentWorktreePath ? (
490 <ListSection title={gt("Worktree")}>
491 <Text selectable textRole="footnote" className="p-4 text-foreground-muted">
492 {currentWorktreePath}
493 </Text>
494 </ListSection>
495 ) : null}
496 </NativeScrollView>
497 );
498​
499 const refresh = {
500 accessibilityLabel: gt("Refresh repository status"),
501 disabled: busy || isRefreshing,
502 onPress: () => void handleRefresh(),
503 };
504​
505 return (
506 <SheetPane surface={isInspector ? "screen" : "sheet"}>
507 <AppBar
508 title={currentBranchLabel}
509 subtitle={currentStatusSummary}
510 hideBottomBorder={!isInspector}
511 onClose={isInspector ? undefined : () => navigation.goBack()}
512 refresh={refresh}
513 />
514 <ScreenContent insetHorizontal={isInspector ? true : undefined}>{content}</ScreenContent>
515 </SheetPane>
516 );