All files / components/TooltipController TooltipController.tsx

43% Statements 83/193
57.14% Branches 4/7
20% Functions 1/5
43% Lines 83/193

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 189 190 191 192 193 1941x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x                     5x 5x                                                                                                               5x 5x                 5x 5x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   4x                                                                         5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x  
import { useEffect, useState } from 'react'
import { Tooltip } from 'components/Tooltip'
import type {
  EventsType,
  PlacesType,
  VariantType,
  WrapperType,
} from 'components/Tooltip/TooltipTypes'
import { dataAttributesKeys } from './constants'
import type { ITooltipController } from './TooltipControllerTypes'
 
const TooltipController = ({
  id,
  anchorId,
  content,
  html,
  className,
  classNameArrow,
  variant = 'dark',
  place = 'top',
  offset = 10,
  wrapper = 'div',
  children = null,
  events = ['hover'],
  delayShow = 0,
  delayHide = 0,
  getContent,
  isOpen,
  setIsOpen,
}: ITooltipController) => {
  const [tooltipContent, setTooltipContent] = useState(content || html)
  const [tooltipPlace, setTooltipPlace] = useState(place)
  const [tooltipVariant, setTooltipVariant] = useState(variant)
  const [tooltipOffset, setTooltipOffset] = useState(offset)
  const [tooltipDelayShow, setTooltipDelayShow] = useState(delayShow)
  const [tooltipDelayHide, setTooltipDelayHide] = useState(delayHide)
  const [tooltipWrapper, setTooltipWrapper] = useState<WrapperType>(wrapper)
  const [tooltipEvents, setTooltipEvents] = useState<EventsType[]>(events)
  const [isHtmlContent, setIsHtmlContent] = useState<boolean>(Boolean(html))
 
  const getDataAttributesFromAnchorElement = (elementReference: HTMLElement) => {
    const dataAttributes = elementReference?.getAttributeNames().reduce((acc, name) => {
      if (name.includes('data-tooltip-')) {
        ;(acc as any)[name] = elementReference?.getAttribute(name)
      }

      return acc
    }, {})

    return dataAttributes
  }
 
  const applyAllDataAttributesFromAnchorElement = (dataAttributes: {
    [key: string]: string | number | boolean
  }) => {
    const keys = Object.keys(dataAttributes)
    let formatedKey = null

    const handleDataAttributes = {
      place: (value: PlacesType) => {
        setTooltipPlace(value)
      },
      content: (value: string) => {
        setIsHtmlContent(true)
        if (getContent) {
          setTooltipContent(getContent(value))
        } else {
          setTooltipContent(value)
        }
      },
      html: (value: string) => {
        setIsHtmlContent(true)
        if (getContent) {
          setTooltipContent(getContent(value))
        } else {
          setTooltipContent(value)
        }
      },
      variant: (value: VariantType) => {
        setTooltipVariant(value)
      },
      offset: (value: number) => {
        setTooltipOffset(value)
      },
      wrapper: (value: WrapperType) => {
        setTooltipWrapper(value)
      },
      events: (value: string) => {
        const parsedEvents = value.split(' ')
        setTooltipEvents(parsedEvents as EventsType[])
      },
      'delay-show': (value: number) => {
        setTooltipDelayShow(Number(value))
      },
      'delay-hide': (value: number) => {
        setTooltipDelayHide(Number(value))
      },
    }

    keys.forEach((key) => {
      formatedKey = key.replace('data-tooltip-', '')

      if (dataAttributesKeys.includes(formatedKey)) {
        // @ts-ignore
        handleDataAttributes[formatedKey](dataAttributes[key])
      }
    })
  }
 
  const getElementSpecificAttributeKeyAndValueParsed = ({
    element,
    attributeName,
  }: {
    element: HTMLElement
    attributeName: string
  }) => {
    return { [attributeName]: element.getAttribute(attributeName) }
  }
 
  useEffect(() => {
    if (!anchorId) {
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      return () => {}
    }
 
    const elementReference = document.querySelector(`#${anchorId}`)
 
    if (!elementReference) {
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      return () => {}
    }

    if (content && getContent) {
      setTooltipContent(getContent(content))
    }

    // do not check for subtree and childrens, we only want to know attribute changes
    // to stay watching `data-attributes` from anchor element
    const observerConfig = { attributes: true, childList: false, subtree: false }

    const observerCallback = (mutationList: any) => {
      mutationList.forEach((mutation: any) => {
        if (mutation.type === 'attributes') {
          const attributeKeyAndValue = getElementSpecificAttributeKeyAndValueParsed({
            element: elementReference as HTMLElement,
            attributeName: mutation.attributeName,
          })

          applyAllDataAttributesFromAnchorElement(
            attributeKeyAndValue as { [key: string]: string | number | boolean },
          )
        }
      })
    }

    // Create an observer instance linked to the callback function
    const observer = new MutationObserver(observerCallback)

    // Start observing the target node for configured mutations
    observer.observe(elementReference, observerConfig)

    const dataAttributes = getDataAttributesFromAnchorElement(elementReference as HTMLElement)

    applyAllDataAttributesFromAnchorElement(dataAttributes)

    return () => {
      // Remove the observer when the tooltip is destroyed
      observer.disconnect()
    }
  }, [anchorId])
 
  const props = {
    id,
    anchorId,
    className,
    classNameArrow,
    content: tooltipContent,
    isHtmlContent,
    place: tooltipPlace,
    variant: tooltipVariant,
    offset: tooltipOffset,
    wrapper: tooltipWrapper,
    events: tooltipEvents,
    delayShow: tooltipDelayShow,
    delayHide: tooltipDelayHide,
    isOpen,
    setIsOpen,
  }
 
  return children ? <Tooltip {...props}>{children}</Tooltip> : <Tooltip {...props} />
}
 
export default TooltipController