Files
writer-work-flow/apps/web/lib/a11y/useRestoreFocus.ts

25 lines
731 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useEffect, useRef, type RefObject } from "react";
// 弹层Drawer / ContextDrawer关闭后把焦点还给触发元素a11y 焦点管理CR-H11
// wasOpenRef 门闩:仅在「曾打开过」后的关闭才还原,避免从未打开时误抢焦点。
// null-safetriggerRef 或其 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]);
}