Files
UI/packages/skin/ui/src/image.ts
T
2026-10-23 18:59:32 +08:00

38 lines
1.5 KiB
TypeScript

import { h } from '@ui-arch/frame';
import type { ImageProps } from './types.js';
/*** 图片:缩略图展示,点击 / 回车打开遮罩大图预览(Esc 或点击遮罩关闭),样式只消费 --ua-* 令牌 ***/
export function image(props: ImageProps): HTMLElement {
const style = props.width ? `width:${props.width}px` : '';
return 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),
});
}
/*** 打开全屏遮罩预览层;关闭时自清理、解绑键盘并归还焦点 ***/
function openViewer(src: string, alt?: string): void {
const prev = document.activeElement as HTMLElement | null; // 焦点归还目标
const mask = h(
'div',
{ class: 'ua-image-mask', role: 'dialog', 'aria-modal': 'true', 'aria-label': '图片预览' },
h('img', { class: 'ua-image-full', src, alt: alt ?? '' }),
);
const close = () => {
mask.remove(); // 卫语句式自清理:遮罩移除 + 键盘解绑 + 焦点归还
document.removeEventListener('keydown', onKey);
prev?.focus?.();
};
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && close();
mask.addEventListener('click', close);
document.addEventListener('keydown', onKey);
document.body.appendChild(mask);
}