fix(ui): no button drops the keyboard focus when its own action disables it
A focused button that turns natively disabled loses the focus to <body> in Chrome. The app disables the very button that was pressed on ~60 sites — a mutation pending, a pager at its last page, undo with nothing left, a player at the end of its queue, a form gone clean — so a keyboard user was thrown out of the page on every such press. One primitive instead of a fix per site: ui/FocusSafeButton renders a focused-and-disabled (or busy) button as aria-disabled with a click guard, and applies the native attribute again once the focus is elsewhere. It asks the document at render time as well as listening for focus events, because a window without focus fires none (measured). ui/Button and ui/form's Switch are built on it; 57 hand-rolled buttons swapped their tag for it keeping their classes, and three hand-copies of the rule (the channel page's Block and Hide, ChannelDiscovery's Subscribe) now pass `busy`. The soft state's dim look is one rule in index.css. `local/focus-safe-disabled` refuses a new raw <button disabled>, pinned by focusSafe.contract.test.ts. lib/plexDetailUi moved to components/: it is components, and lib may not import the primitive. Measured on localdev in Chrome: the audit log's Next button keeps the focus on reaching the last page, reads aria-disabled, and the guarded click does nothing.
This commit is contained in:
@@ -5,7 +5,7 @@
|
||||
// dropped), the loading state (disabled + spinner + aria-busy), and the type="button" default that
|
||||
// stops an action button from submitting a surrounding form.
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, screen, cleanup, fireEvent } from "@testing-library/react";
|
||||
import { act, render, screen, cleanup, fireEvent } from "@testing-library/react";
|
||||
import { Button } from "./Button";
|
||||
|
||||
afterEach(cleanup);
|
||||
@@ -153,6 +153,54 @@ describe("Button primitive (S5)", () => {
|
||||
// so weakening the union turns the whole typecheck lane red.
|
||||
//
|
||||
// Rendered, not just declared, so eslint sees them used and the file stays one test suite.
|
||||
describe("Button · disabled while it holds the focus", () => {
|
||||
// A focused button that turns natively disabled loses the focus to <body> in Chrome (measured, E11
|
||||
// S2) — and ~60 call sites disable the very button that was just pressed while its mutation runs.
|
||||
// jsdom does not move the focus, so the CONTRACT is what is pinned: while focused, the button is
|
||||
// unavailable by aria-disabled + a click guard, never by the native attribute.
|
||||
it("keeps the native attribute off while focused, and blocks activation", () => {
|
||||
const onClick = vi.fn();
|
||||
const { rerender } = render(<Button onClick={onClick}>Save</Button>);
|
||||
const btn = screen.getByRole("button", { name: "Save" });
|
||||
act(() => btn.focus());
|
||||
rerender(
|
||||
<Button onClick={onClick} disabled>
|
||||
Save
|
||||
</Button>,
|
||||
);
|
||||
expect(btn.hasAttribute("disabled")).toBe(false);
|
||||
expect(btn.getAttribute("aria-disabled")).toBe("true");
|
||||
fireEvent.click(btn);
|
||||
expect(onClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("also holds when the window has no focus and no focus event ever fired", () => {
|
||||
// Chrome, with another app in front: `.focus()` moves activeElement and fires nothing. The
|
||||
// button asks the document at render time, so it does not rely on the event (measured).
|
||||
const { rerender } = render(<Button onClick={() => {}}>Next</Button>);
|
||||
const btn = screen.getByRole("button", { name: "Next" });
|
||||
const active = vi.spyOn(document, "activeElement", "get").mockReturnValue(btn);
|
||||
rerender(
|
||||
<Button onClick={() => {}} disabled>
|
||||
Next
|
||||
</Button>,
|
||||
);
|
||||
expect(btn.hasAttribute("disabled")).toBe(false);
|
||||
expect(btn.getAttribute("aria-disabled")).toBe("true");
|
||||
active.mockRestore();
|
||||
});
|
||||
|
||||
it("is natively disabled again once the focus is elsewhere", () => {
|
||||
render(
|
||||
<Button onClick={() => {}} disabled>
|
||||
Save
|
||||
</Button>,
|
||||
);
|
||||
const btn = screen.getByRole("button", { name: "Save" });
|
||||
expect(btn.hasAttribute("disabled")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Button accessible-name contract (type level)", () => {
|
||||
it("rejects a text-less button with no name, and accepts every named spelling", () => {
|
||||
render(
|
||||
|
||||
@@ -2,6 +2,7 @@ import { forwardRef } from "react";
|
||||
import type { ButtonHTMLAttributes, ReactNode, RefAttributes } from "react";
|
||||
import clsx from "clsx";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { FocusSafeButton } from "./FocusSafeButton";
|
||||
|
||||
// The ONE action-button primitive. Before this there were 385 raw <button>s styling themselves with
|
||||
// ad-hoc utility strings over the CSS paint-recipes (.btn-primary/.btn-danger, index.css) + the btnCls
|
||||
@@ -142,10 +143,14 @@ const ButtonImpl = forwardRef<HTMLButtonElement, ButtonOwnProps>(function Button
|
||||
disabled,
|
||||
type,
|
||||
onClick,
|
||||
onFocus,
|
||||
onBlur,
|
||||
...rest
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
// Unavailable while busy (`loading`) or disabled — without dropping a focused button's focus:
|
||||
// see FocusSafeButton, which owns that rule for every button in the app.
|
||||
// A link must not inherit the action-button padding/radius, so its size default differs. Resolved
|
||||
// here rather than by asking every call site to pass `size="none"` alongside `variant="link"` —
|
||||
// a pairing everyone would eventually forget, which is how a "link" grows a button's box.
|
||||
@@ -157,26 +162,14 @@ const ButtonImpl = forwardRef<HTMLButtonElement, ButtonOwnProps>(function Button
|
||||
const touchTarget = variant !== "link";
|
||||
const leading = loading ? <Loader2 className="w-4 h-4 animate-spin" /> : icon;
|
||||
return (
|
||||
<button
|
||||
<FocusSafeButton
|
||||
ref={ref}
|
||||
type={type ?? "button"}
|
||||
// `loading` blocks activation WITHOUT native `disabled`. A focused button that turns disabled
|
||||
// loses the focus: Chrome moved it to <body> ~60 ms after the reroll click on Home and nothing
|
||||
// handed it back when the button re-enabled (measured, E11 S2) — so a keyboard user was dropped
|
||||
// out of the page on every press. `aria-disabled` keeps the button focusable and announced as
|
||||
// unavailable; the click guard is what actually stops the double-submit, whatever `disabled`
|
||||
// says, and its preventDefault also cancels a form's implicit submission (which is a click on
|
||||
// the default button).
|
||||
disabled={disabled}
|
||||
aria-disabled={loading || undefined}
|
||||
aria-busy={loading || undefined}
|
||||
onClick={(e) => {
|
||||
if (loading) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
onClick?.(e);
|
||||
}}
|
||||
busy={loading}
|
||||
onClick={onClick}
|
||||
onFocus={onFocus}
|
||||
onBlur={onBlur}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className={clsx(
|
||||
@@ -191,7 +184,7 @@ const ButtonImpl = forwardRef<HTMLButtonElement, ButtonOwnProps>(function Button
|
||||
>
|
||||
{leading}
|
||||
{!iconOnly && children}
|
||||
</button>
|
||||
</FocusSafeButton>
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { forwardRef, useCallback, useRef, useState, type ButtonHTMLAttributes } from "react";
|
||||
|
||||
// A `<button>` whose `disabled` never throws the focus out of the page.
|
||||
//
|
||||
// A focused button that turns natively disabled loses the focus — Chrome moves it to <body>
|
||||
// (measured, E11 S2) — and the app disables the very button that was just pressed on ~60 sites (a
|
||||
// mutation pending, a form gone clean after its save), so a keyboard user was dropped out of the page
|
||||
// on every submit. While THIS button holds the focus, `disabled` (and `busy`) is expressed as
|
||||
// `aria-disabled` plus a click guard instead: still focusable, announced as unavailable, and not
|
||||
// activatable — its preventDefault also cancels a form's implicit submission, which is a click on the
|
||||
// default button. The native attribute applies again once the focus is elsewhere (at the blur; in
|
||||
// a window without focus, which fires no blur, at the next render).
|
||||
//
|
||||
// Unstyled on purpose: `ui/Button` is built on it, and a hand-rolled `<button>` swaps its tag for
|
||||
// this one keeping its classes. The dimmed look of the soft state is one rule in index.css
|
||||
// (`[data-focus-safe][aria-disabled="true"]`), since a caller's `disabled:*` utilities match only the
|
||||
// native attribute.
|
||||
export const FocusSafeButton = forwardRef<
|
||||
HTMLButtonElement,
|
||||
ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
/** Working: unavailable and announced as busy, whether focused or not. */
|
||||
busy?: boolean;
|
||||
}
|
||||
>(function FocusSafeButton({ disabled, busy = false, onClick, onFocus, onBlur, ...rest }, ref) {
|
||||
const [focusEvent, setFocusEvent] = useState(false);
|
||||
const node = useRef<HTMLButtonElement | null>(null);
|
||||
const setNode = useCallback(
|
||||
(el: HTMLButtonElement | null) => {
|
||||
node.current = el;
|
||||
if (typeof ref === "function") ref(el);
|
||||
else if (ref) ref.current = el;
|
||||
},
|
||||
[ref],
|
||||
);
|
||||
// Focused by the event OR by the document's own answer at render time: when the window itself is
|
||||
// not focused (another app in front) `.focus()` moves `activeElement` but fires no focus event
|
||||
// (measured in Chrome), and the button disabled in that state lost the focus all the same.
|
||||
const focused =
|
||||
focusEvent || (!!node.current && node.current.ownerDocument.activeElement === node.current);
|
||||
const soft = busy || (!!disabled && focused);
|
||||
return (
|
||||
<button
|
||||
ref={setNode}
|
||||
{...rest}
|
||||
data-focus-safe=""
|
||||
disabled={!!disabled && !focused}
|
||||
aria-disabled={soft || undefined}
|
||||
aria-busy={busy || undefined}
|
||||
onClick={(e) => {
|
||||
if (soft) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
onClick?.(e);
|
||||
}}
|
||||
onFocus={(e) => {
|
||||
setFocusEvent(true);
|
||||
onFocus?.(e);
|
||||
}}
|
||||
onBlur={(e) => {
|
||||
setFocusEvent(false);
|
||||
onBlur?.(e);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { hasPagerContent, pageCount } from "./pagerContent";
|
||||
import { FocusSafeButton } from "./FocusSafeButton";
|
||||
|
||||
// The Prev / page-input / Next + "N per page" cluster, lifted out of DataTable so a non-table view
|
||||
// (the channel manager's card layout) can paginate the same way. Controlled: the caller owns page +
|
||||
@@ -58,14 +59,14 @@ export default function Pager({
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
<FocusSafeButton
|
||||
onClick={() => goToPage(Math.max(0, safePage - 1))}
|
||||
disabled={safePage === 0}
|
||||
className="glass-card glass-hover flex items-center gap-1 px-3 py-1.5 rounded-lg disabled:opacity-40 transition"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
{t("datatable.pager.prev")}
|
||||
</button>
|
||||
</FocusSafeButton>
|
||||
<span className="text-muted flex items-center gap-1.5">
|
||||
{t("datatable.pager.pageLabel")}
|
||||
<input
|
||||
@@ -81,14 +82,14 @@ export default function Pager({
|
||||
/>
|
||||
{t("datatable.pager.ofTotal", { total: totalPages })}
|
||||
</span>
|
||||
<button
|
||||
<FocusSafeButton
|
||||
onClick={() => goToPage(Math.min(totalPages - 1, safePage + 1))}
|
||||
disabled={safePage >= totalPages - 1}
|
||||
className="glass-card glass-hover flex items-center gap-1 px-3 py-1.5 rounded-lg disabled:opacity-40 transition"
|
||||
>
|
||||
{t("datatable.pager.next")}
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</button>
|
||||
</FocusSafeButton>
|
||||
</div>
|
||||
)}
|
||||
{total > 0 && (
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Redo2, Undo2 } from "lucide-react";
|
||||
import { dispatch, useKeyScope } from "../../lib/keymap";
|
||||
import { FocusSafeButton } from "./FocusSafeButton";
|
||||
|
||||
// Reusable undo/redo buttons with Ctrl/Cmd+Z (undo) and Ctrl/Cmd+Y or Ctrl/Cmd+Shift+Z
|
||||
// (redo) shortcuts. Pairs with useUndoable but takes plain props, so it works with any
|
||||
@@ -47,7 +48,7 @@ export default function UndoToolbar({
|
||||
"p-1.5 rounded-lg border border-border text-muted enabled:hover:text-fg enabled:hover:border-accent disabled:opacity-30 transition";
|
||||
return (
|
||||
<div className="inline-flex items-center gap-1">
|
||||
<button
|
||||
<FocusSafeButton
|
||||
onClick={onUndo}
|
||||
disabled={!canUndo}
|
||||
title={t("common.undo")}
|
||||
@@ -55,8 +56,8 @@ export default function UndoToolbar({
|
||||
className={btn}
|
||||
>
|
||||
<Undo2 className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
</FocusSafeButton>
|
||||
<FocusSafeButton
|
||||
onClick={onRedo}
|
||||
disabled={!canRedo}
|
||||
title={t("common.redo")}
|
||||
@@ -64,7 +65,7 @@ export default function UndoToolbar({
|
||||
className={btn}
|
||||
>
|
||||
<Redo2 className="w-4 h-4" />
|
||||
</button>
|
||||
</FocusSafeButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ReactNode } from "react";
|
||||
import Tooltip from "./Tooltip";
|
||||
import { FocusSafeButton } from "./FocusSafeButton";
|
||||
|
||||
// Shared form/settings primitives, factored out of the many panels that each re-declared
|
||||
// them (Settings, Config, Stats, admin pages, Setup wizard). Visual contract unchanged.
|
||||
@@ -29,8 +30,10 @@ export function Switch({
|
||||
label?: string;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
// FocusSafeButton: a switch is disabled by its caller while the change it made is saving, and a
|
||||
// natively disabled switch that holds the focus throws it to <body>.
|
||||
return (
|
||||
<button
|
||||
<FocusSafeButton
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={checked}
|
||||
@@ -44,7 +47,7 @@ export function Switch({
|
||||
checked ? "left-4.5" : "left-0.5"
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</FocusSafeButton>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user