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>
This commit is contained in:
le king fu 2026-10-26 20:45:19 -04:00
commit d71ea60598
11 changed files with 989 additions and 21 deletions

View file

@ -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<void> };
/** 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<Props>(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();
});
});

View file

@ -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<void>>(),
updateProfile: vi.fn<(id: string, updates: unknown) => Promise<void>>(),
}));
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<typeof vi.fn>;
isConnected: boolean;
}
const element = (): FakeElement => ({ focus: vi.fn(), isConnected: true });
type KeyListener = (e: Pick<KeyboardEvent, "key">) => 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(<ProfileFormModal onClose={vi.fn()} />);
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(`<h2 id="${PROFILE_FORM_TITLE_ID}"[^>]*>t\\(profile\\.manageProfiles\\)</h2>`));
expect(html).toContain('<button type="button" aria-label="t(common.close)"');
});
it("keeps its role, its name and its X in every mode, the title following the mode", () => {
const seen: Array<[string, string[]]> = [];
const read = (tree: ReactNode) => {
const [dialog] = dialogElements(tree);
expect(dialog.props).toMatchObject({ "aria-modal": "true", "aria-labelledby": PROFILE_FORM_TITLE_ID });
const titles = find(tree, (el) => el.type === "h2");
expect(titles).toHaveLength(1);
expect(titles[0].props.id).toBe(PROFILE_FORM_TITLE_ID);
const [x] = closeButtons(tree);
expect(x.props.type).toBe("button");
return texts(titles[0]);
};
const list = harness.render(() => ProfileFormModal({ onClose: vi.fn() }));
seen.push(["list", read(list)]);
click(buttonsSaying(list, "common.edit").slice(1));
const edit = harness.render(() => ProfileFormModal({ onClose: vi.fn() }));
seen.push(["edit", read(edit)]);
click(buttonsSaying(edit, "common.cancel"));
ctx.gate = { allowed: false, ready: true };
click(buttonsSaying(harness.render(() => ProfileFormModal({ onClose: vi.fn() })), "profile.create"));
const upsell = harness.render(() => ProfileFormModal({ onClose: vi.fn() }));
expect(find(upsell, (el) => el.type === UpsellGate)).toHaveLength(1);
seen.push(["upsell", read(upsell)]);
expect(seen).toEqual([
["list", ["t(profile.manageProfiles)"]],
["edit", ["t(profile.edit)"]],
["upsell", ["t(profile.create)"]],
]);
});
});
describe("ProfileFormModal — Escape (#494)", () => {
/** The keydown listener the window added last. */
function latestListener(): KeyListener {
const added = doc.addEventListener.mock.calls.filter(([type]) => type === "keydown");
expect(added.length).toBeGreaterThan(0);
return added[added.length - 1][1];
}
/** One render of the mounted window, then its effects. */
function renderAndCommit(onClose: () => void) {
const tree = harness.render(() => ProfileFormModal({ onClose }));
harness.commit();
return tree;
}
it("Escape closes it, like its X", () => {
const onClose = vi.fn();
const tree = renderAndCommit(onClose);
latestListener()({ key: "Escape" });
expect(onClose).toHaveBeenCalledTimes(1);
click(closeButtons(tree));
expect(onClose).toHaveBeenCalledTimes(2);
});
it("another key leaves it open", () => {
const onClose = vi.fn();
renderAndCommit(onClose);
const listener = latestListener();
for (const key of ["Enter", " ", "Tab", "a"]) listener({ key });
expect(onClose).not.toHaveBeenCalled();
});
it("Escape does nothing while a save runs, and closes it again once the save is over", async () => {
let finish: (() => void) | undefined;
ctx.updateProfile.mockImplementation(
() =>
new Promise<void>((resolve) => {
finish = () => resolve();
}),
);
const onClose = vi.fn();
const list = renderAndCommit(onClose);
click(buttonsSaying(list, "common.edit").slice(1));
const edit = renderAndCommit(onClose);
const saving = click(buttonsSaying(edit, "common.save")) as Promise<void>;
renderAndCommit(onClose);
latestListener()({ key: "Escape" });
expect(onClose).not.toHaveBeenCalled();
expect(finish).toBeDefined();
finish?.();
await saving;
renderAndCommit(onClose);
latestListener()({ key: "Escape" });
expect(onClose).toHaveBeenCalledTimes(1);
});
it("removes its listener when it goes away", () => {
renderAndCommit(vi.fn());
const listener = latestListener();
harness.unmount();
expect(doc.removeEventListener).toHaveBeenCalledWith("keydown", listener);
});
});
describe("ProfileFormModal — focus (#494)", () => {
const close = element();
const create = element();
beforeEach(() => {
close.focus.mockReset();
create.focus.mockReset();
});
/**
* One render of the mounted window: hands the refs of the X and of
* « Create », when they are in the tree, their fakes, then runs the effects.
*/
function show(options: { returnFocusTo?: RefObject<HTMLElement | null>; dialog?: object } = {}) {
const tree = harness.render(() => ProfileFormModal({ onClose: vi.fn(), returnFocusTo: options.returnFocusTo }));
for (const x of closeButtons(tree)) setRef(x, close);
for (const button of buttonsSaying(tree, "profile.create")) setRef(button, create);
if (options.dialog) setRef(dialogElements(tree)[0], options.dialog);
harness.commit();
return tree;
}
it("puts the focus on its X once mounted, never on « Create »", () => {
show();
expect(close.focus).toHaveBeenCalledTimes(1);
expect(create.focus).not.toHaveBeenCalled();
});
it("StrictMode's second run at mount leaves it on the X", () => {
show();
harness.replayEffects();
expect(create.focus).not.toHaveBeenCalled();
expect(close.focus).toHaveBeenCalledTimes(2);
});
it("entering the upsell puts it on the X, and Cancel back on « Create »", () => {
ctx.gate = { allowed: false, ready: true };
const list = show();
expect(close.focus).toHaveBeenCalledTimes(1);
click(buttonsSaying(list, "profile.create"));
const upsell = show();
expect(find(upsell, (el) => el.type === UpsellGate)).toHaveLength(1);
expect(close.focus).toHaveBeenCalledTimes(2);
expect(create.focus).not.toHaveBeenCalled();
click(buttonsSaying(upsell, "common.cancel"));
show();
expect(create.focus).toHaveBeenCalledTimes(1);
expect(close.focus).toHaveBeenCalledTimes(2);
});
it("the create and edit forms keep the autoFocus of their name field, and Cancel brings the focus back on « Create »", () => {
for (const [mode, enter] of [
["create", (tree: ReactNode) => buttonsSaying(tree, "profile.create")],
["edit", (tree: ReactNode) => buttonsSaying(tree, "common.edit").slice(1)],
] as const) {
harness.clear();
close.focus.mockReset();
create.focus.mockReset();
click(enter(show()));
const form = show();
const names = find(form, (el) => el.type === "input" && el.props.type === "text");
expect(names, mode).toHaveLength(1);
expect(names[0].props.autoFocus, mode).toBe(true);
expect(close.focus, mode).toHaveBeenCalledTimes(1); // the mount only
expect(create.focus, mode).not.toHaveBeenCalled();
click(buttonsSaying(form, "common.cancel"));
show();
expect(create.focus, mode).toHaveBeenCalledTimes(1);
}
});
it("a save brings the focus back on « Create »", async () => {
for (const mode of ["edit", "create"] as const) {
harness.clear();
create.focus.mockReset();
const list = show();
if (mode === "edit") {
click(buttonsSaying(list, "common.edit").slice(1));
} else {
click(buttonsSaying(list, "profile.create"));
const [name] = find(show(), (el) => el.type === "input" && el.props.type === "text");
(name.props.onChange as (e: { target: { value: string } }) => void)({ target: { value: "Vacances" } });
}
const form = show();
expect(create.focus, mode).not.toHaveBeenCalled();
await click(buttonsSaying(form, "common.save"));
show();
expect(create.focus, mode).toHaveBeenCalledTimes(1);
}
expect(ctx.updateProfile).toHaveBeenCalledWith("second", { name: "Second", color: "#C17767" });
expect(ctx.createProfile).toHaveBeenCalledWith("Vacances", expect.any(String), undefined);
});
it("gives the focus back to returnFocusTo when it goes away, else to the element active at the opening", () => {
const opener = element();
const trigger = element();
doc.activeElement = opener;
show({ returnFocusTo: { current: trigger } as unknown as RefObject<HTMLElement | null> });
harness.unmount();
expect(trigger.focus).toHaveBeenCalledTimes(1);
expect(opener.focus).not.toHaveBeenCalled();
harness.clear();
show();
harness.unmount();
expect(opener.focus).toHaveBeenCalledTimes(1);
});
it("Tab on « Create », its last button, goes back to the X, through the handler of the dialog element", () => {
const pin = element();
const tree = show({ dialog: { querySelectorAll: () => [close, pin, create] } });
close.focus.mockReset();
const preventDefault = vi.fn();
const onKeyDown = dialogElements(tree)[0].props.onKeyDown as (event: ReactKeyboardEvent<HTMLElement>) => void;
onKeyDown({ key: "Tab", shiftKey: false, target: create, preventDefault } as unknown as ReactKeyboardEvent<HTMLElement>);
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(close.focus).toHaveBeenCalledTimes(1);
});
});

