import { h } from '@ui-arch/frame'; import { lockScroll, pushOverlay, trapFocus } from './overlay.js'; import type { ImageProps } from './types.js'; /*** 图片:缩略图展示,点击 / 回车打开遮罩大图预览(Esc 或点击遮罩关闭),加载失败自动落占位;样式只消费 --ua-* 令牌 ***/ export function image(props: ImageProps): HTMLElement { const style = props.width ? `width:${props.width}px` : ''; const img = h('img', { class: 'ua-image', src: props.src, alt: props.alt ?? '', style, tabindex: '0', // 可聚焦,键盘用户回车预览 role: 'button', 'aria-label': '预览图片', onclick: () => openViewer(props.src, props.alt), onkeydown: (e: KeyboardEvent) => e.key === 'Enter' && openViewer(props.src, props.alt), }); img.addEventListener('error', () => { const box = h('span', { class: 'ua-image-fallback', style, role: 'img', 'aria-label': props.fallback ?? '图片加载失败' }, props.fallback ?? '图片加载失败'); img.replaceWith(box); // 失败兜底:整块替换,避免残留破图图标 }); return img; } /*** 打开全屏遮罩预览层;关闭时自清理、解绑键盘并归还焦点 ***/ function openViewer(src: string, alt?: string): void { let releaseEsc: (() => void) | null = null; // Esc 栈注销函数:预览层占一层,关闭即释放 const releaseLock = lockScroll(); // 预览期锁背景滚动 const prev = document.activeElement as HTMLElement | null; // 焦点归还目标 const mask = h( 'div', { class: 'ua-image-mask', role: 'dialog', 'aria-modal': 'true', 'aria-label': '图片预览', tabindex: '-1' }, h('img', { class: 'ua-image-full', src, alt: alt ?? '' }), ); const close = () => { mask.remove(); // 自清理:遮罩移除 + 出 Esc 栈 + 焦点归还 releaseEsc?.(); releaseLock(); prev?.focus?.(); }; mask.addEventListener('click', close); releaseEsc = pushOverlay(close); // 入 Esc 栈:预览层压在最上面,Esc 先关它 trapFocus(mask, () => true); // 预览层常开:Tab 全程锁在遮罩内(层内无控件,等于整体拦截) document.body.appendChild(mask); mask.focus(); // 焦点移入预览层,读屏与键盘都不再落在背后的页面 }