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