Skip to content

Commit

Permalink
feat(tooltip): auto-update position on scroll, resize, etc
Browse files Browse the repository at this point in the history
  • Loading branch information
tobyzerner committed Jun 11, 2023
1 parent f323e2e commit 587de3b
Showing 1 changed file with 22 additions and 17 deletions.
39 changes: 22 additions & 17 deletions src/tooltip/tooltip.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { computePosition, flip, shift } from '@floating-ui/dom';
import { autoUpdate, computePosition, flip, shift } from '@floating-ui/dom';
import { goodbye, hello } from 'hello-goodbye';

export default class TooltipElement extends HTMLElement {
Expand All @@ -9,8 +9,9 @@ export default class TooltipElement extends HTMLElement {
private parent?: HTMLElement;
private tooltip?: HTMLElement;
private timeout?: number;
private observer?: MutationObserver;
private disabledObserver?: MutationObserver;
private showing: boolean = false;
private cleanup?: () => void;

private onMouseEnter = this.afterDelay.bind(this, this.show);
private onFocus = this.show.bind(this);
Expand All @@ -31,15 +32,15 @@ export default class TooltipElement extends HTMLElement {
this.parent.addEventListener('blur', this.onBlur);
this.parent.addEventListener('pointerup', this.onPointerUp);

this.observer = new MutationObserver((mutations) => {
this.disabledObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.attributeName === 'disabled') {
this.hide();
}
});
});

this.observer.observe(this.parent, { attributes: true });
this.disabledObserver.observe(this.parent, { attributes: true });
}

document.addEventListener('keydown', this.onKeyDown);
Expand All @@ -64,7 +65,7 @@ export default class TooltipElement extends HTMLElement {
document.removeEventListener('keydown', this.onKeyDown);
document.removeEventListener('scroll', this.onBlur);

this.observer?.disconnect();
this.disabledObserver?.disconnect();
clearTimeout(this.timeout);
}

Expand Down Expand Up @@ -105,23 +106,27 @@ export default class TooltipElement extends HTMLElement {

tooltip.style.position = 'absolute';

computePosition(this.parent!, tooltip, {
placement:
(this.getAttribute('placement') as any) ||
TooltipElement.placement,
middleware: [shift(), flip()],
}).then(({ x, y, placement }) => {
Object.assign(tooltip.style, {
left: `${x}px`,
top: `${y}px`,
});
tooltip.dataset.placement = placement;
});
this.cleanup = autoUpdate(this.parent!, tooltip, () =>
computePosition(this.parent!, tooltip, {
placement:
(this.getAttribute('placement') as any) ||
TooltipElement.placement,
middleware: [shift(), flip()],
}).then(({ x, y, placement }) => {
Object.assign(tooltip.style, {
left: `${x}px`,
top: `${y}px`,
});
tooltip.dataset.placement = placement;
})
);
}

private hide() {
clearTimeout(this.timeout);

this.cleanup?.();

if (this.showing) {
this.showing = false;

Expand Down

0 comments on commit 587de3b

Please sign in to comment.