From d71ea605988701ab3f03879f5db08d0a00eb8043 Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 26 Oct 2026 20:45:19 -0400 Subject: [PATCH] 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 --- .../profile/ProfileFormModal.delete.test.ts | 37 +- .../profile/ProfileFormModal.render.test.tsx | 323 ++++++++++++++++++ src/components/profile/ProfileFormModal.tsx | 74 +++- src/components/profile/ProfileSwitcher.tsx | 18 +- .../profile/ProfileSwitcher.wiring.test.ts | 60 +++- .../shared/UpsellDialog.render.test.tsx | 104 +++++- src/components/shared/UpsellDialog.tsx | 20 +- .../transactions/TransactionTable.tsx | 10 +- .../TransactionTable.wiring.test.ts | 43 ++- src/hooks/useDialogFocus.test.ts | 247 ++++++++++++++ src/hooks/useDialogFocus.ts | 74 ++++ 11 files changed, 989 insertions(+), 21 deletions(-) create mode 100644 src/components/profile/ProfileFormModal.render.test.tsx create mode 100644 src/hooks/useDialogFocus.test.ts create mode 100644 src/hooks/useDialogFocus.ts diff --git a/src/components/profile/ProfileFormModal.delete.test.ts b/src/components/profile/ProfileFormModal.delete.test.ts index d286ea5..ecfd02f 100644 --- a/src/components/profile/ProfileFormModal.delete.test.ts +++ b/src/components/profile/ProfileFormModal.delete.test.ts @@ -1,10 +1,15 @@ -// ProfileFormModal — deleting a secondary profile waits for the confirmation (#421). +// ProfileFormModal — deleting a secondary profile waits for the confirmation (#421), then +// puts the focus on « Create » (#494). // // Before #421 the dialog plugin's async `window.confirm` returned a Promise, always truthy: // the profile and its database were deleted before the user answered, and "Cancel" stopped // nothing. The modal runs as a plain function under the shared hook harness (#409); the test // clicks the delete button of the secondary profile through its props, the confirmation -// answered by a mocked `confirmAction`. +// answered by a mocked `confirmAction`. The deleted row takes its delete button, which had +// the focus, with it: the handler puts the focus on « Create », whose ref gets a fake element +// through its `props.ref` (React 19 keeps `ref` in the props), as React would attach it. In the +// app, `deleteProfile` also unmounts the window today (App shows its loading screen while the +// profiles reload), and React empties that ref first. import { describe, it, expect, vi, beforeEach } from "vitest"; vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig())); @@ -33,16 +38,22 @@ vi.mock("../../contexts/ProfileContext", () => ({ import { Trash2 } from "lucide-react"; import { hookHarness } from "../../test/hookHarness"; -import { holding, type TreeProps } from "../../test/elementTree"; +import { find, holding, texts, type TreeProps } from "../../test/elementTree"; import ProfileFormModal from "./ProfileFormModal"; const harness = hookHarness(); type Props = TreeProps & { onClick?: () => Promise }; +/** The element the ref of « Create » holds: a focus spy. */ +const create = { focus: vi.fn() }; + /** Clicks the only delete button, the secondary profile's, and waits for its handler. */ async function clickDelete() { const tree = harness.render(() => ProfileFormModal({ onClose: vi.fn() })); + const creates = find(tree, (el) => el.type === "button" && texts(el).includes("t(profile.create)")); + expect(creates).toHaveLength(1); + (creates[0].props.ref as { current: unknown }).current = create; const buttons = holding(tree, Trash2); expect(buttons).toHaveLength(1); await buttons[0].props.onClick?.(); @@ -52,6 +63,7 @@ beforeEach(() => { harness.clear(); mocks.confirmAction.mockReset(); mocks.deleteProfile.mockClear(); + create.focus.mockReset(); }); describe("ProfileFormModal deletion (#421)", () => { @@ -72,3 +84,22 @@ describe("ProfileFormModal deletion (#421)", () => { expect(mocks.deleteProfile).toHaveBeenCalledWith("second"); }); }); + +describe("ProfileFormModal deletion — focus (#494)", () => { + it("puts the focus on « Create » once the profile is deleted, not before", async () => { + mocks.confirmAction.mockResolvedValue(true); + + await clickDelete(); + + expect(create.focus).toHaveBeenCalledTimes(1); + expect(mocks.deleteProfile.mock.invocationCallOrder[0]).toBeLessThan(create.focus.mock.invocationCallOrder[0]); + }); + + it("leaves the focus alone when the confirmation is refused: the row and its button stay", async () => { + mocks.confirmAction.mockResolvedValue(false); + + await clickDelete(); + + expect(create.focus).not.toHaveBeenCalled(); + }); +}); diff --git a/src/components/profile/ProfileFormModal.render.test.tsx b/src/components/profile/ProfileFormModal.render.test.tsx new file mode 100644 index 0000000..d7ab8c8 --- /dev/null +++ b/src/components/profile/ProfileFormModal.render.test.tsx @@ -0,0 +1,323 @@ +// ProfileFormModal — a named modal dialog, closed on Escape except while a save +// runs, whose focus goes to its X at the opening and follows its mode (#494). +// +// No jsdom: react-dom/server renders the markup in vitest's node environment. +// React's hooks come from the shared harness (src/test/hookHarness.ts, #409): +// the window runs as a plain function inside `harness.render`, the test clicks +// through the props of the rendered tree, renders again to read the new mode, +// and `commit()` runs the effects against a stubbed `document` (the node +// environment has none). The fake elements of the X, of « Create » and of the +// dialog element reach their refs through `props.ref` (React 19 keeps `ref` in +// the props), as React would attach them, never through a preset slot of the +// harness: a shared hook moves the slots. The harness never detaches a ref, +// so the fake of « Create » stays in its ref while the list is not rendered. +// UpsellGate stays an element, never called. +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { renderToStaticMarkup } from "react-dom/server"; +import type { KeyboardEvent as ReactKeyboardEvent, ReactNode, RefObject } from "react"; + +vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig())); +vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); + +const ctx = vi.hoisted(() => ({ + /** What `useEntitlement("multi-profile")` returns: Base by default, creation open. */ + gate: { allowed: true, ready: true }, + createProfile: vi.fn<(name: string, color: string, pin?: string) => Promise>(), + updateProfile: vi.fn<(id: string, updates: unknown) => Promise>(), +})); +vi.mock("../../services/confirmService", () => ({ confirmAction: vi.fn() })); +vi.mock("../../hooks/useEntitlement", () => ({ useEntitlement: () => ctx.gate })); +vi.mock("../../contexts/ProfileContext", () => ({ + useProfile: () => ({ + profiles: [ + { id: "default", name: "Principal", color: "#4A90A4", pin_hash: null, db_filename: "simpl_resultat.db", created_at: "" }, + { id: "second", name: "Second", color: "#C17767", pin_hash: null, db_filename: "profile_second.db", created_at: "" }, + ], + createProfile: ctx.createProfile, + updateProfile: ctx.updateProfile, + deleteProfile: vi.fn(), + setPin: vi.fn(), + }), +})); + +import { hookHarness } from "../../test/hookHarness"; +import { find, texts, type TreeElement } from "../../test/elementTree"; +import ProfileFormModal, { PROFILE_FORM_TITLE_ID } from "./ProfileFormModal"; +import UpsellGate from "../shared/UpsellGate"; + +const harness = hookHarness(); + +interface FakeElement { + focus: ReturnType; + isConnected: boolean; +} +const element = (): FakeElement => ({ focus: vi.fn(), isConnected: true }); + +type KeyListener = (e: Pick) => void; +const doc = { + activeElement: null as FakeElement | null, + body: element(), + addEventListener: vi.fn<(type: string, listener: KeyListener) => void>(), + removeEventListener: vi.fn<(type: string, listener: KeyListener) => void>(), +}; + +/** The buttons whose text is the marked `key`, in tree order. */ +const buttonsSaying = (tree: ReactNode, key: string) => + find(tree, (el) => el.type === "button" && texts(el).includes(`t(${key})`)); +const closeButtons = (tree: ReactNode) => + find(tree, (el) => el.type === "button" && el.props["aria-label"] === "t(common.close)"); +const dialogElements = (tree: ReactNode) => find(tree, (el) => el.props.role === "dialog"); + +/** Calls the click handler of the one button of `buttons`, and returns what it returns. */ +function click(buttons: TreeElement[]): unknown { + expect(buttons).toHaveLength(1); + return (buttons[0].props.onClick as () => unknown)(); +} + +const setRef = (el: TreeElement, fake: unknown) => { + (el.props.ref as { current: unknown }).current = fake; +}; + +beforeEach(() => { + harness.clear(); + ctx.gate = { allowed: true, ready: true }; + ctx.createProfile.mockReset(); + ctx.updateProfile.mockReset(); + ctx.createProfile.mockResolvedValue(undefined); + ctx.updateProfile.mockResolvedValue(undefined); + doc.activeElement = null; + doc.addEventListener.mockReset(); + doc.removeEventListener.mockReset(); + vi.stubGlobal("document", doc); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("ProfileFormModal — a named modal dialog (#494)", () => { + it("is a modal dialog named by its title, with a Close button", () => { + vi.unstubAllGlobals(); // the static render runs no effect, and needs no document + const html = renderToStaticMarkup(); + expect(html).toContain('role="dialog"'); + expect(html).toContain('aria-modal="true"'); + expect(html).toContain(`aria-labelledby="${PROFILE_FORM_TITLE_ID}"`); + expect(html).toMatch(new RegExp(`

]*>t\\(profile\\.manageProfiles\\)

`)); + expect(html).toContain(' @@ -164,6 +227,7 @@ export default function ProfileFormModal({ onClose, editProfileId }: Props) { ))}