iter(g43): select/menu/popover/image 的 Esc 接入统一弹层栈

This commit is contained in:
HIsheR
2026-10-26 11:57:50 +08:00
parent f0b115db94
commit fc8a541fe6
5 changed files with 37 additions and 17 deletions
+10 -5
View File
@@ -1,6 +1,7 @@
import { effect, h, signal } from '@ui-arch/frame';
import type { PopoverProps } from './types.js';
import { flip } from './position.js';
import { pushOverlay } from './overlay.js';
let seq = 0; // 全局自增序号:保证每个弹层 id 唯一,供 aria-controls 关联
@@ -8,6 +9,7 @@ let seq = 0; // 全局自增序号:保证每个弹层 id 唯一,供 aria-con
export function popover(props: PopoverProps, trigger: HTMLElement): HTMLElement {
// —— 状态集中声明 ——
const open = signal(false); // 弹层显隐
let releaseEsc: (() => void) | null = null; // Esc 栈注销函数:展开期间占一层,收起即释放
const place = signal(props.placement ?? 'bottom'); // 实际生效方位:打开时按视口空间自动翻转
const id = `ua-pop-${++seq}`; // 弹层唯一 id
let timer: number | null = null; // hover 模式下的出入场计时器
@@ -52,13 +54,16 @@ export function popover(props: PopoverProps, trigger: HTMLElement): HTMLElement
});
}
root.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.key !== 'Escape' || !open()) return; // 卫语句:未展开时 Esc 不处理
e.stopPropagation(); // 只关本层,避免连带关闭外层弹窗
setOpen(false);
trigger.focus(); // 收起后焦点回触发器
});
document.addEventListener('click', () => setOpen(false)); // 点外部收起(弹层内已阻止冒泡)
effect(() => { if (open()) place(flip(trigger, panel, props.placement ?? 'bottom')); }); // 每次打开重算方位:空间不足自动翻转
effect(() => {
if (open()) {
releaseEsc ??= pushOverlay(() => { setOpen(false); trigger.focus(); }); // 入 Esc 栈:与弹窗/抽屉共用同一套逐层关闭
} else {
releaseEsc?.();
releaseEsc = null;
}
});
return root;
}