import { h, signal } from '@ui-arch/frame'; import type { TooltipProps } from './types.js'; let seq = 0; // 全局自增序号:保证每个气泡 id 唯一,供 aria-describedby 关联 /*** 悬浮提示:包裹触发器,hover / focus 延迟出场,移出 / 失焦 / Esc 收起,纯展示不拦截指针 ***/ export function tooltip(props: TooltipProps, trigger: HTMLElement): HTMLElement { // —— 状态集中声明 —— const open = signal(false); // 气泡显隐 const id = `ua-tip-${++seq}`; // 气泡唯一 id const delay = props.delay ?? 150; // 出场延迟毫秒;<=0 视为立即显示 let timer: number | null = null; // 出场延迟计时器句柄 const show = () => { if (timer != null) window.clearTimeout(timer); // 重复进入先清旧计时 if (delay <= 0) return open(true); timer = window.setTimeout(() => { timer = null; open(true); }, delay); }; const hide = () => { if (timer != null) { // 还没出场就离开:直接取消计时,避免闪一下 window.clearTimeout(timer); timer = null; } open(false); }; // —— 触发器与气泡 —— trigger.setAttribute('aria-describedby', id); // 无障碍:读屏把提示文案关联到触发器 const bubble = h( 'span', { id, class: () => `ua-tip ua-tip-${props.placement ?? 'top'}${open() ? ' ua-open' : ''}`, role: 'tooltip', 'aria-hidden': () => String(!open()), }, props.content, ); const root = h('span', { class: 'ua-tip-wrap' }, trigger, bubble); root.addEventListener('pointerenter', show); // 鼠标进入 root.addEventListener('pointerleave', hide); // 鼠标离开 root.addEventListener('focusin', show); // 键盘聚焦(focusin 会冒泡) root.addEventListener('focusout', hide); // 失焦 root.addEventListener('keydown', (e: KeyboardEvent) => { if (e.key === 'Escape') hide(); // Esc 立即收起,不必等延迟 }); return root; }