| 29 | } |
| 30 | |
| 31 | export class Tooltip implements Mountable { |
| 32 | readonly root: HTMLElement; |
| 33 | private popper: PopperInstance | null = null; |
| 34 | private mouseEnter = () => this.show(); |
| 35 | private mouseLeave = () => this.hide(); |
| 36 | private focusIn = () => this.show(); |
| 37 | private focusOut = () => this.hide(); |
| 38 | |
| 39 | constructor( |
| 40 | private target: HTMLElement, |
| 41 | private text: string, |
| 42 | private options: TooltipOptions = {} |
| 43 | ) { |
| 44 | this.root = parseHtml(html`<div class="at-tooltip" role="tooltip">${text}</div>`); |
| 45 | this.target.addEventListener('mouseenter', this.mouseEnter); |
| 46 | this.target.addEventListener('mouseleave', this.mouseLeave); |
| 47 | this.target.addEventListener('focusin', this.focusIn); |
| 48 | this.target.addEventListener('focusout', this.focusOut); |
| 49 | } |
| 50 | |
| 51 | setText(text: string): void { |
| 52 | this.text = text; |
| 53 | this.root.textContent = text; |
| 54 | } |
| 55 | |
| 56 | private show(): void { |
| 57 | if (!this.text) { |
| 58 | return; |
| 59 | } |
| 60 | if (!this.root.parentElement) { |
| 61 | document.body.appendChild(this.root); |
| 62 | } |
| 63 | if (!this.popper) { |
| 64 | this.popper = createPopper(this.target, this.root, { |
| 65 | placement: this.options.placement ?? 'top', |
| 66 | modifiers: [{ name: 'offset', options: { offset: [0, 6] } }] |
| 67 | }); |
| 68 | } else { |
| 69 | this.popper.update(); |
| 70 | } |
| 71 | this.root.classList.add('visible'); |
| 72 | } |
| 73 | |
| 74 | private hide(): void { |
| 75 | this.root.classList.remove('visible'); |
| 76 | } |
| 77 | |
| 78 | dispose(): void { |
| 79 | this.target.removeEventListener('mouseenter', this.mouseEnter); |
| 80 | this.target.removeEventListener('mouseleave', this.mouseLeave); |
| 81 | this.target.removeEventListener('focusin', this.focusIn); |
| 82 | this.target.removeEventListener('focusout', this.focusOut); |
| 83 | if (this.popper) { |
| 84 | this.popper.destroy(); |
| 85 | this.popper = null; |
| 86 | } |
| 87 | this.root.remove(); |
| 88 | } |