All files / components/tooltip Tooltip.ts

76.11% Statements 51/67
59.25% Branches 16/27
50% Functions 9/18
76.11% Lines 51/67

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188  1x 1x   1x               13x   13x   13x   13x   13x   13x   13x   13x   13x       13x 13x 13x 13x 13x 13x     13x 13x 13x 13x 13x 13x 13x       13x 13x 13x 13x 13x     13x 13x 13x     13x     13x     13x     13x                 1x       1x   1x                                       13x 52x     13x 26x                               13x                     13x 13x                             13x                               1x   13x                           1x  
import { Directive } from 'vue';
import useGeneratedId from '../../composables/useGeneratedId';
import { computePosition, flip, shift, hide, offset, autoUpdate, Placement } from '@floating-ui/vue';
import { TooltipOptions } from '../../types';
import './Tooltip.less';
 
interface StatefulDirectiveElement extends HTMLElement {
	// eslint-disable-next-line no-use-before-define
	tooltip?: Tooltip
}
 
class Tooltip {
	private referenceElement: StatefulDirectiveElement;
 
	private tooltipElement: HTMLElement;
 
	private textContent: string;
 
	private placement: Placement;
 
	private autoUpdateCleanup: () => void;
 
	private referenceElementHandlers: Record<string, ( () => void )>;
 
	private tooltipElementHandlers: Record<string, ( () => void )>;
 
	private escapeHandler: ( event: KeyboardEvent ) => void;
 
	private timeoutId: ReturnType<typeof setTimeout>|null;
 
	constructor( referenceElement: StatefulDirectiveElement, options: TooltipOptions ) {
		// Initialize tooltip instance properties
		const doc = referenceElement.ownerDocument;
		const tooltipId = useGeneratedId( 'tooltip' );
		this.referenceElement = referenceElement;
		this.textContent = options.textContent;
		this.placement = options.placement ?? 'bottom';
		this.timeoutId = null;
 
		// Set up DOM elements
		this.tooltipElement = doc.createElement( 'div' );
		this.tooltipElement.classList.add( 'cdx-tooltip' );
		this.tooltipElement.role = 'tooltip';
		this.tooltipElement.id = tooltipId;
		this.referenceElement.setAttribute( 'aria-describedby', tooltipId );
		this.tooltipElement.textContent = this.textContent;
		this.referenceElement.parentElement?.appendChild( this.tooltipElement );
 
		// Event handlers are stashed in an an object for convenient setup/teardown
		// 1. Reference element handlers
		this.referenceElementHandlers = {};
		this.referenceElementHandlers.mouseenter = this.show.bind( this );
		this.referenceElementHandlers.mouseleave = this.hideAfterDelay.bind( this );
		this.referenceElementHandlers.focus = this.show.bind( this );
		this.referenceElementHandlers.blur = this.hide.bind( this );
 
		// 2. Tooltip element handlers
		this.tooltipElementHandlers = {};
		this.tooltipElementHandlers.mouseenter = this.show.bind( this );
		this.tooltipElementHandlers.mouseleave = this.hideAfterDelay.bind( this );
 
		// 3. Escape key handler (global) requires separate treatment
		this.escapeHandler = this.onKeyup.bind( this );
 
		// Add the event listeners (except the escape key listener) to the document
		this.addEventListeners();
 
		// Set up autoUpdate and stash a reference to the cleanup function that is returned
		this.autoUpdateCleanup = autoUpdate(
			this.referenceElement,
			this.tooltipElement,
			() => this.update()
		);
	}
 
	private isVisible() {
		return this.tooltipElement.style.display === 'block';
	}
 
	private show() {
		Iif ( this.timeoutId ) {
			clearTimeout( this.timeoutId );
		}
 
		this.tooltipElement.style.display = 'block';
		// Add the escape key listener when the tooltip is displayed
		this.tooltipElement.ownerDocument.addEventListener( 'keyup', this.escapeHandler );
	}
 
	private hide() {
		this.tooltipElement.style.display = 'none';
		// Remove the escape key listener when the tooltip is hidden
		this.tooltipElement.ownerDocument.removeEventListener( 'keyup', this.escapeHandler );
	}
 
	private hideAfterDelay() {
		this.timeoutId = setTimeout( this.hide.bind( this ), 250 );
	}
 
	private onKeyup( event: KeyboardEvent ) {
		Iif ( event.key === 'Escape' && this.isVisible() ) {
			this.hide();
		}
	}
 
	private addEventListeners() {
		Object.keys( this.referenceElementHandlers ).forEach( ( k ) => {
			this.referenceElement.addEventListener( k, this.referenceElementHandlers[ k ] );
		} );
 
		Object.keys( this.tooltipElementHandlers ).forEach( ( k ) => {
			this.tooltipElement.addEventListener( k, this.tooltipElementHandlers[ k ] );
		} );
	}
 
	private removeEventListeners() {
		Object.keys( this.referenceElementHandlers ).forEach( ( k ) => {
			this.referenceElement.removeEventListener( k, this.referenceElementHandlers[ k ] );
		} );
 
		Object.keys( this.tooltipElementHandlers ).forEach( ( k ) => {
			this.tooltipElement.removeEventListener( k, this.tooltipElementHandlers[ k ] );
		} );
	}
 
	private update() {
		// eslint-disable-next-line @typescript-eslint/no-floating-promises
		computePosition( this.referenceElement, this.tooltipElement, {
			placement: this.placement,
			middleware: [
				offset( 4 ),
				flip(),
				shift(),
				hide()
			]
		} ).then( ( { x, y, middlewareData } ) => {
			// Tooltip placement based on middleware data - considers flipping since the
			// offset property is calculated after flipping.
			const finalPlacement = middlewareData.offset?.placement ?? this.placement;
			const opposites: Record<Placement, string> = {
				left: 'right',
				'left-start': 'right',
				'left-end': 'right',
				top: 'bottom',
				'top-start': 'bottom',
				'top-end': 'bottom',
				bottom: 'top',
				'bottom-start': 'top',
				'bottom-end': 'top',
				right: 'left',
				'right-start': 'left',
				'right-end': 'left'
			};
 
			Object.assign( this.tooltipElement.style, {
				left: `${ x }px`,
				top: `${ y }px`,
				visibility: middlewareData.hide?.referenceHidden ? 'hidden' : 'visible',
				transformOrigin: opposites[ finalPlacement ]
			} );
		} );
	}
 
	public remove() {
		this.tooltipElement.remove();
		this.autoUpdateCleanup();
		this.removeEventListeners();
	}
}
 
const CdxTooltip : Directive = {
	mounted( el: StatefulDirectiveElement, { value, arg } ) {
		el.tooltip = new Tooltip( el, {
			textContent: String( value ),
			placement: arg as Placement
		} );
 
	},
 
	beforeUnmount( el: StatefulDirectiveElement ) {
		Iif ( el.tooltip ) {
			el.tooltip.remove();
		}
	}
};
 
export default CdxTooltip;