Open History to see the last commit
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, plural, part, select } 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} />;
77}
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`${plural(
161 { count: taskFolder.repositories.length },
162 {
163 one: part`${{ count: taskFolder.repositories.length }} repository worktree`,
164 other: part`${{ count: taskFolder.repositories.length }} repository worktrees`,
165 },
166 )}`
167 : trackedRepositoryCount > 0
168 ? gt`${plural(
169 { count: trackedRepositoryCount },
170 {
171 one: part`${{ count: trackedRepositoryCount }} repository`,
172 other: part`${{ count: trackedRepositoryCount }} repositories`,
173 },
174 )}`
175 : statusSummary(gitStatus.data, m);
176 const currentWorktreePath = repository === undefined ? selectedThreadWorktreePath : null;
177 const gitOperationLabel = gitState.gitOperationLabel;
178 const busy = gitOperationLabel !== null;
179 const hasPrimaryRemote = gitStatus.data?.hasPrimaryRemote ?? false;
180 const isDefaultRef = gitStatus.data?.isDefaultRef ?? false;
181
182 const menuItems = isRepo ? buildMenuItems(gitStatus.data, busy, hasPrimaryRemote, m) : [];
183
184 const sheetMenuItems = menuItems.map((item) => ({
185 item: {
186 ...item,
187 disabled: item.disabled || (!canWriteSourceControl && item.kind !== "open_pr"),
188 },
189 disabledReason:
190 !canWriteSourceControl && item.kind !== "open_pr"
191 ? gt`This connection cannot change source control.`
192 : getGitActionDisabledReason(
193 {
194 item,
195 gitStatus: gitStatus.data,
196 isBusy: busy,
197 hasOriginRemote: hasPrimaryRemote,
198 },
199 m,
200 ),
201 }));
202
203 const term = changeRequestTermKind(
204 sourceControlClients.get(gitStatus.data?.sourceControlProvider?.kind).changeRequest,
205 );
206
207 const openExistingPr = async () => {
208 const prUrl = gitStatus.data?.pr?.state === "open" ? gitStatus.data.pr.url : null;
209 if (!prUrl) {
210 Dialog.alert(
211 gt`${select(
212 { term },
213 {
214 mr: "No open MR",
215 cr: "No open change request",
216 other: "No open PR",
217 },
218 )}`,
219 gt`${select(
220 { term },
221 {
222 mr: "This branch does not have an open merge request.",
223 cr: "This branch does not have an open change request.",
224 other: "This branch does not have an open pull request.",
225 },
226 )}`,
227 );
228 return;
229 }
230 if (!(await openPullRequest(prUrl))) {
231 Dialog.alert(
232 gt`${select(
233 { term },
234 {
235 mr: "Unable to open MR",
236 cr: "Unable to open change request",
237 other: "Unable to open PR",
238 },
239 )}`,
240 gt`${select(
241 { term },
242 {
243 mr: "The merge request could not be opened.",
244 cr: "The change request could not be opened.",
245 other: "The pull request could not be opened.",
246 },
247 )}`,
248 );
249 }
250 };
251
252 const runActionWithPrompt = async (input: GitActionRequestInput) => {
253 if (!canWriteSourceControl) return;
254 const confirmableAction =
255 input.action === "push" ||
256 input.action === "create_pr" ||
257 input.action === "commit_push" ||
258 input.action === "commit_push_pr"
259 ? input.action
260 : null;
261 const branchName = gitStatus.data?.refName;
262 if (
263 branchName &&
264 confirmableAction &&
265 !input.featureBranch &&
266 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
267 ) {
268 presentRoute(() =>
269 navigation.navigate("GitConfirm", {
270 environmentId: String(environmentId),
271 threadId: String(threadId),
272 ...repositoryParams,
273 confirmAction: confirmableAction,
274 }),
275 );
276 return;
277 }
278
279 // Close a sheet so the thread shows the action's progress.
280 if (!isInspector) navigation.goBack();
281 else closeInspectorSheet?.();
282 await gitActions.onRunSelectedThreadGitAction(input);
283 };
284
285 const onPressMenuItem = async (item: (typeof menuItems)[number]) => {
286 if (item.disabled) return;
287 if (item.kind === "open_pr") {
288 await openExistingPr();
289 return;
290 }
291 if (!canWriteSourceControl) return;
292 if (item.dialogAction === "commit") {
293 presentRoute(() =>
294 navigation.navigate("GitCommit", {
295 environmentId: String(environmentId),
296 threadId: String(threadId),
297 ...repositoryParams,
298 }),
299 );
300 return;
301 }
302 if (item.dialogAction === "push") {
303 await runActionWithPrompt({ action: "push" });
304 return;
305 }
306 if (item.dialogAction === "create_pr") {
307 await runActionWithPrompt({ action: "create_pr" });
308 }
309 };
310
311 const rowStatusDetail = (item: (typeof menuItems)[number]): string | undefined => {
312 const status = gitStatus.data;
313 if (status == null) {
314 return undefined;
315 }
316 if (item.dialogAction === "commit" && status.hasWorkingTreeChanges) {
317 const fileCount = status.workingTree?.files.length ?? 0;
318 return gt`${plural(
319 { count: fileCount },
320 {
321 one: part`${{ count: fileCount }} file changed`,
322 other: part`${{ count: fileCount }} files changed`,
323 },
324 )}`;
325 }
326 if (item.dialogAction === "push" && (status.aheadCount ?? 0) > 0) {
327 const ahead = status.aheadCount ?? 0;
328 return gt`${plural(
329 { count: ahead },
330 {
331 one: part`${{ count: ahead }} commit ahead`,
332 other: part`${{ count: ahead }} commits ahead`,
333 },
334 )}`;
335 }
336 if (item.kind === "open_pr" && status.pr?.number != null) {
337 return gt`${select(
338 { term },
339 {
340 mr: part`MR #${{ number: status.pr.number }} ${select(
341 { state: status.pr.state ?? "open" },
342 {
343 open: "open",
344 closed: "closed",
345 merged: "merged",
346 other: part`${{ state: status.pr.state ?? "open" }}`,
347 },
348 )}`,
349 cr: part`change request #${{ number: status.pr.number }} ${select(
350 { state: status.pr.state ?? "open" },
351 {
352 open: "open",
353 closed: "closed",
354 merged: "merged",
355 other: part`${{ state: status.pr.state ?? "open" }}`,
356 },
357 )}`,
358 other: part`PR #${{ number: status.pr.number }} ${select(
359 { state: status.pr.state ?? "open" },
360 {
361 open: "open",
362 closed: "closed",
363 merged: "merged",
364 other: part`${{ state: status.pr.state ?? "open" }}`,
365 },
366 )}`,
367 },
368 )}`;
369 }
370 return undefined;
371 };
372
373 const behindCount = gitStatus.data?.behindCount ?? 0;
374
375 const openRepository = (section: ThreadRepositorySection) => {
376 const params = {
377 environmentId: String(environmentId),
378 threadId: String(threadId),
379 repositoryCwd: section.cwd,
380 repositoryName: section.name,
381 };
382 // A sheet swaps in place, so closing the repository or running an action lands on the thread.
383 if (presentation === "sheet") {
384 navigation.dispatch(StackActions.replace("GitOverview", params));
385 } else {
386 presentRoute(() => navigation.dispatch(StackActions.push("GitOverview", params)));
387 }
388 };
389
390 // Background refreshes also report pending; using that query flag would stick the RefreshControl spinner.
391 const [isRefreshing, setIsRefreshing] = useState(false);
392 const handleRefresh = async () => {
393 setIsRefreshing(true);
394 await gitActions.refreshSelectedThreadGitStatus();
395 setIsRefreshing(false);
396 };
397
398 const content = (
399 <NativeScrollView
400 nestedScrollEnabled
401 alwaysBounceVertical
402 className="flex-1 bg-screen"
403 contentInsetAdjustmentBehavior="automatic"
404 showsVerticalScrollIndicator={false}
405 contentContainerStyle={{
406 ...groupedListInsets(isInspector),
407 paddingTop: 8,
408 paddingBottom: Math.max(insets.bottom, 18) + 18,
409 }}
410 refreshControl={
411 <RefreshControl refreshing={isRefreshing} onRefresh={() => void handleRefresh()} />
412 }
413 >
414 {sheetMenuItems.length > 0 || behindCount > 0 ? (
415 <ListSection>
416 {sheetMenuItems.map(({ item, disabledReason }) => (
417 <ListRow
418 key={`${item.id}-${item.label}`}
419 icon={menuItemIconName(item.icon)}
420 label={item.label}
421 description={disabledReason ?? rowStatusDetail(item)}
422 disabled={item.disabled}
423 onPress={() => void onPressMenuItem(item)}
424 />
425 ))}
426 {behindCount > 0 ? (
427 <ListRow
428 icon="arrow.down.circle"
429 label={gt`Pull latest`}
430 description={
431 canWriteSourceControl
432 ? gt`${plural(
433 { count: behindCount },
434 {
435 one: part`${{ count: behindCount }} commit behind upstream`,
436 other: part`${{ count: behindCount }} commits behind upstream`,
437 },
438 )}`
439 : gt`This connection cannot change source control.`
440 }
441 disabled={!canWriteSourceControl || busy || !isRepo}
442 onPress={() => void gitActions.onPullSelectedThreadBranch()}
443 />
444 ) : null}
445 </ListSection>
446 ) : null}
447
448 {listsRepositories ? (
449 <ThreadRepositoryRows
450 threadRef={threadRef}
451 projectId={selectedThreadProject.id}
452 threadCwd={selectedThreadCwd}
453 taskFolder={taskFolder}
454 reachesTracked={reachesTracked}
455 onTaskFolderChange={taskFolderQuery.refresh}
456 explainsEmpty={!isRepo}
457 onOpen={openRepository}
458 />
459 ) : null}
460
461 {repository === undefined || isPinnedRepository ? (
462 <ListSection>
463 {repository === undefined ? (
464 <>
465 <ListRow
466 icon="text.bubble"
467 label={gt`Review changes`}
468 description={
469 trackedRepositoryCount > 0
470 ? gt`Inspect turn diffs`
471 : gt`Inspect changes, uncommitted edits, and turn diffs`
472 }
473 disabled={busy || !(isRepo || trackedRepositoryCount > 0)}
474 onPress={() => {
475 const params = { environmentId, threadId };
476 if (presentation === "sheet") {
477 navigation.dispatch(StackActions.replace("ThreadReview", params));
478 } else {
479 presentRoute(() =>
480 navigation.dispatch(CommonActions.navigate("ThreadReview", params)),
481 );
482 }
483 }}
484 />
485 <ListRow
486 icon="point.topleft.down.curvedto.point.bottomright.up"
487 label={gt`Branches & worktrees`}
488 description={
489 canChangeThreadBranch
490 ? gt`Switch branch, create branch, or move to a worktree`
491 : gt`View branches and worktrees`
492 }
493 disabled={busy || !isRepo}
494 onPress={() =>
495 presentRoute(() =>
496 navigation.navigate("GitBranches", {
497 environmentId: String(environmentId),
498 threadId: String(threadId),
499 }),
500 )
501 }
502 />
503 {linkedPrActions.canLink ? (
504 <ListRow
505 icon="link"
506 label={gt`${select(
507 { term: changeRequestTermKind(linkedPrActions.terminology) },
508 {
509 mr: "Link merge request",
510 cr: "Link change request",
511 other: "Link pull request",
512 },
513 )}`}
514 description={gt`${select(
515 { term: changeRequestTermKind(linkedPrActions.terminology) },
516 {
517 mr: "Attach a merge request by URL or number",
518 cr: "Attach a change request by URL or number",
519 other: "Attach a pull request by URL or number",
520 },
521 )}`}
522 onPress={linkedPrActions.promptLink}
523 />
524 ) : null}
525 </>
526 ) : isPinnedRepository ? (
527 <ListRow
528 icon="pin.slash"
529 label={gt`Remove from this thread`}
530 description={gt`The repository stays tracked by the project`}
531 disabled={busy}
532 onPress={() => {
533 unpinRepositoryFromThread(threadRef, repository.key);
534 navigation.goBack();
535 }}
536 />
537 ) : null}
538 </ListSection>
539 ) : null}
540
541 {repository === undefined && linkedPrLines.length > 0 ? (
542 <ListSection
543 title={gt`${select(
544 { term: changeRequestTermKind(linkedPrActions.terminology) },
545 {
546 mr: "Linked merge requests",
547 cr: "Linked change requests",
548 other: "Linked pull requests",
549 },
550 )}`}
551 >
552 {linkedPrLines.map((line, index) => (
553 <LinkedPullRequestRow
554 key={linkedPullRequestKey(line)}
555 line={line}
556 separator={index < linkedPrLines.length - 1}
557 surfaceClassName="text-grouped-card"
558 openPullRequest={openPullRequest}
559 actions={linkedPrActions}
560 />
561 ))}
562 </ListSection>
563 ) : null}
564
565 {currentWorktreePath ? (
566 <ListSection title={gt`Worktree`}>
567 <Text selectable textRole="footnote" className="p-4 text-foreground-muted">
568 {currentWorktreePath}
569 </Text>
570 </ListSection>
571 ) : null}
572 </NativeScrollView>
573 );
574
575 const refresh = {
576 accessibilityLabel: gt`Refresh repository status`,
577 disabled: busy || isRefreshing,
578 onPress: () => void handleRefresh(),
579 };
580
581 return (
582 <SheetPane surface={isInspector ? "screen" : "sheet"}>
583 <AppBar
584 title={currentBranchLabel}
585 subtitle={currentStatusSummary}
586 hideBottomBorder={!isInspector}
587 onClose={isInspector ? undefined : () => navigation.goBack()}
588 refresh={refresh}
589 />
590 <ScreenContent insetHorizontal={isInspector ? true : undefined}>{content}</ScreenContent>
591 </SheetPane>
592 );
593}