All files / src/components details.js

0% Statements 0/18
0% Branches 0/11
0% Functions 0/6
0% Lines 0/16

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                                                                                                                                       
import React from 'react'
import styled from 'styled-components'
 
// The <details> element is not yet supported in Edge so we have to use a polyfill.
// We have to check if window is defined before importing the polyfill
// so the code doesn’t run while Gatsby is building.
if (typeof window !== 'undefined') {
  import('details-element-polyfill')
}
 
// TODO: Replace this Details component with the one from @primer/components when 14.0.0 is released.
// Reference: https://github.com/primer/components/pull/499
 
const DetailsReset = styled.details`
  & > summary {
    list-style: none;
  }
 
  & > summary::-webkit-details-marker {
    display: none;
  }
 
  & > summary::before {
    display: none;
  }
`
 
function getRenderer(children) {
  return typeof children === 'function' ? children : () => children
}
 
function Details({children, overlay, render = getRenderer(children), ...rest}) {
  const [open, setOpen] = React.useState(Boolean(rest.open))
 
  function toggle(event) {
    if (event) event.preventDefault()
    if (overlay) {
      openMenu()
    } else {
      setOpen(!open)
    }
  }
 
  function openMenu() {
    if (!open) {
      setOpen(true)
      document.addEventListener('click', closeMenu)
    }
  }
 
  function closeMenu() {
    setOpen(false)
    document.removeEventListener('click', closeMenu)
  }
 
  return (
    <DetailsReset {...rest} open={open}>
      {render({open, toggle})}
    </DetailsReset>
  )
}
 
Details.defaultProps = {
  overlay: false,
}
 
export default Details