fix: tooltip positioning — measure after rAF, shift up minimally to fit
This commit is contained in:
@@ -29,19 +29,27 @@ export function tooltip(node: HTMLElement, text: string) {
|
||||
if (!currentText) return;
|
||||
const el = getTooltipEl();
|
||||
el.textContent = currentText;
|
||||
|
||||
// Position off-screen first so we can measure dimensions after render
|
||||
el.style.left = '-9999px';
|
||||
el.style.top = '-9999px';
|
||||
el.classList.add('hu-tooltip--visible');
|
||||
|
||||
// Position near cursor, clamped to viewport with 8px margin
|
||||
// Use rAF to let the browser lay out the element before measuring
|
||||
requestAnimationFrame(() => {
|
||||
position(el, e.clientX, e.clientY);
|
||||
});
|
||||
}
|
||||
|
||||
function position(el: HTMLDivElement, cx: number, cy: number) {
|
||||
const margin = 8;
|
||||
const w = el.offsetWidth;
|
||||
const h = el.offsetHeight;
|
||||
const x = Math.min(e.clientX + 12, window.innerWidth - w - margin);
|
||||
// Try below cursor first; if it clips the bottom, flip above
|
||||
let y = e.clientY + 20;
|
||||
if (y + h + margin > window.innerHeight) {
|
||||
y = e.clientY - h - 12;
|
||||
}
|
||||
// Final clamp: don't go above top of viewport
|
||||
const x = Math.min(cx + 12, window.innerWidth - w - margin);
|
||||
// Place below cursor; shift up only as much as needed to fit
|
||||
let y = cy + 20;
|
||||
const overflow = y + h + margin - window.innerHeight;
|
||||
if (overflow > 0) y -= overflow;
|
||||
y = Math.max(margin, y);
|
||||
el.style.left = `${x}px`;
|
||||
el.style.top = `${y}px`;
|
||||
@@ -55,18 +63,7 @@ export function tooltip(node: HTMLElement, text: string) {
|
||||
function move(e: MouseEvent) {
|
||||
// Keep tooltip near cursor while hovering
|
||||
if (!tooltipEl?.classList.contains('hu-tooltip--visible')) return;
|
||||
const el = getTooltipEl();
|
||||
const margin = 8;
|
||||
const w = el.offsetWidth;
|
||||
const h = el.offsetHeight;
|
||||
const x = Math.min(e.clientX + 12, window.innerWidth - w - margin);
|
||||
let y = e.clientY + 20;
|
||||
if (y + h + margin > window.innerHeight) {
|
||||
y = e.clientY - h - 12;
|
||||
}
|
||||
y = Math.max(margin, y);
|
||||
el.style.left = `${x}px`;
|
||||
el.style.top = `${y}px`;
|
||||
position(getTooltipEl(), e.clientX, e.clientY);
|
||||
}
|
||||
|
||||
function leave() {
|
||||
|
||||
Reference in New Issue
Block a user