All files / utils compute-positions.ts

100% Statements 64/64
80% Branches 8/10
100% Functions 1/1
100% Lines 64/64

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 651x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 5x 5x 5x 5x 5x 3x 8x 1x 1x 2x 2x 2x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import { computePosition, offset, flip, shift, arrow } from '@floating-ui/dom'
import type { IComputePositions } from './compute-positions-types'
 
export const computeToolTipPosition = async ({
  elementReference = null,
  tooltipReference = null,
  tooltipArrowReference = null,
  place = 'top',
  offset: offsetValue = 10,
}: IComputePositions) => {
  if (!elementReference) {
    // elementReference can be null or undefined and we will not compute the position
    // eslint-disable-next-line no-console
    // console.error('The reference element for tooltip was not defined: ', elementReference)
    return { tooltipStyles: {}, tooltipArrowStyles: {} }
  }
 
  if (tooltipReference === null) {
    return { tooltipStyles: {}, tooltipArrowStyles: {} }
  }
 
  const middleware = [offset(Number(offsetValue)), flip(), shift({ padding: 5 })]
 
  if (tooltipArrowReference) {
    middleware.push(arrow({ element: tooltipArrowReference as HTMLElement }))
 
    return computePosition(elementReference as HTMLElement, tooltipReference as HTMLElement, {
      placement: place,
      middleware,
    }).then(({ x, y, placement, middlewareData }) => {
      const styles = { left: `${x}px`, top: `${y}px` }
 
      // @ts-ignore
      const { x: arrowX, y: arrowY } = middlewareData.arrow
 
      const staticSide = {
        top: 'bottom',
        right: 'left',
        bottom: 'top',
        left: 'right',
      }[placement.split('-')[0]]
 
      const arrowStyle = {
        left: arrowX != null ? `${arrowX}px` : '',
        top: arrowY != null ? `${arrowY}px` : '',
        right: '',
        bottom: '',
        // @ts-ignore
        [staticSide]: '-4px',
      }
 
      return { tooltipStyles: styles, tooltipArrowStyles: arrowStyle }
    })
  }
 
  return computePosition(elementReference as HTMLElement, tooltipReference as HTMLElement, {
    placement: 'bottom',
    middleware,
  }).then(({ x, y }) => {
    const styles = { left: `${x}px`, top: `${y}px` }
 
    return { tooltipStyles: styles, tooltipArrowStyles: {} }
  })
}