From e99f81394e3aefef7d51326e69e4a38075645615 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Almeida?= <57680069+zeval@users.noreply.github.com> Date: Wed, 1 Jul 2026 23:43:04 +0100 Subject: [PATCH] feat: press Enter on a dialog to run its semantic action (#1565) * feat: press Enter on a dialog to run its semantic action * fix: harden dialog Enter-to-confirm from review feedback * fix: refine dialog Enter guards and fix prettier CI --- apps/packages/ui/src/alert-dialog.tsx | 10 + apps/packages/ui/src/dialog.tsx | 10 + .../ui/src/lib/dialog-default-action.ts | 152 ++++++++ apps/web/AGENTS.md | 15 + .../github/my-github/save-preset-dialog.tsx | 3 - .../gitlab/my-gitlab/save-preset-dialog.tsx | 3 - .../task/layout-preset-selector.tsx | 3 - .../components/task/task-rename-dialog.tsx | 3 - .../kanban/dialog-enter-confirms.spec.ts | 41 +++ apps/web/lib/dialog-default-action.test.ts | 332 ++++++++++++++++++ 10 files changed, 560 insertions(+), 12 deletions(-) create mode 100644 apps/packages/ui/src/lib/dialog-default-action.ts create mode 100644 apps/web/e2e/tests/kanban/dialog-enter-confirms.spec.ts create mode 100644 apps/web/lib/dialog-default-action.test.ts diff --git a/apps/packages/ui/src/alert-dialog.tsx b/apps/packages/ui/src/alert-dialog.tsx index 0b3dd77fde..315367ed85 100644 --- a/apps/packages/ui/src/alert-dialog.tsx +++ b/apps/packages/ui/src/alert-dialog.tsx @@ -5,6 +5,7 @@ import { AlertDialog as AlertDialogPrimitive } from "radix-ui"; import { cn } from "./lib/utils"; import { Button } from "./button"; +import { handleDialogDefaultActionKeyDown } from "./lib/dialog-default-action"; function AlertDialog({ ...props }: React.ComponentProps) { React.useEffect(() => { @@ -50,10 +51,18 @@ function AlertDialogOverlay({ function AlertDialogContent({ className, size = "default", + enterConfirms = true, + onKeyDown, ...props }: React.ComponentProps & { size?: "default" | "sm"; + /** Pressing Enter activates the semantic action button. Default: true. */ + enterConfirms?: boolean; }) { + const handleKeyDown = (event: React.KeyboardEvent) => { + onKeyDown?.(event); + if (enterConfirms) handleDialogDefaultActionKeyDown(event); + }; return ( @@ -64,6 +73,7 @@ function AlertDialogContent({ "data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 bg-background ring-foreground/10 gap-3 rounded-xl p-4 ring-1 duration-100 data-[size=default]:max-w-xs data-[size=sm]:max-w-64 data-[size=default]:sm:max-w-sm group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 outline-none", className, )} + onKeyDown={handleKeyDown} {...props} /> diff --git a/apps/packages/ui/src/dialog.tsx b/apps/packages/ui/src/dialog.tsx index 072f3ff5f0..85fbcb375b 100644 --- a/apps/packages/ui/src/dialog.tsx +++ b/apps/packages/ui/src/dialog.tsx @@ -6,6 +6,7 @@ import { Dialog as DialogPrimitive } from "radix-ui"; import { cn } from "./lib/utils"; import { Button } from "./button"; import { IconX } from "@tabler/icons-react"; +import { handleDialogDefaultActionKeyDown } from "./lib/dialog-default-action"; function Dialog({ ...props }: React.ComponentProps) { React.useEffect(() => { @@ -57,11 +58,19 @@ function DialogContent({ children, showCloseButton = true, overlayClassName, + enterConfirms = true, + onKeyDown, ...props }: React.ComponentProps & { showCloseButton?: boolean; overlayClassName?: string; + /** Pressing Enter activates the semantic action button. Default: true. */ + enterConfirms?: boolean; }) { + const handleKeyDown = (event: React.KeyboardEvent) => { + onKeyDown?.(event); + if (enterConfirms) handleDialogDefaultActionKeyDown(event); + }; return ( @@ -71,6 +80,7 @@ function DialogContent({ "border-border bg-popover text-popover-foreground data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 grid max-w-[calc(100%-2rem)] gap-4 rounded-lg border p-4 text-xs/relaxed shadow-md duration-100 sm:max-w-lg fixed top-1/2 left-1/2 z-50 w-full -translate-x-1/2 -translate-y-1/2", className, )} + onKeyDown={handleKeyDown} {...props} > {children} diff --git a/apps/packages/ui/src/lib/dialog-default-action.ts b/apps/packages/ui/src/lib/dialog-default-action.ts new file mode 100644 index 0000000000..80ed4831c0 --- /dev/null +++ b/apps/packages/ui/src/lib/dialog-default-action.ts @@ -0,0 +1,152 @@ +import * as React from "react"; + +/** + * Enter-to-confirm for dialogs. + * + * Pressing Enter inside a dialog should execute its semantically focused + * action — the destructive/primary button — regardless of which control + * currently holds DOM focus (Radix, for example, focuses the Cancel button of + * an AlertDialog by default). This module resolves that button from the dialog + * content and exposes a keydown handler the base Dialog/AlertDialog content + * components attach. + * + * Note: a plain single-line `` is intentionally *not* exempt — dialogs + * such as a "type the name to confirm" delete flow expect Enter in the input to + * fire the primary action. Only text-entry surfaces where Enter means "newline" + * (`textarea`, contenteditable) are skipped. Interactive controls with their own + * Enter semantics (other buttons, ``, a combobox, or an item inside one — let that + * control handle it instead of hijacking Enter for the footer action. The one + * exception is a genuine dismiss control (an AlertDialog Cancel or the close + * "X", identified by its `data-slot`): overriding those is the whole point, + * since Radix focuses Cancel on an AlertDialog by default. + */ +function focusKeepsEnter(target: EventTarget | null, action: HTMLElement): boolean { + if (!(target instanceof HTMLElement)) return false; + if (target === action) return true; // let native activation click it (no double-fire) + + const role = target.getAttribute("role"); + const interactive = + target.tagName === "BUTTON" || + target.tagName === "A" || + target.tagName === "SELECT" || + (role !== null && INTERACTIVE_ROLES.has(role)); + if (!interactive) return false; + + // Only real cancel/close controls are overridden — matched by their explicit + // slot, not by variant, so outline/secondary buttons that are real actions + // keep their native Enter behavior. + const slot = target.getAttribute("data-slot"); + if (slot === "alert-dialog-cancel" || slot === "dialog-close") return false; + + return true; +} + +/** + * Keydown handler for dialog content. Attach to the Radix `*Content` element so + * `event.currentTarget` is the dialog content root. On a plain Enter it + * activates the resolved semantic action; everything else falls through + * untouched. + */ +export function handleDialogDefaultActionKeyDown(event: React.KeyboardEvent): void { + if (event.key !== "Enter") return; + if (event.shiftKey || event.metaKey || event.ctrlKey || event.altKey) return; + if (event.repeat) return; // ignore auto-repeat while Enter is held down + if (event.defaultPrevented) return; + // mid-IME composition: `isComposing`, plus keyCode 229 which some IMEs report + // for the Enter that accepts a candidate even after isComposing flips false. + if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return; + if (isTextEntry(event.target)) return; + + const action = resolveDialogDefaultAction(event.currentTarget); + if (!action) return; + if (focusKeepsEnter(event.target, action)) return; + + event.preventDefault(); + action.click(); +} diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index 32826ebd36..00d4912747 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -92,6 +92,21 @@ surface. - Components: <200 lines, extract to domain components, composition over props. - Hooks: domain-organized in `hooks/domains/`, encapsulate subscription + selection. - **Interactivity:** all buttons and links with actions must have `cursor-pointer` class. +- **Dialog Enter-to-confirm:** the base `@kandev/ui` `DialogContent` / `AlertDialogContent` + activate the dialog's semantic action on plain Enter (`packages/ui/src/lib/dialog-default-action.ts`), + so per-dialog "submit on Enter" input handlers are unnecessary — let the base own it. + Resolution: `AlertDialogAction` → an explicit `data-dialog-default-action` button → the single + primary (`type="submit"` or `data-variant="default"|"destructive"`) button in `DialogFooter`. + More than one primary candidate (counting disabled ones), a disabled resolved action, or one inside + a `hidden`/`aria-hidden` subtree → no-op (never guesses). Left alone: `textarea`/contenteditable, + Shift/Cmd/Ctrl/Alt+Enter, `event.repeat` auto-repeat, mid-IME composition (`isComposing` or keyCode + 229), already-`preventDefault`ed events, and Enter fired from a focused interactive control that owns + Enter (any action button — including outline/secondary like Copy/Back — `` is + _not_ exempt — type-to-confirm dialogs rely on Enter firing the primary. + Pass `enterConfirms={false}` to opt a dialog out; mark the intended button with + `data-dialog-default-action` when a footer has several action buttons. - **Radix tooltip on disabled buttons:** disabled buttons do not receive pointer/focus events, so wrap the disabled `Button` in a focusable span and put `TooltipTrigger asChild` on that span: ```tsx diff --git a/apps/web/components/github/my-github/save-preset-dialog.tsx b/apps/web/components/github/my-github/save-preset-dialog.tsx index 69b7a75267..74f0765307 100644 --- a/apps/web/components/github/my-github/save-preset-dialog.tsx +++ b/apps/web/components/github/my-github/save-preset-dialog.tsx @@ -67,9 +67,6 @@ function SavePresetForm({ autoFocus value={value} onChange={(e) => setValue(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Enter") handleSubmit(); - }} onFocus={(e) => e.target.select()} placeholder="e.g. Needs my review" /> diff --git a/apps/web/components/gitlab/my-gitlab/save-preset-dialog.tsx b/apps/web/components/gitlab/my-gitlab/save-preset-dialog.tsx index e26080ba48..f1d65aaf91 100644 --- a/apps/web/components/gitlab/my-gitlab/save-preset-dialog.tsx +++ b/apps/web/components/gitlab/my-gitlab/save-preset-dialog.tsx @@ -67,9 +67,6 @@ function SavePresetForm({ autoFocus value={value} onChange={(e) => setValue(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Enter") handleSubmit(); - }} onFocus={(e) => e.target.select()} placeholder="e.g. Needs my review" /> diff --git a/apps/web/components/task/layout-preset-selector.tsx b/apps/web/components/task/layout-preset-selector.tsx index 108bfb8629..4e3aa1e4a4 100644 --- a/apps/web/components/task/layout-preset-selector.tsx +++ b/apps/web/components/task/layout-preset-selector.tsx @@ -130,9 +130,6 @@ function SaveLayoutDialog({ onChange={(e) => setName(e.target.value)} placeholder="My layout" autoFocus - onKeyDown={(e) => { - if (e.key === "Enter") handleSave(); - }} />
diff --git a/apps/web/components/task/task-rename-dialog.tsx b/apps/web/components/task/task-rename-dialog.tsx index 02bcb47e77..5ee8ea8513 100644 --- a/apps/web/components/task/task-rename-dialog.tsx +++ b/apps/web/components/task/task-rename-dialog.tsx @@ -44,9 +44,6 @@ function TaskRenameForm({ autoFocus value={value} onChange={(e) => setValue(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Enter") handleSubmit(); - }} onFocus={(e) => e.target.select()} placeholder="Task title" /> diff --git a/apps/web/e2e/tests/kanban/dialog-enter-confirms.spec.ts b/apps/web/e2e/tests/kanban/dialog-enter-confirms.spec.ts new file mode 100644 index 0000000000..37565344df --- /dev/null +++ b/apps/web/e2e/tests/kanban/dialog-enter-confirms.spec.ts @@ -0,0 +1,41 @@ +import { test, expect } from "../../fixtures/test-base"; +import { KanbanPage } from "../../pages/kanban-page"; + +const TASK_VISIBLE_TIMEOUT = 10_000; + +// Pressing Enter on a dialog must execute its semantically focused action. +// For the delete-task confirm dialog that means the destructive "Delete" +// button, without the user having to click it or tab to it. +test.describe("Dialog Enter key — executes the semantic action", () => { + test("pressing Enter on the delete-task confirm dialog deletes the task", async ({ + testPage, + apiClient, + seedData, + }) => { + const task = await apiClient.createTask(seedData.workspaceId, "Enter Delete Task", { + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + }); + const kanban = new KanbanPage(testPage); + await kanban.goto(); + + await expect(kanban.taskCardByTitle("Enter Delete Task")).toBeVisible({ + timeout: TASK_VISIBLE_TIMEOUT, + }); + + await kanban.openTaskActionsMenu(task.id); + await testPage.getByRole("menuitem", { name: "Delete" }).click(); + + const dialog = testPage.getByRole("alertdialog"); + await expect(dialog).toBeVisible(); + await expect(dialog).toContainText("Enter Delete Task"); + + // Do NOT click Delete — Enter alone must trigger the destructive action. + await testPage.keyboard.press("Enter"); + + await expect(dialog).not.toBeVisible(); + await expect(kanban.taskCardByTitle("Enter Delete Task")).not.toBeVisible({ + timeout: TASK_VISIBLE_TIMEOUT, + }); + }); +}); diff --git a/apps/web/lib/dialog-default-action.test.ts b/apps/web/lib/dialog-default-action.test.ts new file mode 100644 index 0000000000..c4ea0ebc43 --- /dev/null +++ b/apps/web/lib/dialog-default-action.test.ts @@ -0,0 +1,332 @@ +import { describe, it, expect, vi } from "vitest"; +import { + resolveDialogDefaultAction, + handleDialogDefaultActionKeyDown, +} from "@kandev/ui/lib/dialog-default-action"; +import type React from "react"; + +/** + * Unit coverage for the "Enter confirms the semantic action" resolver + keydown + * handler used by the base Dialog / AlertDialog components. Builds real DOM + * subtrees mirroring the markup the base components render, then asserts which + * button Enter would activate. + */ +function content(html: string): HTMLElement { + const el = document.createElement("div"); + el.innerHTML = html; + return el; +} + +describe("resolveDialogDefaultAction", () => { + it("returns the AlertDialog action button", () => { + const el = content(` + + + `); + expect(resolveDialogDefaultAction(el)?.id).toBe("go"); + }); + + it("returns null when the AlertDialog action is disabled", () => { + const el = content(` + + + `); + expect(resolveDialogDefaultAction(el)).toBeNull(); + }); + + it("returns null when the AlertDialog action is aria-disabled", () => { + const el = content(` + + `); + expect(resolveDialogDefaultAction(el)).toBeNull(); + }); +}); + +describe("resolveDialogDefaultAction — generic dialog footer", () => { + it("resolves the single primary button in a generic dialog footer", () => { + const el = content(` +
+ + +
+ `); + expect(resolveDialogDefaultAction(el)?.id).toBe("del"); + }); + + it("resolves a submit button in the footer", () => { + const el = content(` +
+ + +
+ `); + expect(resolveDialogDefaultAction(el)?.id).toBe("save"); + }); + + it("prefers an explicit data-dialog-default-action marker", () => { + const el = content(` +
+ + +
+ `); + expect(resolveDialogDefaultAction(el)?.id).toBe("pick"); + }); + + it("returns null when the explicit data-dialog-default-action button is disabled", () => { + const el = content(` +
+ + + +
+ `); + expect(resolveDialogDefaultAction(el)).toBeNull(); + }); + + it("returns null when a generic footer has several primary actions (no guessing)", () => { + const el = content(` +
+ + + +
+ `); + expect(resolveDialogDefaultAction(el)).toBeNull(); + }); + + it("returns null when a second primary action is only temporarily disabled", () => { + // "Migrate & Delete" is disabled pending a selection; the resolver must + // treat the footer as ambiguous rather than firing the enabled destructive. + const el = content(` +
+ + + +
+ `); + expect(resolveDialogDefaultAction(el)).toBeNull(); + }); + + it("returns null when the only primary action is inside an aria-hidden subtree", () => { + const el = content(` +
+ + +
+ `); + expect(resolveDialogDefaultAction(el)).toBeNull(); + }); + + it("returns null when the only primary action is inside a [hidden] subtree", () => { + const el = content(` +
+ + +
+ `); + expect(resolveDialogDefaultAction(el)).toBeNull(); + }); + + it("ignores disabled primary buttons when they are the only candidate", () => { + const el = content(` +
+ + +
+ `); + expect(resolveDialogDefaultAction(el)).toBeNull(); + }); + + it("returns null when there is no footer and no action marker", () => { + const el = content(`

Just some informational content

`); + expect(resolveDialogDefaultAction(el)).toBeNull(); + }); +}); + +type KeyEventOverrides = Partial>; + +function keyEvent(currentTarget: HTMLElement, overrides: KeyEventOverrides = {}) { + const preventDefault = vi.fn(); + const event = { + key: "Enter", + shiftKey: false, + metaKey: false, + ctrlKey: false, + altKey: false, + repeat: false, + defaultPrevented: false, + currentTarget, + target: currentTarget, + nativeEvent: { isComposing: false, keyCode: 13 } as KeyboardEvent, + preventDefault, + ...overrides, + } as unknown as React.KeyboardEvent; + return { event, preventDefault }; +} + +function alertContent() { + const el = content( + ` + `, + ); + const action = el.querySelector("#action")!; + const cancel = el.querySelector("#cancel")!; + const click = vi.fn(); + action.addEventListener("click", click); + return { el, action, cancel, click }; +} + +describe("handleDialogDefaultActionKeyDown — activation and guards", () => { + it("clicks the semantic action and prevents default on plain Enter", () => { + const { el, click } = alertContent(); + const { event, preventDefault } = keyEvent(el); + handleDialogDefaultActionKeyDown(event); + expect(click).toHaveBeenCalledTimes(1); + expect(preventDefault).toHaveBeenCalledTimes(1); + }); + + it("fires the primary even when the Cancel button holds focus (Radix default)", () => { + const { el, cancel, click } = alertContent(); + const { event } = keyEvent(el, { target: cancel }); + handleDialogDefaultActionKeyDown(event); + expect(click).toHaveBeenCalledTimes(1); + }); + + it("ignores Shift+Enter so it can be used for newlines", () => { + const { el, click } = alertContent(); + const { event, preventDefault } = keyEvent(el, { shiftKey: true }); + handleDialogDefaultActionKeyDown(event); + expect(click).not.toHaveBeenCalled(); + expect(preventDefault).not.toHaveBeenCalled(); + }); + + it.each(["metaKey", "ctrlKey", "altKey"] as const)("ignores %s+Enter", (mod) => { + const { el, click } = alertContent(); + const { event } = keyEvent(el, { [mod]: true }); + handleDialogDefaultActionKeyDown(event); + expect(click).not.toHaveBeenCalled(); + }); + + it("ignores auto-repeat Enter (key held down)", () => { + const { el, click } = alertContent(); + const { event } = keyEvent(el, { repeat: true }); + handleDialogDefaultActionKeyDown(event); + expect(click).not.toHaveBeenCalled(); + }); + + it("ignores Enter during IME composition", () => { + const { el, click } = alertContent(); + const { event } = keyEvent(el, { + nativeEvent: { isComposing: true, keyCode: 13 } as KeyboardEvent, + }); + handleDialogDefaultActionKeyDown(event); + expect(click).not.toHaveBeenCalled(); + }); + + it("ignores the composition-confirming Enter reported as keyCode 229", () => { + const { el, click } = alertContent(); + const { event } = keyEvent(el, { + nativeEvent: { isComposing: false, keyCode: 229 } as KeyboardEvent, + }); + handleDialogDefaultActionKeyDown(event); + expect(click).not.toHaveBeenCalled(); + }); + + it("ignores Enter originating from a textarea", () => { + const { el, click } = alertContent(); + const textarea = document.createElement("textarea"); + const { event } = keyEvent(el, { target: textarea }); + handleDialogDefaultActionKeyDown(event); + expect(click).not.toHaveBeenCalled(); + }); + + it("ignores Enter originating from a contenteditable element", () => { + const { el, click } = alertContent(); + const div = document.createElement("div"); + div.contentEditable = "true"; + const { event } = keyEvent(el, { target: div }); + handleDialogDefaultActionKeyDown(event); + expect(click).not.toHaveBeenCalled(); + }); + + it("fires the primary when Enter comes from a plain single-line input", () => { + const { el, click } = alertContent(); + const input = document.createElement("input"); + const { event } = keyEvent(el, { target: input }); + handleDialogDefaultActionKeyDown(event); + expect(click).toHaveBeenCalledTimes(1); + }); + + it("ignores non-Enter keys", () => { + const { el, click } = alertContent(); + const { event } = keyEvent(el, { key: "a" }); + handleDialogDefaultActionKeyDown(event); + expect(click).not.toHaveBeenCalled(); + }); + + it("does nothing when the event was already handled (defaultPrevented)", () => { + const { el, click } = alertContent(); + const { event } = keyEvent(el, { defaultPrevented: true }); + handleDialogDefaultActionKeyDown(event); + expect(click).not.toHaveBeenCalled(); + }); + + it("does not prevent default when there is no resolvable action", () => { + const el = content(`

Nothing actionable here

`); + const { event, preventDefault } = keyEvent(el); + handleDialogDefaultActionKeyDown(event); + expect(preventDefault).not.toHaveBeenCalled(); + }); +}); + +describe("handleDialogDefaultActionKeyDown — focused-control handling", () => { + it("lets a focused non-cancel action button keep its own Enter behavior", () => { + const { el, click } = alertContent(); + const validate = document.createElement("button"); + validate.setAttribute("data-variant", "default"); + const { event, preventDefault } = keyEvent(el, { target: validate }); + handleDialogDefaultActionKeyDown(event); + expect(click).not.toHaveBeenCalled(); + expect(preventDefault).not.toHaveBeenCalled(); + }); + + it("lets a focused outline/secondary action button (e.g. Copy, Back) keep Enter", () => { + const { el, click } = alertContent(); + const copy = document.createElement("button"); + copy.setAttribute("data-variant", "outline"); // NOT a slot-marked cancel + const { event } = keyEvent(el, { target: copy }); + handleDialogDefaultActionKeyDown(event); + expect(click).not.toHaveBeenCalled(); + }); + + it("lets a focused