import { effect } from '@ui-arch/frame'; import type { Signal } from '@ui-arch/frame'; /*** 弹层键盘栈:维护打开顺序,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(); }; /*** 点外部关闭:仅在展开期间挂全局 click,收起即摘(避免逐实例常驻监听,组件卸载后不再残留) ***/ export function bindOutside(root: HTMLElement, isOpen: Signal, close: () => void): void { // —— 状态集中声明 —— let release: (() => void) | null = null; // 当前监听的注销函数,未挂载时为 null const handler = (e: Event): void => { if (root.contains(e.target as Node)) return; // 卫语句:组件内点击不处理 close(); }; effect(() => { if (isOpen() && !release) { document.addEventListener('click', handler); release = () => document.removeEventListener('click', handler); } else if (!isOpen() && release) { release(); // 收起即摘 release = null; } }); } /*** 注册一个打开的弹层,返回注销函数(弹层关闭时务必调用,否则栈不清理) ***/ 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; } }; } // —— 背景滚动锁:模态弹层(modal/drawer/image 预览)引用计数,全关才解锁 —— let locks = 0; // 活跃模态层数 /*** 模态层打开时调用,返回解锁函数;嵌套叠加时只由最外层还原 body 内联样式 ***/ export function lockScroll(): () => void { if (locks === 0) document.body.style.overflow = 'hidden'; // 第一层才锁,避免相互覆盖 locks++; return () => { locks--; if (locks === 0) document.body.style.overflow = ''; // 全关解锁 }; }