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 { DrawerProps } from './types.js';
import { pushOverlay } from './overlay.js';
import { lockScroll, pushOverlay } from './overlay.js';
/*** 抽屉:open 信号驱动侧滑面板,点遮罩 / × / Esc 关闭;Tab 焦点陷阱 + 关闭归还焦点,与 modal 的分工是不打断主视图、可从侧边保留上下文 ***/
export function drawer(props: DrawerProps, ...children: unknown[]): HTMLElement {
@@ -31,6 +31,7 @@ export function drawer(props: DrawerProps, ...children: unknown[]): HTMLElement
let lastFocus: HTMLElement | null = null; // 打开前焦点宿主,关闭时归还
let release: (() => void) | null = null; // Esc 栈注销函数,关闭时释放
let releaseLock: (() => void) | null = null; // 背景滚动锁解锁函数,全关才还原
const focusables = (): HTMLElement[] =>
Array.from(panel.querySelectorAll<HTMLElement>('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'))
.filter((el) => !el.hasAttribute('disabled')); // 面板内可聚焦元素(排除禁用)
@@ -38,10 +39,13 @@ export function drawer(props: DrawerProps, ...children: unknown[]): HTMLElement
if (props.open()) {
lastFocus = document.activeElement as HTMLElement | null; // 记录打开前焦点
release ??= pushOverlay(close); // 入 Esc 栈:多弹层时只关最上层
releaseLock ??= lockScroll(); // 模态期锁背景滚动
(panel.querySelector('button, input, textarea') as HTMLElement | null)?.focus(); // 打开时聚焦首个可交互元素
} else {
release?.(); // 出 Esc 栈
release = null;
releaseLock?.(); // 解锁背景滚动
releaseLock = null;
lastFocus?.focus(); // 关闭时归还焦点
lastFocus = null;
}