iter(g102): 焦点陷阱下沉为共享助手
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import { effect, h } from '@ui-arch/frame';
|
||||
import type { ModalProps } from './types.js';
|
||||
import { lockScroll, pushOverlay } from './overlay.js';
|
||||
import { lockScroll, pushOverlay, trapFocus } from './overlay.js';
|
||||
|
||||
let seq = 0; // 实例序号:给标题生成唯一 id,供 aria-labelledby 关联
|
||||
|
||||
@@ -31,9 +31,6 @@ export function modal(props: ModalProps, ...children: unknown[]): HTMLElement {
|
||||
let lastFocus: HTMLElement | null = null; // 打开前焦点宿主,关闭时归还
|
||||
let release: (() => void) | null = null; // Esc 栈注销函数,关闭时释放
|
||||
let releaseLock: (() => void) | null = null; // 背景滚动锁解锁函数,全关才还原
|
||||
const focusables = (): HTMLElement[] =>
|
||||
Array.from(box.querySelectorAll<HTMLElement>('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'))
|
||||
.filter((el) => !el.hasAttribute('disabled')); // 弹窗内可聚焦元素(排除禁用)
|
||||
effect(() => {
|
||||
const open = props.open();
|
||||
overlay.classList.toggle('ua-open', open); // 显隐跟随信号
|
||||
@@ -51,17 +48,6 @@ export function modal(props: ModalProps, ...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 || !box.contains(document.activeElement))) {
|
||||
e.preventDefault(); last.focus(); // Shift+Tab 到首位时回绕到末尾
|
||||
} else if (!e.shiftKey && (document.activeElement === last || !box.contains(document.activeElement))) {
|
||||
e.preventDefault(); first.focus(); // Tab 到末位时回绕到开头
|
||||
}
|
||||
});
|
||||
trapFocus(box, () => props.open()); // Tab 焦点陷阱:与 drawer 共用同一份实现
|
||||
return overlay;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user