iter(g45): modal/drawer/image 打开时锁定背景滚动

This commit is contained in:
HIsheR
2026-10-26 12:02:16 +08:00
parent 7437fed395
commit 0a0dc7a853
5 changed files with 28 additions and 3 deletions
+5 -1
View File
@@ -1,6 +1,6 @@
import { effect, h } from '@ui-arch/frame';
import type { ModalProps } from './types.js';
import { pushOverlay } from './overlay.js';
import { lockScroll, pushOverlay } from './overlay.js';
/*** 弹窗:open 信号驱动显隐,点遮罩、× 或 Esc 触发 onClose;Tab 焦点陷阱 + 关闭归还焦点 ***/
export function modal(props: ModalProps, ...children: unknown[]): HTMLElement {
@@ -25,6 +25,7 @@ export function modal(props: ModalProps, ...children: unknown[]): HTMLElement {
overlay.append(box);
let lastFocus: HTMLElement | null = null; // 打开前焦点宿主,关闭时归还
let release: (() => void) | null = null; // Esc 栈注销函数,关闭时释放
let releaseLock: (() => void) | null = null; // 背景滚动锁解锁函数,全关才还原
const focusables = (): HTMLElement[] =>
Array.from(box.querySelectorAll<HTMLElement>('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'))
.filter((el) => !el.hasAttribute('disabled')); // 弹窗内可聚焦元素(排除禁用)
@@ -34,10 +35,13 @@ export function modal(props: ModalProps, ...children: unknown[]): HTMLElement {
if (open) {
lastFocus = document.activeElement as HTMLElement | null; // 记录打开前焦点
release ??= pushOverlay(close); // 入 Esc 栈:多弹层时只关最上层
releaseLock ??= lockScroll(); // 模态期锁背景滚动
(box.querySelector('button, input, textarea') as HTMLElement | null)?.focus(); // 打开时聚焦首个可交互元素
} else {
release?.(); // 出 Esc 栈
release = null;
releaseLock?.(); // 解锁背景滚动
releaseLock = null;
lastFocus?.focus(); // 关闭时归还焦点
lastFocus = null;
}