iter(g102): 焦点陷阱下沉为共享助手

This commit is contained in:
HIsheR
2026-10-26 13:51:40 +08:00
parent f373b8cf31
commit abfbb821b7
5 changed files with 37 additions and 34 deletions
+2 -16
View File
@@ -1,6 +1,6 @@
import { effect, h } from '@ui-arch/frame';
import type { DrawerProps } from './types.js';
import { lockScroll, pushOverlay } from './overlay.js';
import { lockScroll, pushOverlay, trapFocus } from './overlay.js';
let seq = 0; // 实例序号:给标题生成唯一 id,供 aria-labelledby 关联
@@ -38,9 +38,6 @@ export function drawer(props: DrawerProps, ...children: unknown[]): HTMLElement
let lastFocus: HTMLElement | null = null; // 打开前焦点宿主,关闭时归还
let release: (() => void) | null = null; // Esc 栈注销函数,关闭时释放
let releaseLock: (() => void) | null = null; // 背景滚动锁解锁函数,全关才还原
const focusables = (): HTMLElement[] =>
Array.from(panel.querySelectorAll<HTMLElement>('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'))
.filter((el) => !el.hasAttribute('disabled')); // 面板内可聚焦元素(排除禁用)
effect(() => {
if (props.open()) {
lastFocus = document.activeElement as HTMLElement | null; // 记录打开前焦点
@@ -56,17 +53,6 @@ export function drawer(props: DrawerProps, ...children: unknown[]): HTMLElement
lastFocus = null;
}
});
overlay.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.key !== 'Tab' || !props.open()) return; // 仅处理打开中的 Tab
const els = focusables();
if (els.length === 0) { e.preventDefault(); return; } // 无可聚焦元素:拦截 Tab 防焦点逃逸
const first = els[0];
const last = els[els.length - 1];
if (e.shiftKey && (document.activeElement === first || !panel.contains(document.activeElement))) {
e.preventDefault(); last.focus(); // Shift+Tab 到首位时回绕到末尾
} else if (!e.shiftKey && (document.activeElement === last || !panel.contains(document.activeElement))) {
e.preventDefault(); first.focus(); // Tab 到末位时回绕到开头
}
});
trapFocus(panel, () => props.open()); // Tab 焦点陷阱:与 modal 共用同一份实现
return overlay;
}