iter(g27): 抽出弹层 Esc 栈,多弹层只关最上层
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { effect, h } from '@ui-arch/frame';
|
||||
import type { DrawerProps } from './types.js';
|
||||
import { pushOverlay } from './overlay.js';
|
||||
|
||||
/*** 抽屉:open 信号驱动侧滑面板,点遮罩 / × / Esc 关闭;Tab 焦点陷阱 + 关闭归还焦点,与 modal 的分工是不打断主视图、可从侧边保留上下文 ***/
|
||||
export function drawer(props: DrawerProps, ...children: unknown[]): HTMLElement {
|
||||
@@ -29,15 +30,19 @@ export function drawer(props: DrawerProps, ...children: unknown[]): HTMLElement
|
||||
overlay.append(panel);
|
||||
|
||||
let lastFocus: HTMLElement | null = null; // 打开前焦点宿主,关闭时归还
|
||||
let release: (() => void) | null = null; // Esc 栈注销函数,关闭时释放
|
||||
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; // 记录打开前焦点
|
||||
release ??= pushOverlay(close); // 入 Esc 栈:多弹层时只关最上层
|
||||
(panel.querySelector('button, input, textarea') as HTMLElement | null)?.focus(); // 打开时聚焦首个可交互元素
|
||||
} else if (lastFocus) {
|
||||
lastFocus.focus(); // 关闭时归还焦点
|
||||
} else {
|
||||
release?.(); // 出 Esc 栈
|
||||
release = null;
|
||||
lastFocus?.focus(); // 关闭时归还焦点
|
||||
lastFocus = null;
|
||||
}
|
||||
});
|
||||
@@ -53,8 +58,5 @@ export function drawer(props: DrawerProps, ...children: unknown[]): HTMLElement
|
||||
e.preventDefault(); first.focus(); // Tab 到末位时回绕到开头
|
||||
}
|
||||
});
|
||||
document.addEventListener('keydown', (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && props.open()) close();
|
||||
});
|
||||
return overlay;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user