All files / molecule/modal/src MoleculeModalWithURLState.js

11.76% Statements 4/34
0% Branches 0/15
0% Functions 0/8
14.28% Lines 4/28

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            1x             1x                                                                                   1x   1x              
import {forwardRef, useEffect, useState} from 'react'
 
import PropTypes from 'prop-types'
 
import MoleculeModal from './MoleculeModal.js'
 
const checkHash = hash => typeof window !== 'undefined' && window.location.hash.includes(hash)
 
/**
 * It must be refactored with react-router hooks (in React Router > 5)
 * - useHistory
 * - useLocation
 */
const MoleculeModalWithURLState = forwardRef((props, ref) => {
  const {hash, openModalTrigger, onClose, ...rest} = props
  const {isOpen} = rest
  const [isPopStateChange, setIsPopStateChange] = useState(checkHash(hash))
 
  useEffect(() => {
    const getUrl = ({hash: hashName} = {}) => {
      const location = window.location
      const hash = hashName ? `#${hashName}` : ''
      return `${location.origin}${location.pathname}${location.search}${hash}`
    }
 
    const _handleStateChange = () => {
      if (isPopStateChange) return setIsPopStateChange(false)
 
      const nextUrl = isOpen ? getUrl({hash}) : getUrl()
      window.history.pushState({hash}, '', nextUrl)
    }
 
    _handleStateChange()
  }, [hash, isOpen]) // eslint-disable-line
 
  useEffect(() => {
    const _handlePopState = ev => {
      const hasHash = checkHash(hash)
      setIsPopStateChange(true)
 
      if (hasHash) openModalTrigger()
      else onClose()
    }
 
    if (checkHash(hash)) openModalTrigger()
 
    window.addEventListener('popstate', _handlePopState)
    return () => window.removeEventListener('popstate', _handlePopState)
  }, [hash]) // eslint-disable-line
 
  if (typeof window === 'undefined') return <MoleculeModal {...props} />
 
  return <MoleculeModal ref={ref} {...rest} onClose={onClose} />
})
 
MoleculeModalWithURLState.displayName = `${MoleculeModal.displayName}WithUrlState`
 
MoleculeModalWithURLState.propTypes = {
  hash: PropTypes.string.isRequired,
  openModalTrigger: PropTypes.func.isRequired,
  onClose: PropTypes.func.isRequired
}
 
export default MoleculeModalWithURLState