import { effect, h, signal } from '@ui-arch/frame'; import type { TooltipProps } from './types.js'; import { flip } from './position.js'; let seq = 0; // 全局自增序号:保证每个气泡 id 唯一,供 aria-describedby 关联 /*** 悬浮提示:包裹触发器,hover / focus 延迟出场,移出 / 失焦 / Esc 收起,纯展示不拦截指针 ***/ export function tooltip(props: TooltipProps, trigger: HTMLElement): HTMLElement { // —— 状态集中声明 —— const open = signal(false); // 气泡显隐 const place = signal(props.placement ?? 'top'); // 实际生效方位:出场时按视口空间自动翻转 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-${place()}${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); // 失焦 effect(() => { if (open()) place(flip(trigger, bubble, props.placement ?? 'top')); }); // 每次出场重算方位:空间不足自动翻转 root.addEventListener('keydown', (e: KeyboardEvent) => { if (e.key === 'Escape') { e.stopPropagation(); hide(); } // Esc 立即收起且不影响外层弹层 }); return root; }