Files
UI/packages/skin/ui/src/tooltip.ts
T
2026-10-26 15:32:47 +08:00

73 lines
3.4 KiB
TypeScript

import { effect, h, signal } from '@ui-arch/frame';
import type { TooltipProps } from './types.js';
import { flipSide } 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<'top' | 'bottom' | 'left' | 'right'>(props.placement ?? 'top'); // 实际生效方位:出场时按视口空间自动翻转
const id = `ua-tip-${++seq}`; // 气泡唯一 id
const delay = props.delay ?? 150; // 出场延迟毫秒;<=0 视为立即显示
let timer: number | null = null; // 出场延迟计时器句柄
let holdTimer: 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;
}
if (holdTimer != null) { // 触摸遗留的延迟收起一并取消,避免刚点开又被上一轮收掉
window.clearTimeout(holdTimer);
holdTimer = null;
}
open(false);
};
/*** 触摸抬手后延迟收起:手指离开屏幕时气泡正被人挡着,留一会儿再收 ***/
const hideLater = (ms = 1200): void => {
if (holdTimer != null) window.clearTimeout(holdTimer);
holdTimer = window.setTimeout(() => {
holdTimer = null;
open(false);
}, ms);
};
// —— 触发器与气泡 ——
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', (e: PointerEvent) => { if (e.pointerType !== 'touch') show(); }); // 鼠标进入(触摸交给下面的点按)
root.addEventListener('pointerleave', (e: PointerEvent) => { if (e.pointerType !== 'touch') hide(); }); // 鼠标离开
root.addEventListener('focusin', show); // 键盘聚焦(focusin 会冒泡)
root.addEventListener('focusout', hide); // 失焦
// —— 触摸屏:没有 hover,改点按。按下即出(不等 150ms),抬手留 1.2s 再收,否则手指正挡着气泡就没了 ——
root.addEventListener('pointerdown', (e: PointerEvent) => { if (e.pointerType === 'touch') show(); });
root.addEventListener('pointerup', (e: PointerEvent) => { if (e.pointerType === 'touch') hideLater(); });
effect(() => { if (open()) place(flipSide(trigger, bubble, props.placement ?? 'top')); }); // 每次出场重算方位:空间不足自动翻转
root.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.key === 'Escape') { e.stopPropagation(); hide(); } // Esc 立即收起且不影响外层弹层
});
return root;
}