View file

@ -1,8 +1,9 @@
import { useState } from "react";
import { useEffect, useRef, useState, type RefObject } from "react";
import { useTranslation } from "react-i18next";
import { X, Trash2, Lock, LockOpen, Plus } from "lucide-react";
import { useProfile } from "../../contexts/ProfileContext";
import { useEntitlement } from "../../hooks/useEntitlement";
import { useDialogFocus } from "../../hooks/useDialogFocus";
import { requiredTierFor } from "../../shared/entitlements";
import { isProfileCreationLocked } from "../../shared/profileGate";
import { confirmAction } from "../../services/confirmService";
@ -13,12 +14,26 @@ const PRESET_COLORS = [
"#ec4899", "#06b6d4", "#f97316", "#6366f1", "#14b8a6",
];
/**
* The id of the window's title, its accessible name (#494). A static id: two
* instances never coexist, ProfileSelectionPage rendering only without an
* active profile (as in StarterAccountsModal); a generated id would make the
* hook harness of the tests throw.
*/
export const PROFILE_FORM_TITLE_ID = "profile-form-title";
interface Props {
onClose: () => void;
editProfileId?: string;
/**
* Where the focus goes back when the window closes, when the button that
* opened it is gone by then: ProfileSwitcher passes its trigger (#494).
* Without it, the focus goes back to the element active at the opening.
*/
returnFocusTo?: RefObject<HTMLElement | null>;
}
export default function ProfileFormModal({ onClose, editProfileId }: Props) {
export default function ProfileFormModal({ onClose, editProfileId, returnFocusTo }: Props) {
const { t } = useTranslation();
const { profiles, createProfile, updateProfile, deleteProfile, setPin } = useProfile();
// Multi-profile gate (Base+, #300) — this modal is the SINGLE creation
@ -41,6 +56,36 @@ export default function ProfileFormModal({ onClose, editProfileId }: Props) {
const [color, setColor] = useState(editProfile?.color ?? PRESET_COLORS[0]);
const [pin, setPin_] = useState("");
const [saving, setSaving] = useState(false);
const dialogRef = useRef<HTMLDivElement>(null);
const closeRef = useRef<HTMLButtonElement>(null);
const createRef = useRef<HTMLButtonElement>(null);
// Focus (#494): on the X once mounted, in every mode; Tab and Shift+Tab kept
// inside; given back when the window goes away.
const { onKeyDown } = useDialogFocus({ dialog: dialogRef, initialFocus: closeRef, returnFocusTo });
// Escape closes the window like its X, except while a save is running (as
// in FeedbackDialog). The listener follows the latest onClose and `saving`.
useEffect(() => {
function handleEscape(e: KeyboardEvent) {
if (e.key === "Escape" && !saving) onClose();
}
document.addEventListener("keydown", handleEscape);
return () => document.removeEventListener("keydown", handleEscape);
}, [onClose, saving]);
// A change of mode unmounts the button that had the focus (Create, Cancel,
// Save): entering the upsell puts the focus on the X, every return to the
// list on « Create ». The create and edit forms keep the autoFocus of their
// name field. Never at mount, where the initial focus goes to the X: the
// mode last acted on starts as the mode of the first render, so StrictMode's
// second run of the effect at mount does nothing either.
const focusedMode = useRef(mode);
useEffect(() => {
if (focusedMode.current === mode) return;
focusedMode.current = mode;
if (mode === "upsell") closeRef.current?.focus();
else if (mode === "list") createRef.current?.focus();
}, [mode]);
const handleCreate = () => {
if (creationLocked) {
@ -91,6 +136,11 @@ export default function ProfileFormModal({ onClose, editProfileId }: Props) {
if (!profile || profile.db_filename === "simpl_resultat.db") return;
if (!(await confirmAction(t("profile.deleteConfirm")))) return;
await deleteProfile(id);
// The deleted row takes its delete button, which had the focus, with it:
// the focus goes to « Create », as on every return to the list (#494).
// Today `deleteProfile` also unmounts the window (App shows its loading
// screen while the profiles reload), and the ref is empty by then.
createRef.current?.focus();
};
const handleTogglePin = async (id: string) => {
@ -109,16 +159,29 @@ export default function ProfileFormModal({ onClose, editProfileId }: Props) {
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div className="bg-[var(--card)] rounded-xl shadow-xl w-full max-w-md border border-[var(--border)]">
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-labelledby={PROFILE_FORM_TITLE_ID}
onKeyDown={onKeyDown}
className="bg-[var(--card)] rounded-xl shadow-xl w-full max-w-md border border-[var(--border)]"
>
<div className="flex items-center justify-between p-4 border-b border-[var(--border)]">
<h2 className="font-semibold text-[var(--foreground)]">
<h2 id={PROFILE_FORM_TITLE_ID} className="font-semibold text-[var(--foreground)]">
{mode === "create" || mode === "upsell"
? t("profile.create")
: mode === "edit"
? t("profile.edit")
: t("profile.manageProfiles")}
</h2>
<button onClick={onClose} className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]">
<button
ref={closeRef}
type="button"
onClick={onClose}
aria-label={t("common.close")}
className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
>
<X size={18} />
</button>
</div>
@ -164,6 +227,7 @@ export default function ProfileFormModal({ onClose, editProfileId }: Props) {
</div>
))}
<button
ref={createRef}
onClick={handleCreate}
title={creationLocked ? t("nav.locked") : undefined}
className={`flex items-center gap-2 w-full p-3 rounded-lg border-2 border-dashed border-[var(--border)] hover:border-[var(--primary)] text-[var(--muted-foreground)] text-sm transition-colors ${

View file

@ -21,6 +21,10 @@ export default function ProfileSwitcher() {
const [showManage, setShowManage] = useState(false);
const [showUpsell, setShowUpsell] = useState(false);
const ref = useRef<HTMLDivElement>(null);
// The windows opened from the menu give the focus back to this button when
// they close (#494): the menu item that opened them is unmounted with the
// menu, in the same update as the window mounts.
const triggerRef = useRef<HTMLButtonElement>(null);
// Close on outside click
useEffect(() => {
@ -69,7 +73,11 @@ export default function ProfileSwitcher() {
return (
<>
<div ref={ref} className="relative px-3 pb-2">
{/* No aria-haspopup: the list is not a role="menu" (#494). */}
<button
ref={triggerRef}
type="button"
aria-expanded={open}
onClick={() => setOpen(!open)}
className="flex items-center gap-2 w-full px-3 py-2 rounded-lg text-sm hover:bg-[var(--sidebar-hover)] transition-colors"
>
@ -135,10 +143,16 @@ export default function ProfileSwitcher() {
)}
{showManage && (
<ProfileFormModal onClose={() => setShowManage(false)} />
<ProfileFormModal onClose={() => setShowManage(false)} returnFocusTo={triggerRef} />
)}
{showUpsell && <UpsellDialog feature="multi-profile" onClose={() => setShowUpsell(false)} />}
{showUpsell && (
<UpsellDialog
feature="multi-profile"
onClose={() => setShowUpsell(false)}
returnFocusTo={triggerRef}
/>
)}
</>
);
}

View file

@ -12,7 +12,10 @@
// UpsellDialog stays an element, never called: what it renders (UpsellGate,
// Escape) is proved by UpsellDialog.render.test.tsx. A locked profile that has
// a PIN opens the dialog, never the PIN entry: the lock is checked first, or
// the right PIN would switch to a locked profile.
// the right PIN would switch to a locked profile. The windows opened from the
// menu give the focus back to the switcher's trigger (#494): the test reads the
// ref each window element receives, what the window does with it being proved
// by UpsellDialog.render.test.tsx and ProfileFormModal.render.test.tsx.
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { ReactNode } from "react";
@ -39,11 +42,12 @@ vi.mock("../../contexts/ProfileContext", () => ({
}),
}));
import { ChevronDown } from "lucide-react";
import { ChevronDown, Settings } from "lucide-react";
import { hookHarness } from "../../test/hookHarness";
import { find, holding } from "../../test/elementTree";
import ProfileSwitcher from "./ProfileSwitcher";
import PinDialog from "./PinDialog";
import ProfileFormModal from "./ProfileFormModal";
import UpsellDialog from "../shared/UpsellDialog";
import UpsellGate from "../shared/UpsellGate";
@ -137,3 +141,55 @@ describe("ProfileSwitcher — the upsell of a locked profile (#451)", () => {
expect(ctx.switchProfile).not.toHaveBeenCalled();
});
});
describe("ProfileSwitcher — the trigger and the focus of its windows (#494)", () => {
/** The trigger: the button that holds the chevron. */
function trigger(tree: ReactNode) {
const toggles = holding(tree, ChevronDown);
expect(toggles).toHaveLength(1);
return toggles[0];
}
/** The trigger's ref: a ref object, the one React fills with the button. */
function triggerRef(tree: ReactNode) {
const ref = trigger(tree).props.ref;
expect(ref).toHaveProperty("current");
return ref;
}
it("is a plain button whose aria-expanded follows the menu, without aria-haspopup", () => {
const closed = trigger(render());
expect(closed.props.type).toBe("button");
expect(closed.props["aria-expanded"]).toBe(false);
// The list is not a role="menu": announcing a menu would be wrong (Max, 2026-10-25).
expect(closed.props).not.toHaveProperty("aria-haspopup");
(closed.props.onClick as () => void)();
const opened = trigger(render());
expect(opened.props["aria-expanded"]).toBe(true);
expect(opened.props).not.toHaveProperty("aria-haspopup");
(opened.props.onClick as () => void)();
expect(trigger(render()).props["aria-expanded"]).toBe(false);
});
it("a locked profile's window gives the focus back to the trigger: the menu item is gone by then", () => {
openMenu();
(profileButtons(render(), "second")[0].props.onClick as () => void)();
const opened = render();
const shown = dialogs(opened);
expect(shown).toHaveLength(1);
expect(shown[0].props.returnFocusTo).toBe(triggerRef(opened));
});
it("« Manage profiles » gives the focus back to the trigger too", () => {
openMenu();
const manage = holding(render(), Settings);
expect(manage).toHaveLength(1);
(manage[0].props.onClick as () => void)();
const opened = render();
const forms = find(opened, (el) => el.type === ProfileFormModal);
expect(forms).toHaveLength(1);
expect(forms[0].props.returnFocusTo).toBe(triggerRef(opened));
expect(dialogs(opened)).toHaveLength(0);
});
});

View file

@ -1,13 +1,18 @@
// UpsellDialog — the locked screen in a modal (#369), closed on Escape (#451).
// UpsellDialog — the locked screen in a modal (#369), closed on Escape (#451),
// with the focus on its X and kept inside (#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 dialog runs as a plain function inside `harness.render`, which exposes
// the props it hands to UpsellGate and to its close button, and `commit()`
// runs its Escape effect against a stubbed `document` (the node environment
// has none), whose listener the test then calls with a key.
// has none), whose listener the test then calls with a key. For the focus,
// the test hands fake elements to the refs of the X and of the dialog element
// through their `props.ref` (React 19 keeps `ref` in the props), as React
// would attach them, never through a preset slot of the harness.
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import type { KeyboardEvent as ReactKeyboardEvent, ReactNode, RefObject } from "react";
vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig()));
vi.mock("@tauri-apps/plugin-opener", () => ({ openUrl: vi.fn(() => Promise.resolve()) }));
@ -133,3 +138,98 @@ describe("UpsellDialog — Escape (#451)", () => {
expect(first).not.toHaveBeenCalled();
});
});
describe("UpsellDialog — focus (#494)", () => {
interface FakeElement {
focus: ReturnType<typeof vi.fn>;
isConnected: boolean;
}
const element = (): FakeElement => ({ focus: vi.fn(), isConnected: true });
const doc = {
activeElement: null as FakeElement | null,
body: element(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
};
const refTo = (current: FakeElement) => ({ current }) as unknown as RefObject<HTMLElement | null>;
beforeEach(() => {
doc.activeElement = null;
doc.addEventListener.mockReset();
doc.removeEventListener.mockReset();
vi.stubGlobal("document", doc);
});
afterEach(() => {
vi.unstubAllGlobals();
});
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");
/**
* Renders the dialog, hands the refs of its X and of its dialog element the
* fakes, then runs its effects: the dialog as React mounts it.
*/
function mount(close: FakeElement, options: { dialog?: object; returnFocusTo?: RefObject<HTMLElement | null> } = {}) {
const tree = harness.render(() =>
UpsellDialog({ feature: "adjustments", onClose: vi.fn(), returnFocusTo: options.returnFocusTo }),
);
const [x] = closeButtons(tree);
(x.props.ref as { current: unknown }).current = close;
const [dialog] = dialogElements(tree);
if (options.dialog) (dialog.props.ref as { current: unknown }).current = options.dialog;
harness.commit();
return dialog;
}
it("puts the focus on its X once mounted, not during the render", () => {
const close = element();
const tree = harness.render(() => UpsellDialog({ feature: "adjustments", onClose: vi.fn() }));
(closeButtons(tree)[0].props.ref as { current: unknown }).current = close;
expect(close.focus).not.toHaveBeenCalled();
harness.commit();
expect(close.focus).toHaveBeenCalledTimes(1);
});
it("gives the focus back to the element active at the opening when it goes away (the Répartition button)", () => {
const opener = element();
doc.activeElement = opener;
mount(element());
expect(opener.focus).not.toHaveBeenCalled();
harness.unmount();
expect(opener.focus).toHaveBeenCalledTimes(1);
});
it("gives it to returnFocusTo instead when the host passes it (the profile switcher's trigger)", () => {
const opener = element();
const trigger = element();
doc.activeElement = opener;
mount(element(), { returnFocusTo: refTo(trigger) });
harness.unmount();
expect(trigger.focus).toHaveBeenCalledTimes(1);
expect(opener.focus).not.toHaveBeenCalled();
});
it("Tab on its last button goes back to the X, through the handler of the dialog element", () => {
const close = element();
const purchase = element();
const haveKey = element();
const dialog = mount(close, { dialog: { querySelectorAll: () => [close, purchase, haveKey] } });
close.focus.mockClear();
const preventDefault = vi.fn();
const onKeyDown = dialog.props.onKeyDown as (event: ReactKeyboardEvent<HTMLElement>) => void;
onKeyDown({ key: "Tab", shiftKey: false, target: haveKey, preventDefault } as unknown as ReactKeyboardEvent<HTMLElement>);
expect(preventDefault).toHaveBeenCalledTimes(1);
expect(close.focus).toHaveBeenCalledTimes(1);
onKeyDown({ key: "Tab", shiftKey: true, target: close, preventDefault } as unknown as ReactKeyboardEvent<HTMLElement>);
expect(haveKey.focus).toHaveBeenCalledTimes(1);
});
it("adds no listener of its own to the document: Escape stays the only one", () => {
mount(element());
expect(doc.addEventListener).toHaveBeenCalledTimes(1);
expect(doc.addEventListener).toHaveBeenCalledWith("keydown", expect.any(Function));
});
});

View file

@ -1,12 +1,19 @@
import { useEffect } from "react";
import { useEffect, useRef, type RefObject } from "react";
import { useTranslation } from "react-i18next";
import { X } from "lucide-react";
import { requiredTierFor, type FeatureKey } from "../../shared/entitlements";
import { useDialogFocus } from "../../hooks/useDialogFocus";
import UpsellGate from "./UpsellGate";
interface UpsellDialogProps {
feature: FeatureKey;
onClose: () => void;
/**
* Where the focus goes back when the dialog goes away, when the button that
* opened it is gone by then: ProfileSwitcher passes its trigger (#494).
* Without it, the focus goes back to the element active at the opening.
*/
returnFocusTo?: RefObject<HTMLElement | null>;
}
/**
@ -19,10 +26,16 @@ interface UpsellDialogProps {
* page; the purchase button leaves it open (the product page opens in the
* browser). The X button and Escape close it too; a click on the backdrop does
* not.
*
* Focus (#494, `useDialogFocus`): on the X once mounted, Tab and Shift+Tab
* kept inside, and given back when the dialog goes away, however it goes.
*/
export default function UpsellDialog({ feature, onClose }: UpsellDialogProps) {
export default function UpsellDialog({ feature, onClose, returnFocusTo }: UpsellDialogProps) {
const { t } = useTranslation();
const requiredTier = requiredTierFor(feature);
const dialogRef = useRef<HTMLDivElement>(null);
const closeRef = useRef<HTMLButtonElement>(null);
const { onKeyDown } = useDialogFocus({ dialog: dialogRef, initialFocus: closeRef, returnFocusTo });
// Escape closes the dialog, as in TransactionDetailModal. The listener
// follows the latest onClose: hosts pass an inline arrow.
@ -37,13 +50,16 @@ export default function UpsellDialog({ feature, onClose }: UpsellDialogProps) {
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-label={t("upsell.title", { tier: t(`license.editions.${requiredTier}`) })}
onKeyDown={onKeyDown}
className="bg-[var(--card)] rounded-xl shadow-xl w-full max-w-md border border-[var(--border)]"
>
<div className="flex justify-end p-3 pb-0">
<button
ref={closeRef}
type="button"
onClick={onClose}
aria-label={t("common.close")}

View file

@ -1,4 +1,4 @@
import { Fragment, useState, useMemo } from "react";
import { Fragment, useState, useMemo, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { ChevronUp, ChevronDown, MessageSquare, Tag, Link2 } from "lucide-react";
import type {
@ -95,6 +95,14 @@ export default function TransactionTable({
() => [{ value: "", label: t("transactions.table.noCategory") }],
[t]
);
// The upsell goes away without onClose once the edition resolves to Base or
// Premium (see its render below): clear its flag then, or the dialog would
// come back on its own, and take the focus, if the access went back to
// locked (#494). Before the early return: no hook may come after it, or the
// number of hooks would change when the list goes from no row to some.
useEffect(() => {
if (splitAccess === "open") setShowSplitUpsell(false);
}, [splitAccess]);
if (rows.length === 0) {
return (

View file

@ -7,7 +7,8 @@
// state survives from one call to the next as between two renders of a mounted
// component, and the test clicks through the props the table hands to each
// SplitButton (or to a row's notes button), then renders again to read what
// opened.
// opened. `commit()` runs the table's one effect, which clears the upsell's
// flag once the edition is Base (#494); it touches no `document`.
import { describe, it, expect, vi, beforeEach } from "vitest";
import { Fragment, type ReactNode } from "react";
@ -52,11 +53,11 @@ const row = (id: number, isSplit: boolean): TransactionRow => ({
/** A split row and a plain one: the button must behave the same on both. */
const ROWS = [row(1, true), row(2, false)];
/** One render of the mounted table, under the given access. */
const render = (splitAccess: SplitAccess) =>
/** One render of the mounted table, under the given access, with the given rows (the two of ROWS by default). */
const render = (splitAccess: SplitAccess, rows: TransactionRow[] = ROWS) =>
harness.render(() =>
TransactionTable({
rows: ROWS,
rows,
sort: { column: "date", direction: "desc" },
categories: [GROCERIES],
onSort: vi.fn(),
@ -135,6 +136,40 @@ describe("TransactionTable — the Répartition button's wiring (#369)", () => {
});
});
// The upsell goes away without onClose once the edition is Base: its flag must
// go too, or the dialog would come back on its own, and take the focus, if the
// access went back to locked (#494).
describe("TransactionTable — an upsell gone with the edition stays gone (#494)", () => {
it("does not come back on its own when the access turns locked again", () => {
render("locked");
harness.commit();
(splitButtons(render("locked"))[0].props.onOpenUpsell as () => void)();
// A refresh keeps it open: only an edition that resolves to Base or Premium clears it.
expect(upsells(render("pending"))).toHaveLength(1);
harness.commit();
expect(upsells(render("locked"))).toHaveLength(1);
harness.commit();
expect(upsells(render("open"))).toHaveLength(0);
harness.commit();
expect(upsells(render("locked"))).toHaveLength(0);
// A click opens it again, as before.
(splitButtons(render("locked"))[0].props.onOpenUpsell as () => void)();
expect(upsells(render("locked"))).toHaveLength(1);
});
// The effect sits before the early return of an empty table: a hook after it
// would change the number of hooks when the list goes from no row to some
// (React throws), and would not run while the table is empty.
it("clears it even while the table has no row", () => {
(splitButtons(render("locked"))[0].props.onOpenUpsell as () => void)();
render("locked", []);
harness.commit();
render("open", []);
harness.commit();
expect(upsells(render("locked"))).toHaveLength(0);
});
});
describe("TransactionTable — the notes row (#437)", () => {
/** The rows' notes buttons, named by their title (pinned in TransactionTable.render.test.tsx). */
const notesButtons = (tree: ReactNode) =>

View file

@ -0,0 +1,247 @@
// 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"])',
]);
});
});

View file

@ -0,0 +1,74 @@
import { useEffect, type KeyboardEvent as ReactKeyboardEvent, type RefObject } from "react";
/**
* What can take the focus inside a dialog, for the Tab loop (#494): a disabled
* button or field is left out, as the browser leaves it out of the Tab order.
*/
export const FOCUSABLE_SELECTOR =
'button:not([disabled]), [href], input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])';
export interface DialogFocusRefs {
/** The `role="dialog"` element: Tab and Shift+Tab loop through its focusable elements. */
dialog: RefObject<HTMLElement | null>;
/** What takes the focus once the dialog is mounted: its close button. */
initialFocus: RefObject<HTMLElement | null>;
/**
* What takes the focus back when the dialog goes away, when the host has it:
* it wins over the element that was active at mount. ProfileSwitcher passes
* its trigger, since the menu item that opened the dialog is gone by then.
*/
returnFocusTo?: RefObject<HTMLElement | null>;
}
/** The element active at mount, if the focus can go back to it: neither `body` nor out of the document. */
function returnable(element: Element | null): HTMLElement | null {
if (!element || element === document.body || !element.isConnected) return null;
return element as HTMLElement;
}
/**
* The focus of a modal window (#494), shared by UpsellDialog and
* ProfileFormModal.
*
* - Once mounted, the dialog remembers the active element and puts the focus
* on `initialFocus`.
* - When it goes away, the focus goes to `returnFocusTo` when the host passed
* it and it holds an element, otherwise to the element remembered at mount,
* unless that one is `body` or no longer in the document. This runs in the
* effect's cleanup, so it also covers a dialog its host unmounts without
* calling `onClose` (the split upsell once the edition is Base).
* - The returned `onKeyDown`, set on the dialog element (never on `document`,
* where the dialogs listen for Escape), makes Tab on the last focusable
* element go to the first, and Shift+Tab on the first go to the last.
*
* `useEffect` is its only hook: the hook harness of the tests throws on a
* generated id or a layout effect (src/test/hookHarness.ts). The refs are
* stable objects, read when the effect runs and when it is cleaned up, hence
* the empty dependency list: mount and unmount only.
*/
export function useDialogFocus({ dialog, initialFocus, returnFocusTo }: DialogFocusRefs) {
useEffect(() => {
const opener = document.activeElement;
initialFocus.current?.focus();
return () => {
(returnFocusTo?.current ?? returnable(opener))?.focus();
};
}, []);
const onKeyDown = (event: ReactKeyboardEvent<HTMLElement>) => {
if (event.key !== "Tab") return;
const focusable = dialog.current?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);
if (!focusable || focusable.length === 0) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (event.shiftKey && event.target === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && event.target === last) {
event.preventDefault();
first.focus();
}
};
return { onKeyDown };
}