Simpl-Resultat/src/hooks/useDialogFocus.test.ts
le king fu d71ea60598 feat: focus of the upsell windows and ProfileFormModal as a dialog (#494)
A shared hook, useDialogFocus, gives a modal window its focus: on its X
once mounted, Tab and Shift+Tab looped inside by an onKeyDown handler on
the dialog element (never on document, where Escape is listened for),
and given back in the effect's cleanup, so on every way out: to
returnFocusTo when the host passes it and it holds an element, otherwise
to the element active at mount, unless that one is body or no longer in
the document.

- UpsellDialog: refs on its X and on the dialog element, an optional
  returnFocusTo, the Tab handler; the Escape listener is unchanged.
- ProfileSwitcher: its trigger gets a ref, passed to UpsellDialog and
  ProfileFormModal, type="button" and aria-expanded={open}, without
  aria-haspopup since the list is not a role="menu".
- TransactionTable: an effect, placed before the early return of an
  empty table, clears showSplitUpsell once the access is open, so an
  upsell that went away with the edition never comes back on its own.
- ProfileFormModal: role="dialog", aria-modal, aria-labelledby to its
  title (static id), aria-label and type="button" on its X, Escape that
  closes like the X except while saving, the same focus hook; entering
  the upsell puts the focus on the X, every return to the list (cancel,
  save, deletion) on "Create", never at mount.

Tests: useDialogFocus.test.ts and ProfileFormModal.render.test.tsx are
new; UpsellDialog, ProfileSwitcher, TransactionTable and the deletion
of ProfileFormModal get their cases. Fakes reach the refs through
props.ref, never through a preset slot of the harness.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 20:45:19 -04:00

247 lines
9.4 KiB
TypeScript

// useDialogFocus — the focus of a modal window (#494).
//
// No jsdom: React's hooks come from the shared harness (src/test/hookHarness.ts,
// #409), the hook runs as a plain function inside `harness.render`, `commit()`
// runs its effect and `unmount()` its cleanup. The DOM is faked: `document` is a
// stub (`vi.stubGlobal`) whose `activeElement` and `body` the test sets, the
// elements are objects with a `focus` spy and an `isConnected` flag, and the
// dialog's `querySelectorAll` returns the elements the test lists. The refs are
// plain `{ current }` objects: the hook is called directly, not through the
// tree of a component (UpsellDialog.render.test.tsx and
// ProfileFormModal.render.test.tsx prove that wiring through `props.ref`).
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { KeyboardEvent as ReactKeyboardEvent, RefObject } from "react";
vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
import { hookHarness } from "../test/hookHarness";
import { FOCUSABLE_SELECTOR, useDialogFocus } from "./useDialogFocus";
const harness = hookHarness();
interface FakeElement {
focus: ReturnType<typeof vi.fn>;
isConnected: boolean;
}
/** An element of the fake DOM: a focus spy, in the document unless told otherwise. */
const element = (isConnected = true): FakeElement => ({ focus: vi.fn(), isConnected });
const doc: { activeElement: FakeElement | null; body: FakeElement } = { activeElement: null, body: element() };
/** A ref holding a fake element, typed as the hook takes it. */
const refTo = (current: FakeElement | object | null) => ({ current }) as unknown as RefObject<HTMLElement | null>;
/** The dialog element: `querySelectorAll` returns `items`, the focusable elements in DOM order. */
function dialogOf(items: FakeElement[]) {
return { querySelectorAll: vi.fn((_selector: string) => items) };
}
/** A keydown on `target`, with the spy React's `preventDefault` stands for. */
function keydown(key: string, target: FakeElement, shiftKey = false) {
const preventDefault = vi.fn();
const event = { key, shiftKey, target, preventDefault } as unknown as ReactKeyboardEvent<HTMLElement>;
return { event, preventDefault };
}
beforeEach(() => {
harness.clear();
doc.activeElement = null;
doc.body = element();
vi.stubGlobal("document", doc);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("useDialogFocus — focus at the opening (#494)", () => {
it("puts the focus on the initial element once mounted, not during the render", () => {
const close = element();
harness.render(() => useDialogFocus({ dialog: refTo(null), initialFocus: refTo(close) }));
expect(close.focus).not.toHaveBeenCalled();
harness.commit();
expect(close.focus).toHaveBeenCalledTimes(1);
});
it("does it once: a later render with the same refs leaves the focus where it is", () => {
const close = element();
const refs = { dialog: refTo(null), initialFocus: refTo(close) };
harness.render(() => useDialogFocus(refs));
harness.commit();
harness.render(() => useDialogFocus(refs));
harness.commit();
expect(close.focus).toHaveBeenCalledTimes(1);
});
it("an empty initial ref focuses nothing and does not throw", () => {
harness.render(() => useDialogFocus({ dialog: refTo(null), initialFocus: refTo(null) }));
expect(() => harness.commit()).not.toThrow();
});
});
describe("useDialogFocus — focus given back when the dialog goes away (#494)", () => {
/** Mounts the hook with the opener active, then unmounts it. */
function openThenClose(opener: FakeElement | null, returnFocusTo?: RefObject<HTMLElement | null>) {
doc.activeElement = opener;
harness.render(() => useDialogFocus({ dialog: refTo(null), initialFocus: refTo(element()), returnFocusTo }));
harness.commit();
}
it("gives it back to the element active at the opening, on unmount only", () => {
const opener = element();
openThenClose(opener);
expect(opener.focus).not.toHaveBeenCalled();
harness.unmount();
expect(opener.focus).toHaveBeenCalledTimes(1);
});
it("returnFocusTo wins over the element active at the opening", () => {
const opener = element();
const trigger = element();
openThenClose(opener, refTo(trigger));
harness.unmount();
expect(trigger.focus).toHaveBeenCalledTimes(1);
expect(opener.focus).not.toHaveBeenCalled();
});
it("an empty returnFocusTo leaves the element active at the opening", () => {
const opener = element();
openThenClose(opener, refTo(null));
harness.unmount();
expect(opener.focus).toHaveBeenCalledTimes(1);
});
it("never gives it to body", () => {
openThenClose(doc.body);
harness.unmount();
expect(doc.body.focus).not.toHaveBeenCalled();
});
it("never to an element no longer in the document", () => {
const opener = element();
openThenClose(opener);
// The opener is unmounted along with the dialog (a navigation, a row that goes away).
opener.isConnected = false;
harness.unmount();
expect(opener.focus).not.toHaveBeenCalled();
});
it("with nothing active at the opening, gives the focus to nothing", () => {
openThenClose(null);
expect(() => harness.unmount()).not.toThrow();
});
it("StrictMode's double run at mount ends with the focus on the initial element, the opener still remembered", () => {
const opener = element();
const close = element();
doc.activeElement = opener;
harness.render(() => useDialogFocus({ dialog: refTo(null), initialFocus: refTo(close) }));
harness.commit();
harness.replayEffects();
const calls = (spy: FakeElement) => spy.focus.mock.invocationCallOrder;
expect(calls(close)).toHaveLength(2);
expect(calls(opener)).toHaveLength(1);
// The X, the opener (the simulated unmount), then the X again.
expect(calls(close)[0]).toBeLessThan(calls(opener)[0]);
expect(calls(opener)[0]).toBeLessThan(calls(close)[1]);
harness.unmount();
expect(opener.focus).toHaveBeenCalledTimes(2);
});
});
describe("useDialogFocus — Tab stays inside the dialog (#494)", () => {
const first = element();
const middle = element();
const last = element();
beforeEach(() => {
for (const el of [first, middle, last]) el.focus.mockReset();
});
/** The keydown handler of a mounted dialog whose focusable elements are `items`. */
function handler(items: FakeElement[] = [first, middle, last]) {
const dialog = dialogOf(items);
const { onKeyDown } = harness.render(() =>
useDialogFocus({ dialog: refTo(dialog), initialFocus: refTo(null) }),
);
return { onKeyDown, dialog };
}
it("Tab on the last element goes to the first, instead of leaving the dialog", () => {
const { onKeyDown, dialog } = handler();
const { event, preventDefault } = keydown("Tab", last);
onKeyDown(event);
expect(dialog.querySelectorAll).toHaveBeenCalledWith(FOCUSABLE_SELECTOR);
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(first.focus).toHaveBeenCalledTimes(1);
expect(last.focus).not.toHaveBeenCalled();
});
it("Shift+Tab on the first element goes to the last", () => {
const { onKeyDown } = handler();
const { event, preventDefault } = keydown("Tab", first, true);
onKeyDown(event);
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(last.focus).toHaveBeenCalledTimes(1);
expect(first.focus).not.toHaveBeenCalled();
});
it("anywhere else, Tab and Shift+Tab are left to the browser", () => {
const { onKeyDown } = handler();
for (const [target, shift] of [
[middle, false],
[middle, true],
[first, false],
[last, true],
] as const) {
const { event, preventDefault } = keydown("Tab", target, shift);
onKeyDown(event);
expect(preventDefault).not.toHaveBeenCalled();
}
for (const el of [first, middle, last]) expect(el.focus).not.toHaveBeenCalled();
});
it("another key does nothing, even on the last element", () => {
const { onKeyDown, dialog } = handler();
for (const key of ["Enter", "Escape", " ", "ArrowDown", "a"]) {
const { event, preventDefault } = keydown(key, last);
onKeyDown(event);
expect(preventDefault).not.toHaveBeenCalled();
}
expect(dialog.querySelectorAll).not.toHaveBeenCalled();
expect(first.focus).not.toHaveBeenCalled();
});
it("one focusable element only: Tab and Shift+Tab keep the focus on it", () => {
const { onKeyDown } = handler([middle]);
onKeyDown(keydown("Tab", middle).event);
onKeyDown(keydown("Tab", middle, true).event);
expect(middle.focus).toHaveBeenCalledTimes(2);
});
it("no focusable element, or no dialog element: Tab is left to the browser, without an error", () => {
const { onKeyDown } = handler([]);
const empty = keydown("Tab", last);
onKeyDown(empty.event);
expect(empty.preventDefault).not.toHaveBeenCalled();
harness.clear();
const { onKeyDown: unmounted } = harness.render(() =>
useDialogFocus({ dialog: refTo(null), initialFocus: refTo(null) }),
);
const none = keydown("Tab", last);
expect(() => unmounted(none.event)).not.toThrow();
expect(none.preventDefault).not.toHaveBeenCalled();
});
it("counts what the issue lists as focusable, and leaves out what is disabled", () => {
expect(FOCUSABLE_SELECTOR.split(", ")).toEqual([
"button:not([disabled])",
"[href]",
"input:not([disabled])",
"select",
"textarea",
'[tabindex]:not([tabindex="-1"])',
]);
});
});