iter(g86): 弹层外部点击监听改按需挂载

This commit is contained in:
HIsheR
2026-10-26 13:05:34 +08:00
parent 249fa03f01
commit a123140fab
10 changed files with 46 additions and 39 deletions
+22
View File
@@ -1,3 +1,6 @@
import { effect } from '@ui-arch/frame';
import type { Signal } from '@ui-arch/frame';
/*** 弹层键盘栈:维护打开顺序,Esc 只关最上层,避免多个弹层(含嵌套)被一次全关 ***/
// —— 状态集中声明 ——
@@ -13,6 +16,25 @@ const onKeydown = (e: KeyboardEvent) => {
top.close();
};
/*** 点外部关闭:仅在展开期间挂全局 click,收起即摘(避免逐实例常驻监听,组件卸载后不再残留) ***/
export function bindOutside(root: HTMLElement, isOpen: Signal<boolean>, 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) {