iter(g27): 抽出弹层 Esc 栈,多弹层只关最上层
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
/*** 弹层键盘栈:维护打开顺序,Esc 只关最上层,避免多个弹层(含嵌套)被一次全关 ***/
|
||||
|
||||
// —— 状态集中声明 ——
|
||||
const stack: { close: () => void }[] = []; // 打开中的弹层,后进先出
|
||||
let bound = false; // 全局 keydown 监听只挂一次,栈空时摘除
|
||||
|
||||
/*** 全局 Esc 分发:只把事件交给栈顶弹层,其余保持不动 ***/
|
||||
const onKeydown = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Escape') return; // 卫语句:只关心 Esc
|
||||
const top = stack[stack.length - 1];
|
||||
if (!top) return; // 卫语句:栈空无事可做
|
||||
e.preventDefault();
|
||||
top.close();
|
||||
};
|
||||
|
||||
/*** 注册一个打开的弹层,返回注销函数(弹层关闭时务必调用,否则栈不清理) ***/
|
||||
export function pushOverlay(close: () => void): () => void {
|
||||
if (!bound) {
|
||||
document.addEventListener('keydown', onKeydown); // 首个弹层才挂全局监听
|
||||
bound = true;
|
||||
}
|
||||
const entry = { close };
|
||||
stack.push(entry);
|
||||
return () => {
|
||||
const i = stack.indexOf(entry);
|
||||
if (i >= 0) stack.splice(i, 1); // 出栈:允许非栈顶关闭
|
||||
if (!stack.length && bound) {
|
||||
document.removeEventListener('keydown', onKeydown); // 栈空摘监听,避免泄漏
|
||||
bound = false;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user