fix(frontend): Drawer 焦点还原提取 useRestoreFocus + 回归测试 + DRY(CR-H11)

This commit is contained in:
Yaojia Wang
2026-07-08 11:10:23 +02:00
parent 5c02792e5f
commit 6e2b478ca9
4 changed files with 97 additions and 20 deletions

View File

@@ -0,0 +1,65 @@
// @vitest-environment jsdom
import { renderHook } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import type { RefObject } from "react";
import { useRestoreFocus } from "./useRestoreFocus";
const appended: HTMLElement[] = [];
function mountEl<T extends HTMLElement>(el: T): T {
document.body.appendChild(el);
appended.push(el);
return el;
}
afterEach(() => {
for (const el of appended.splice(0)) el.remove();
});
describe("useRestoreFocusCR-H11", () => {
it("关闭时把焦点还给 triggerRef", () => {
const trigger = mountEl(document.createElement("button"));
const other = mountEl(document.createElement("input"));
const ref: RefObject<HTMLElement | null> = { current: trigger };
const { rerender } = renderHook(
({ open }) => useRestoreFocus(open, ref),
{ initialProps: { open: true } },
);
other.focus();
expect(document.activeElement).toBe(other);
rerender({ open: false });
expect(document.activeElement).toBe(trigger);
});
it("从未打开过关闭态不抢焦点wasOpen 门闩)", () => {
const trigger = mountEl(document.createElement("button"));
const other = mountEl(document.createElement("input"));
const ref: RefObject<HTMLElement | null> = { current: trigger };
renderHook(({ open }) => useRestoreFocus(open, ref), {
initialProps: { open: false },
});
other.focus();
expect(document.activeElement).toBe(other);
});
it("triggerRef 为 null / undefined 时关闭不抛错", () => {
const nullRef: RefObject<HTMLElement | null> = { current: null };
const nullCase = renderHook(
({ open }) => useRestoreFocus(open, nullRef),
{ initialProps: { open: true } },
);
expect(() => nullCase.rerender({ open: false })).not.toThrow();
const undefCase = renderHook(
({ open }) => useRestoreFocus(open, undefined),
{ initialProps: { open: true } },
);
expect(() => undefCase.rerender({ open: false })).not.toThrow();
});
});