All files / modules/10-common/components/DynamicPopover DynamicPopover.tsx

78.08% Statements 57/73
62.5% Branches 35/56
66.67% Functions 10/15
79.17% Lines 57/72

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              631x 631x 631x   631x 631x                                                             631x                     89x 88x 88x 88x   88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x   88x         88x       88x   36x   1x 1x   1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x   1x 1x 1x         1x       1x       1x 1x               88x 37x           88x 36x     88x 36x 29x 1x     29x 1x         88x   88x                                                                  
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useState, useMemo } from 'react'
import { usePopper } from 'react-popper'
import cx from 'classnames'
import type * as PopperJS from '@popperjs/core'
import { useGlobalEventListener } from '@common/hooks'
import css from './DynamicPopover.module.scss'
 
declare global {
  interface WindowEventMap {
    UPDATE_POPOVER_POSITION: CustomEvent<string>
  }
}
export interface DynamicPopoverHandlerBinding<T> {
  show: (
    ref: Element | PopperJS.VirtualElement | string,
    data?: T,
    options?: { darkMode?: boolean; useArrows?: boolean; fixedPosition?: boolean; placement?: PopperJS.Placement },
    onHideCallBack?: () => void,
    isHoverView?: boolean
  ) => void
  hide: () => void
  isHoverView?: () => boolean
}
 
export interface DynamicPopoverProps<T> {
  render: (data: T) => JSX.Element
  className?: string
  darkMode?: boolean
  useArrows?: boolean
  fixedPosition?: boolean
  bind: (dynamicPopoverHandler: DynamicPopoverHandlerBinding<T>) => void
  closeOnMouseOut?: boolean
  hoverShowDelay?: number
  hoverHideDelay?: number
}
 
export function DynamicPopover<T>(props: DynamicPopoverProps<T>): JSX.Element {
  const {
    bind,
    render,
    className = '',
    darkMode = false,
    useArrows = true,
    fixedPosition = false,
    closeOnMouseOut,
    hoverShowDelay = 0,
    hoverHideDelay = 300
  } = props
  const [darkModeState, setDarkMode] = useState<boolean>(darkMode)
  const [useArrowsState, setArrowVisibility] = useState<boolean>(useArrows)
  const [fixedPositionState, setFixedPosition] = useState<boolean>(fixedPosition)
 
  const [popperElement, setPopperElement] = useState<HTMLElement | null>(null)
  const [data, setData] = useState<T>()
  const [arrowElement, setArrowElement] = useState<HTMLElement | null>(null)
  const [referenceElement, setReferenceElement] = useState<Element | PopperJS.VirtualElement | null>(null)
  const [visible, setVisibility] = useState<boolean>(false)
  const [hideCallback, setHideCallBack] = useState<() => void | undefined>()
  const [placement, setPlacement] = useState<PopperJS.Placement>('auto')
  const showTimerRef = React.useRef<number | null>(null)
  const hideTimerRef = React.useRef<number | null>(null)
  const mouseInRef = React.useRef<boolean>(false)
  const [isHoverView, setIsHoverView] = React.useState<boolean>()
 
  const { styles, attributes, forceUpdate } = usePopper(referenceElement, popperElement, {
    modifiers: [{ name: 'arrow', options: { element: arrowElement } }],
    placement
  })
 
  useGlobalEventListener('UPDATE_POPOVER_POSITION', () => {
    forceUpdate?.()
  })
 
  const handler = useMemo(
    () =>
      ({
        show: (ref, dataTemp, options, callback, hoverView) => {
          Eif (hideTimerRef.current) {
            window.clearTimeout(hideTimerRef.current)
          }
          showTimerRef.current = window.setTimeout(() => {
            setVisibility(true)
            setData(dataTemp)
            setIsHoverView(hoverView)
            Eif (typeof ref === 'string') {
              setReferenceElement(document.querySelector(ref))
            } else {
              setReferenceElement(ref)
            }
 
            Eif (options) {
              typeof options.darkMode === 'boolean' && setDarkMode(options.darkMode)
              typeof options.useArrows === 'boolean' && setArrowVisibility(options.useArrows)
              typeof options.fixedPosition === 'boolean' && setFixedPosition(options.fixedPosition)
              options.placement ? setPlacement(options.placement) : setPlacement('auto')
            }
            setHideCallBack(prev => {
              prev?.()
              return callback
            })
          }, hoverShowDelay)
        },
        hide: () => {
          Iif (showTimerRef.current) {
            window.clearTimeout(showTimerRef.current)
          }
 
          Iif (hideTimerRef.current) {
            window.clearTimeout(hideTimerRef.current)
          }
 
          Eif (!mouseInRef.current) {
            hideTimerRef.current = window.setTimeout(() => setVisibility(false), hoverHideDelay)
          }
        },
        isHoverView: () => isHoverView
      } as DynamicPopoverHandlerBinding<T>),
    [setVisibility, isHoverView, hoverHideDelay, hoverShowDelay]
  )
 
  React.useEffect(() => {
    Iif (!visible && hideCallback) {
      hideCallback()
      setHideCallBack(undefined)
    }
  }, [hideCallback, visible])
 
  React.useEffect(() => {
    bind(handler)
  }, [bind, handler])
 
  React.useEffect(() => {
    return () => {
      if (showTimerRef.current) {
        window.clearTimeout(showTimerRef.current)
      }
 
      if (hideTimerRef.current) {
        window.clearTimeout(hideTimerRef.current)
      }
    }
  }, [])
 
  const popperStyle = fixedPositionState ? { ...styles.popper, transform: 'initial' } : styles.popper
 
  return (
    <>
      {visible && (
        <span
          ref={setPopperElement}
          className={cx(css.dynamicPopover, { [css.dark]: darkModeState }, className)}
          style={popperStyle}
          {...attributes.popper}
          onMouseEnter={() => {
            if (closeOnMouseOut) {
              mouseInRef.current = true
              if (hideTimerRef.current) {
                window.clearTimeout(hideTimerRef.current)
              }
              setVisibility(true)
            }
          }}
          onMouseLeave={() => {
            if (closeOnMouseOut) {
              mouseInRef.current = false
              handler.hide()
            }
          }}
        >
          {data && render(data)}
          {useArrowsState && (
            <div className={css.arrow} data-popper-arrow="true" ref={setArrowElement} style={styles.arrow} />
          )}
        </span>
      )}
    </>
  )
}