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 -7
View File
@@ -1,11 +1,13 @@
import { effect, h, signal } from '@ui-arch/frame';
import type { MenuItem, MenuProps } from './types.js';
import { flip } from './position.js';
import { pushOverlay } from './overlay.js';
/*** 下拉菜单:触发器 + 自绘弹层,项支持禁用 / 危险 / 分隔线;点项 / 点外部 / Esc 关闭,↑↓ 环形导航 + Home/End 跳转 + 键入快跳 ***/
export function menu(props: MenuProps): HTMLElement {
// —— 状态集中声明 ——
const open = signal(false); // 弹层开合
let releaseEsc: (() => void) | null = null; // Esc 栈注销函数:展开期间占一层,收起即释放
const place = signal<'top' | 'bottom'>('bottom'); // 实际生效方位:打开时按视口空间自动翻转
const focusables: HTMLButtonElement[] = []; // 可聚焦项(跳过分隔线与禁用项),供键盘导航
const labels: string[] = []; // 与 focusables 平行的条目文案,供键入快跳
@@ -72,12 +74,6 @@ export function menu(props: MenuProps): HTMLElement {
};
root.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.stopPropagation(); // 只关本层:不再冒泡去关外层的弹窗/抽屉
open(false);
trigger.focus(); // 收起后焦点回到触发器,键盘流不断
return;
}
if (e.key === 'Home' && open()) { e.preventDefault(); focusables[0]?.focus(); return; } // Home 跳首项
if (e.key === 'End' && open()) { e.preventDefault(); focusables[focusables.length - 1]?.focus(); return; } // End 跳末项
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') {
@@ -100,7 +96,14 @@ export function menu(props: MenuProps): HTMLElement {
open(false); // 点外部收起
});
effect(() => open()); // 建立依赖,保证开合信号生效
effect(() => {
if (open()) {
releaseEsc ??= pushOverlay(() => { open(false); trigger.focus(); }); // 入 Esc 栈:与弹窗/抽屉共用同一套逐层关闭
} else {
releaseEsc?.();
releaseEsc = null;
}
});
effect(() => { if (open()) place(flip(trigger, pop, 'bottom')); }); // 每次打开重算方位:空间不足自动翻转
return root;
}