fix(frontend): Drawer 焦点还原提取 useRestoreFocus + 回归测试 + DRY(CR-H11)
This commit is contained in:
24
apps/web/lib/a11y/useRestoreFocus.ts
Normal file
24
apps/web/lib/a11y/useRestoreFocus.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, type RefObject } from "react";
|
||||
|
||||
// 弹层(Drawer / ContextDrawer)关闭后把焦点还给触发元素(a11y 焦点管理,CR-H11)。
|
||||
// wasOpenRef 门闩:仅在「曾打开过」后的关闭才还原,避免从未打开时误抢焦点。
|
||||
// null-safe:triggerRef 或其 current 为空时静默跳过。
|
||||
export function useRestoreFocus(
|
||||
open: boolean,
|
||||
triggerRef?: RefObject<HTMLElement | null>,
|
||||
): void {
|
||||
const wasOpenRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
if (wasOpenRef.current) {
|
||||
wasOpenRef.current = false;
|
||||
triggerRef?.current?.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
wasOpenRef.current = true;
|
||||
}, [open, triggerRef]);
|
||||
}
|
||||
Reference in New Issue
Block a user