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

GitActionsControl.tsx

852 lines30.1 KB

1import type { GitStackedAction, GitStatusResult, ThreadId } from "@t3tools/contracts";
2import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
3import { useCallback, useEffect, useMemo, useState } from "react";
4import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
5import { GitHubIcon } from "./Icons";
6import {
7 buildGitActionProgressStages,
8 buildMenuItems,
9 type GitActionIconName,
10 type GitActionMenuItem,
11 type GitQuickAction,
12 type DefaultBranchConfirmableAction,
13 requiresDefaultBranchConfirmation,
14 resolveDefaultBranchActionDialogCopy,
15 resolveQuickAction,
16 summarizeGitResult,
17} from "./GitActionsControl.logic";
18import { Button } from "~/components/ui/button";
19import {
20 Dialog,
21 DialogDescription,
22 DialogFooter,
23 DialogHeader,
24 DialogPanel,
25 DialogPopup,
26 DialogTitle,
27} from "~/components/ui/dialog";
28import { Group, GroupSeparator } from "~/components/ui/group";
29import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
30import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
31import { ScrollArea } from "~/components/ui/scroll-area";
32import { Textarea } from "~/components/ui/textarea";
33import { toastManager } from "~/components/ui/toast";
34import {
35 gitBranchesQueryOptions,
36 gitInitMutationOptions,
37 gitMutationKeys,
38 gitPullMutationOptions,
39 gitRunStackedActionMutationOptions,
40 gitStatusQueryOptions,
41 invalidateGitQueries,
42} from "~/lib/gitReactQuery";
43import { preferredTerminalEditor, resolvePathLinkTarget } from "~/terminal-links";
44import { readNativeApi } from "~/nativeApi";
45​
46interface GitActionsControlProps {
47 gitCwd: string | null;
48 activeThreadId: ThreadId | null;
50​
51interface PendingDefaultBranchAction {
52 action: DefaultBranchConfirmableAction;
53 branchName: string;
54 includesCommit: boolean;
55 commitMessage?: string;
56 forcePushOnlyProgress: boolean;
57 onConfirmed?: () => void;
59​
60type GitActionToastId = ReturnType<typeof toastManager.add>;
61​
62function getMenuActionDisabledReason({
63 item,
64 gitStatus,
65 isBusy,
66 hasOriginRemote,
67}: {
68 item: GitActionMenuItem;
69 gitStatus: GitStatusResult | null;
70 isBusy: boolean;
71 hasOriginRemote: boolean;
72}): string | null {
73 if (!item.disabled) return null;
74 if (isBusy) return "Git action in progress.";
75 if (!gitStatus) return "Git status is unavailable.";
76​
77 const hasBranch = gitStatus.branch !== null;
78 const hasChanges = gitStatus.hasWorkingTreeChanges;
79 const hasOpenPr = gitStatus.pr?.state === "open";
80 const isAhead = gitStatus.aheadCount > 0;
81 const isBehind = gitStatus.behindCount > 0;
82​
83 if (item.id === "commit") {
84 if (!hasChanges) {
85 return "Worktree is clean. Make changes before committing.";
86 }
87 return "Commit is currently unavailable.";
88 }
89​
90 if (item.id === "push") {
91 if (!hasBranch) {
92 return "Detached HEAD: checkout a branch before pushing.";
93 }
94 if (hasChanges) {
95 return "Commit or stash local changes before pushing.";
96 }
97 if (isBehind) {
98 return "Branch is behind upstream. Pull/rebase before pushing.";
99 }
100 if (!gitStatus.hasUpstream && !hasOriginRemote) {
101 return 'Add an "origin" remote before pushing.';
102 }
103 if (!isAhead) {
104 return "No local commits to push.";
105 }
106 return "Push is currently unavailable.";
107 }
108​
109 if (hasOpenPr) {
110 return "View PR is currently unavailable.";
111 }
112 if (!hasBranch) {
113 return "Detached HEAD: checkout a branch before creating a PR.";
114 }
115 if (hasChanges) {
116 return "Commit local changes before creating a PR.";
117 }
118 if (!gitStatus.hasUpstream && !hasOriginRemote) {
119 return 'Add an "origin" remote before creating a PR.';
120 }
121 if (!isAhead) {
122 return "No local commits to include in a PR.";
123 }
124 if (isBehind) {
125 return "Branch is behind upstream. Pull/rebase before creating a PR.";
126 }
127 return "Create PR is currently unavailable.";
129​
130const COMMIT_DIALOG_TITLE = "Commit changes";
131const COMMIT_DIALOG_DESCRIPTION =
132 "Review and confirm your commit. Leave the message blank to auto-generate one.";
133​
134function GitActionItemIcon({ icon }: { icon: GitActionIconName }) {
135 if (icon === "commit") return <GitCommitIcon />;
136 if (icon === "push") return <CloudUploadIcon />;
137 return <GitHubIcon />;
139​
140function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
141 const iconClassName = "size-3.5";
142 if (quickAction.kind === "open_pr") return <GitHubIcon className={iconClassName} />;
143 if (quickAction.kind === "run_pull") return <InfoIcon className={iconClassName} />;
144 if (quickAction.kind === "run_action") {
145 if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
146 if (quickAction.action === "commit_push") return <CloudUploadIcon className={iconClassName} />;
147 return <GitHubIcon className={iconClassName} />;
148 }
149 if (quickAction.label === "Commit") return <GitCommitIcon className={iconClassName} />;
150 return <InfoIcon className={iconClassName} />;
152​
153export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsControlProps) {
154 const threadToastData = useMemo(
155 () => (activeThreadId ? { threadId: activeThreadId } : undefined),
156 [activeThreadId],
157 );
158 const queryClient = useQueryClient();
159 const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
160 const [dialogCommitMessage, setDialogCommitMessage] = useState("");
161 const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
162 useState<PendingDefaultBranchAction | null>(null);
163​
164 const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
165​
166 const { data: branchList = null } = useQuery(gitBranchesQueryOptions(gitCwd));
167 // Default to true while loading so we don't flash init controls.
168 const isRepo = branchList?.isRepo ?? true;
169 const hasOriginRemote = branchList?.hasOriginRemote ?? false;
170 const currentBranch = branchList?.branches.find((branch) => branch.current)?.name ?? null;
171 const isGitStatusOutOfSync =
172 !!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch;
173​
174 useEffect(() => {
175 if (!isGitStatusOutOfSync) return;
176 void invalidateGitQueries(queryClient);
177 }, [isGitStatusOutOfSync, queryClient]);
178​
179 const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
180​
181 const initMutation = useMutation(gitInitMutationOptions({ cwd: gitCwd, queryClient }));
182​
183 const runImmediateGitActionMutation = useMutation(
184 gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
185 );
186 const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
187​
188 const isRunStackedActionRunning =
189 useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
190 const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
191 const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
192 const isDefaultBranch = useMemo(() => {
193 const branchName = gitStatusForActions?.branch;
194 if (!branchName) return false;
195 const current = branchList?.branches.find((branch) => branch.name === branchName);
196 return current?.isDefault ?? (branchName === "main" || branchName === "master");
197 }, [branchList?.branches, gitStatusForActions?.branch]);
198​
199 const gitActionMenuItems = useMemo(
200 () => buildMenuItems(gitStatusForActions, isGitActionRunning, hasOriginRemote),
201 [gitStatusForActions, hasOriginRemote, isGitActionRunning],
202 );
203 const quickAction = useMemo(
204 () =>
205 resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultBranch, hasOriginRemote),
206 [gitStatusForActions, hasOriginRemote, isDefaultBranch, isGitActionRunning],
207 );
208 const quickActionDisabledReason = quickAction.disabled
209 ? (quickAction.hint ?? "This action is currently unavailable.")
210 : null;
211 const pendingDefaultBranchActionCopy = pendingDefaultBranchAction
212 ? resolveDefaultBranchActionDialogCopy({
213 action: pendingDefaultBranchAction.action,
214 branchName: pendingDefaultBranchAction.branchName,
215 includesCommit: pendingDefaultBranchAction.includesCommit,
216 })
217 : null;
218​
219 const openExistingPr = useCallback(async () => {
220 const api = readNativeApi();
221 if (!api) {
222 toastManager.add({
223 type: "error",
224 title: "Link opening is unavailable.",
225 data: threadToastData,
226 });
227 return;
228 }
229 const prUrl = gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : null;
230 if (!prUrl) {
231 toastManager.add({
232 type: "error",
233 title: "No open PR found.",
234 data: threadToastData,
235 });
236 return;
237 }
238 void api.shell.openExternal(prUrl).catch((err) => {
239 toastManager.add({
240 type: "error",
241 title: "Unable to open PR link",
242 description: err instanceof Error ? err.message : "An error occurred.",
243 data: threadToastData,
244 });
245 });
246 }, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
247​
248 const runGitActionWithToast = useCallback(
249 async ({
250 action,
251 commitMessage,
252 forcePushOnlyProgress = false,
253 onConfirmed,
254 skipDefaultBranchPrompt = false,
255 statusOverride,
256 featureBranch = false,
257 isDefaultBranchOverride,
258 progressToastId,
259 }: {
260 action: GitStackedAction;
261 commitMessage?: string;
262 forcePushOnlyProgress?: boolean;
263 onConfirmed?: () => void;
264 skipDefaultBranchPrompt?: boolean;
265 statusOverride?: GitStatusResult | null;
266 featureBranch?: boolean;
267 isDefaultBranchOverride?: boolean;
268 progressToastId?: GitActionToastId;
269 }) => {
270 const actionStatus = statusOverride ?? gitStatusForActions;
271 const actionBranch = actionStatus?.branch ?? null;
272 const actionIsDefaultBranch =
273 isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch);
274 const includesCommit =
275 !forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
276 if (
277 !skipDefaultBranchPrompt &&
278 requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
279 actionBranch
280 ) {
281 if (action !== "commit_push" && action !== "commit_push_pr") {
282 return;
283 }
284 setPendingDefaultBranchAction({
285 action,
286 branchName: actionBranch,
287 includesCommit,
288 ...(commitMessage ? { commitMessage } : {}),
289 forcePushOnlyProgress,
290 ...(onConfirmed ? { onConfirmed } : {}),
291 });
292 return;
293 }
294 onConfirmed?.();
295​
296 const progressStages = buildGitActionProgressStages({
297 action,
298 hasCustomCommitMessage: !!commitMessage?.trim(),
299 hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
300 forcePushOnly: forcePushOnlyProgress,
301 featureBranch,
302 });
303 const resolvedProgressToastId =
304 progressToastId ??
305 toastManager.add({
306 type: "loading",
307 title: progressStages[0] ?? "Running git action...",
308 timeout: 0,
309 data: threadToastData,
310 });
311​
312 if (progressToastId) {
313 toastManager.update(progressToastId, {
314 type: "loading",
315 title: progressStages[0] ?? "Running git action...",
316 timeout: 0,
317 data: threadToastData,
318 });
319 }
320​
321 let stageIndex = 0;
322 const stageInterval = setInterval(() => {
323 stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
324 toastManager.update(resolvedProgressToastId, {
325 title: progressStages[stageIndex] ?? "Running git action...",
326 type: "loading",
327 timeout: 0,
328 data: threadToastData,
329 });
330 }, 1100);
331​
332 const stopProgressUpdates = () => {
333 clearInterval(stageInterval);
334 };
335​
336 const promise = runImmediateGitActionMutation.mutateAsync({
337 action,
338 ...(commitMessage ? { commitMessage } : {}),
339 ...(featureBranch ? { featureBranch } : {}),
340 });
341​
342 try {
343 const result = await promise;
344 stopProgressUpdates();
345 const resultToast = summarizeGitResult(result);
346​
347 const existingOpenPrUrl =
348 actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
349 const prUrl = result.pr.url ?? existingOpenPrUrl;
350 const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
351 const shouldOfferOpenPrCta =
352 (action === "commit_push" || action === "commit_push_pr") &&
353 !!prUrl &&
354 (!actionIsDefaultBranch ||
355 result.pr.status === "created" ||
356 result.pr.status === "opened_existing");
357 const shouldOfferCreatePrCta =
358 action === "commit_push" &&
359 !prUrl &&
360 result.push.status === "pushed" &&
361 !actionIsDefaultBranch;
362 const closeResultToast = () => {
363 toastManager.close(resolvedProgressToastId);
364 };
365​
366 toastManager.update(resolvedProgressToastId, {
367 type: "success",
368 title: resultToast.title,
369 description: resultToast.description,
370 timeout: 0,
371 data: {
372 ...threadToastData,
373 dismissAfterVisibleMs: 10_000,
374 },
375 ...(shouldOfferPushCta
376 ? {
377 actionProps: {
378 children: "Push",
379 onClick: () => {
380 void runGitActionWithToast({
381 action: "commit_push",
382 forcePushOnlyProgress: true,
383 onConfirmed: closeResultToast,
384 statusOverride: actionStatus,
385 isDefaultBranchOverride: actionIsDefaultBranch,
386 });
387 },
388 },
389 }
390 : shouldOfferOpenPrCta
391 ? {
392 actionProps: {
393 children: "View PR",
394 onClick: () => {
395 const api = readNativeApi();
396 if (!api) return;
397 closeResultToast();
398 void api.shell.openExternal(prUrl);
399 },
400 },
401 }
402 : shouldOfferCreatePrCta
403 ? {
404 actionProps: {
405 children: "Create PR",
406 onClick: () => {
407 closeResultToast();
408 void runGitActionWithToast({
409 action: "commit_push_pr",
410 forcePushOnlyProgress: true,
411 statusOverride: actionStatus,
412 isDefaultBranchOverride: actionIsDefaultBranch,
413 });
414 },
415 },
416 }
417 : {}),
418 });
419 } catch (err) {
420 stopProgressUpdates();
421 toastManager.update(resolvedProgressToastId, {
422 type: "error",
423 title: "Action failed",
424 description: err instanceof Error ? err.message : "An error occurred.",
425 data: threadToastData,
426 });
427 }
428 },
429​
430 [
431 isDefaultBranch,
432 runImmediateGitActionMutation,
433 setPendingDefaultBranchAction,
434 threadToastData,
435 gitStatusForActions,
436 ],
437 );
438​
439 const continuePendingDefaultBranchAction = useCallback(() => {
440 if (!pendingDefaultBranchAction) return;
441 const { action, commitMessage, forcePushOnlyProgress, onConfirmed } =
442 pendingDefaultBranchAction;
443 setPendingDefaultBranchAction(null);
444 void runGitActionWithToast({
445 action,
446 ...(commitMessage ? { commitMessage } : {}),
447 forcePushOnlyProgress,
448 ...(onConfirmed ? { onConfirmed } : {}),
449 skipDefaultBranchPrompt: true,
450 });
451 }, [pendingDefaultBranchAction, runGitActionWithToast]);
452​
453 const checkoutNewBranchAndRunAction = useCallback(
454 (actionParams: {
455 action: GitStackedAction;
456 commitMessage?: string;
457 forcePushOnlyProgress?: boolean;
458 onConfirmed?: () => void;
459 }) => {
460 void runGitActionWithToast({
461 ...actionParams,
462 featureBranch: true,
463 skipDefaultBranchPrompt: true,
464 });
465 },
466 [runGitActionWithToast],
467 );
468​
469 const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
470 if (!pendingDefaultBranchAction) return;
471 const { action, commitMessage, forcePushOnlyProgress, onConfirmed } =
472 pendingDefaultBranchAction;
473 setPendingDefaultBranchAction(null);
474 checkoutNewBranchAndRunAction({
475 action,
476 ...(commitMessage ? { commitMessage } : {}),
477 forcePushOnlyProgress,
478 ...(onConfirmed ? { onConfirmed } : {}),
479 });
480 }, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
481​
482 const runDialogActionOnNewBranch = useCallback(() => {
483 if (!isCommitDialogOpen) return;
484 const commitMessage = dialogCommitMessage.trim();
485​
486 setIsCommitDialogOpen(false);
487 setDialogCommitMessage("");
488​
489 checkoutNewBranchAndRunAction({
490 action: "commit",
491 ...(commitMessage ? { commitMessage } : {}),
492 });
493 }, [isCommitDialogOpen, dialogCommitMessage, checkoutNewBranchAndRunAction]);
494​
495 const runQuickAction = useCallback(() => {
496 if (quickAction.kind === "open_pr") {
497 void openExistingPr();
498 return;
499 }
500 if (quickAction.kind === "run_pull") {
501 const promise = pullMutation.mutateAsync();
502 toastManager.promise(promise, {
503 loading: { title: "Pulling...", data: threadToastData },
504 success: (result) => ({
505 title: result.status === "pulled" ? "Pulled" : "Already up to date",
506 description:
507 result.status === "pulled"
508 ? `Updated ${result.branch} from ${result.upstreamBranch ?? "upstream"}`
509 : `${result.branch} is already synchronized.`,
510 data: threadToastData,
511 }),
512 error: (err) => ({
513 title: "Pull failed",
514 description: err instanceof Error ? err.message : "An error occurred.",
515 data: threadToastData,
516 }),
517 });
518 void promise.catch(() => undefined);
519 return;
520 }
521 if (quickAction.kind === "show_hint") {
522 toastManager.add({
523 type: "info",
524 title: quickAction.label,
525 description: quickAction.hint,
526 data: threadToastData,
527 });
528 return;
529 }
530 if (quickAction.action) {
531 void runGitActionWithToast({ action: quickAction.action });
532 }
533 }, [openExistingPr, pullMutation, quickAction, runGitActionWithToast, threadToastData]);
534​
535 const openDialogForMenuItem = useCallback(
536 (item: GitActionMenuItem) => {
537 if (item.disabled) return;
538 if (item.kind === "open_pr") {
539 void openExistingPr();
540 return;
541 }
542 if (item.dialogAction === "push") {
543 void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
544 return;
545 }
546 if (item.dialogAction === "create_pr") {
547 void runGitActionWithToast({ action: "commit_push_pr" });
548 return;
549 }
550 setIsCommitDialogOpen(true);
551 },
552 [openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
553 );
554​
555 const runDialogAction = useCallback(() => {
556 if (!isCommitDialogOpen) return;
557 const commitMessage = dialogCommitMessage.trim();
558 setIsCommitDialogOpen(false);
559 setDialogCommitMessage("");
560 void runGitActionWithToast({
561 action: "commit",
562 ...(commitMessage ? { commitMessage } : {}),
563 });
564 }, [
565 dialogCommitMessage,
566 isCommitDialogOpen,
567 runGitActionWithToast,
568 setDialogCommitMessage,
569 setIsCommitDialogOpen,
570 ]);
571​
572 const openChangedFileInEditor = useCallback(
573 (filePath: string) => {
574 const api = readNativeApi();
575 if (!api || !gitCwd) {
576 toastManager.add({
577 type: "error",
578 title: "Editor opening is unavailable.",
579 data: threadToastData,
580 });
581 return;
582 }
583 const target = resolvePathLinkTarget(filePath, gitCwd);
584 void api.shell.openInEditor(target, preferredTerminalEditor()).catch((error) => {
585 toastManager.add({
586 type: "error",
587 title: "Unable to open file",
588 description: error instanceof Error ? error.message : "An error occurred.",
589 data: threadToastData,
590 });
591 });
592 },
593 [gitCwd, threadToastData],
594 );
595​
596 if (!gitCwd) return null;
597​
598 return (
599 <>
600 {!isRepo ? (
601 <Button
602 variant="outline"
603 size="xs"
604 disabled={initMutation.isPending}
605 onClick={() => initMutation.mutate()}
606 >
607 {initMutation.isPending ? "Initializing..." : "Initialize Git"}
608 </Button>
609 ) : (
610 <Group aria-label="Git actions">
611 {quickActionDisabledReason ? (
612 <Popover>
613 <PopoverTrigger
614 openOnHover
615 render={
616 <Button
617 aria-disabled="true"
618 className="cursor-not-allowed rounded-e-none border-e-0 opacity-64 before:rounded-e-none"
619 size="xs"
620 variant="outline"
621 />
622 }
623 >
624 <GitQuickActionIcon quickAction={quickAction} />
625 <span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
626 {quickAction.label}
627 </span>
628 </PopoverTrigger>
629 <PopoverPopup tooltipStyle side="bottom" align="start">
630 {quickActionDisabledReason}
631 </PopoverPopup>
632 </Popover>
633 ) : (
634 <Button
635 variant="outline"
636 size="xs"
637 disabled={isGitActionRunning || quickAction.disabled}
638 onClick={runQuickAction}
639 >
640 <GitQuickActionIcon quickAction={quickAction} />
641 <span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
642 {quickAction.label}
643 </span>
644 </Button>
645 )}
646 <GroupSeparator className="hidden @sm/header-actions:block" />
647 <Menu
648 onOpenChange={(open) => {
649 if (open) void invalidateGitQueries(queryClient);
650 }}
651 >
652 <MenuTrigger
653 render={<Button aria-label="Git action options" size="icon-xs" variant="outline" />}
654 disabled={isGitActionRunning}
655 >
656 <ChevronDownIcon aria-hidden="true" className="size-4" />
657 </MenuTrigger>
658 <MenuPopup align="end" className="w-full">
659 {gitActionMenuItems.map((item) => {
660 const disabledReason = getMenuActionDisabledReason({
661 item,
662 gitStatus: gitStatusForActions,
663 isBusy: isGitActionRunning,
664 hasOriginRemote,
665 });
666 if (item.disabled && disabledReason) {
667 return (
668 <Popover key={`${item.id}-${item.label}`}>
669 <PopoverTrigger
670 openOnHover
671 nativeButton={false}
672 render={<span className="block w-max cursor-not-allowed" />}
673 >
674 <MenuItem className="w-full" disabled>
675 <GitActionItemIcon icon={item.icon} />
676 {item.label}
677 </MenuItem>
678 </PopoverTrigger>
679 <PopoverPopup tooltipStyle side="left" align="center">
680 {disabledReason}
681 </PopoverPopup>
682 </Popover>
683 );
684 }
685​
686 return (
687 <MenuItem
688 key={`${item.id}-${item.label}`}
689 disabled={item.disabled}
690 onClick={() => {
691 openDialogForMenuItem(item);
692 }}
693 >
694 <GitActionItemIcon icon={item.icon} />
695 {item.label}
696 </MenuItem>
697 );
698 })}
699 {gitStatusForActions?.branch === null && (
700 <p className="px-2 py-1.5 text-xs text-warning">
701 Detached HEAD: create and checkout a branch to enable push and PR actions.
702 </p>
703 )}
704 {gitStatusForActions &&
705 gitStatusForActions.branch !== null &&
706 !gitStatusForActions.hasWorkingTreeChanges &&
707 gitStatusForActions.behindCount > 0 &&
708 gitStatusForActions.aheadCount === 0 && (
709 <p className="px-2 py-1.5 text-xs text-warning">
710 Behind upstream. Pull/rebase first.
711 </p>
712 )}
713 {isGitStatusOutOfSync && (
714 <p className="px-2 py-1.5 text-xs text-muted-foreground">
715 Refreshing git status...
716 </p>
717 )}
718 {gitStatusError && (
719 <p className="px-2 py-1.5 text-xs text-destructive">{gitStatusError.message}</p>
720 )}
721 </MenuPopup>
722 </Menu>
723 </Group>
724 )}
725​
726 <Dialog
727 open={isCommitDialogOpen}
728 onOpenChange={(open) => {
729 if (!open) {
730 setIsCommitDialogOpen(false);
731 setDialogCommitMessage("");
732 }
733 }}
734 >
735 <DialogPopup>
736 <DialogHeader>
737 <DialogTitle>{COMMIT_DIALOG_TITLE}</DialogTitle>
738 <DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
739 </DialogHeader>
740 <DialogPanel className="space-y-4">
741 <div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
742 <div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
743 <span className="text-muted-foreground">Branch</span>
744 <span className="flex items-center justify-between gap-2">
745 <span className="font-medium">
746 {gitStatusForActions?.branch ?? "(detached HEAD)"}
747 </span>
748 {isDefaultBranch && (
749 <span className="text-right text-warning text-xs">Warning: default branch</span>
750 )}
751 </span>
752 </div>
753 <div className="space-y-1">
754 <p className="text-muted-foreground">Files</p>
755 {!gitStatusForActions || gitStatusForActions.workingTree.files.length === 0 ? (
756 <p className="font-medium">none</p>
757 ) : (
758 <div className="space-y-2">
759 <ScrollArea className="h-44 rounded-md border border-input bg-background">
760 <div className="space-y-1 p-1">
761 {gitStatusForActions.workingTree.files.map((file) => (
762 <button
763 type="button"
764 key={file.path}
765 className="flex w-full items-center justify-between gap-3 rounded-md px-2 py-1 font-mono text-left transition-colors hover:bg-accent/50"
766 onClick={() => openChangedFileInEditor(file.path)}
767 >
768 <span className="truncate">{file.path}</span>
769 <span className="shrink-0">
770 <span className="text-success">+{file.insertions}</span>
771 <span className="text-muted-foreground"> / </span>
772 <span className="text-destructive">-{file.deletions}</span>
773 </span>
774 </button>
775 ))}
776 </div>
777 </ScrollArea>
778 <div className="flex justify-end font-mono">
779 <span className="text-success">
780 +{gitStatusForActions.workingTree.insertions}
781 </span>
782 <span className="text-muted-foreground"> / </span>
783 <span className="text-destructive">
784 -{gitStatusForActions.workingTree.deletions}
785 </span>
786 </div>
787 </div>
788 )}
789 </div>
790 </div>
791 <div className="space-y-1">
792 <p className="text-xs font-medium">Commit message (optional)</p>
793 <Textarea
794 value={dialogCommitMessage}
795 onChange={(event) => setDialogCommitMessage(event.target.value)}
796 placeholder="Leave empty to auto-generate"
797 size="sm"
798 />
799 </div>
800 </DialogPanel>
801 <DialogFooter>
802 <Button
803 variant="outline"
804 size="sm"
805 onClick={() => {
806 setIsCommitDialogOpen(false);
807 setDialogCommitMessage("");
808 }}
809 >
810 Cancel
811 </Button>
812 <Button variant="outline" size="sm" onClick={runDialogActionOnNewBranch}>
813 Commit on new branch
814 </Button>
815 <Button size="sm" onClick={runDialogAction}>
816 Commit
817 </Button>
818 </DialogFooter>
819 </DialogPopup>
820 </Dialog>
821​
822 <Dialog
823 open={pendingDefaultBranchAction !== null}
824 onOpenChange={(open) => {
825 if (!open) {
826 setPendingDefaultBranchAction(null);
827 }
828 }}
829 >
830 <DialogPopup className="max-w-xl">
831 <DialogHeader>
832 <DialogTitle>
833 {pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"}
834 </DialogTitle>
835 <DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
836 </DialogHeader>
837 <DialogFooter>
838 <Button variant="outline" size="sm" onClick={() => setPendingDefaultBranchAction(null)}>
839 Abort
840 </Button>
841 <Button variant="outline" size="sm" onClick={continuePendingDefaultBranchAction}>
842 {pendingDefaultBranchActionCopy?.continueLabel ?? "Continue"}
843 </Button>
844 <Button size="sm" onClick={checkoutFeatureBranchAndContinuePendingAction}>
845 Checkout feature branch & continue
846 </Button>
847 </DialogFooter>
848 </DialogPopup>
849 </Dialog>
850 </>
851 );