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 = ''; // 全关解锁 }; } /*** 焦点陷阱:Tab / Shift+Tab 在容器内首尾环形循环,容器内无可用焦点时整体拦截;焦点已在容器外则按方向拉回首尾 ***/ export function trapFocus(box: HTMLElement, isOpen: () => boolean): void { box.addEventListener('keydown', (e: KeyboardEvent) => { if (e.key !== 'Tab' || !isOpen()) return; // 卫语句:只处理打开中的 Tab const els = Array.from(box.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')) .filter((el) => !el.hasAttribute('disabled')); // 容器内可聚焦元素(排除禁用) if (!els.length) { e.preventDefault(); return; } // 卫语句:无可用焦点就整体拦截,防焦点逃逸 const first = els[0]; const last = els[els.length - 1]; const active = document.activeElement; const outside = !box.contains(active); // 焦点落在容器外:按方向重新拉回,而不是让它继续往外跑 if (e.shiftKey && (active === first || outside)) { e.preventDefault(); last.focus(); // Shift+Tab 到首位回绕到末尾 } else if (!e.shiftKey && (active === last || outside)) { e.preventDefault(); first.focus(); // Tab 到末位回绕到开头 } }); }