{"size": 1781, "ext": "js", "max_stars_repo_path": "components/radio-item.js", "max_stars_repo_name": "sickerman/hull-marketing-starter", "max_stars_repo_stars_event_min_datetime": "2021-11-18T00:24:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T00:29:15.000Z", "max_issues_repo_path": "components/radio-item.js", "max_issues_repo_name": "sickerman/hull-marketing-starter", "max_issues_repo_issues_event_min_datetime": "2021-11-09T22:50:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T19:49:04.000Z", "max_forks_repo_path": "components/radio-item.js", "max_forks_repo_name": "sickerman/hull-marketing-starter", "max_forks_repo_forks_event_min_datetime": "2021-11-18T00:24:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T16:21:59.000Z"}
{"max_stars_count": 3, "max_issues_count": 6, "max_forks_count": 5, "avg_line_length": 20.2386363636, "max_line_length": 74, "alphanum_fraction": 0.5918023582}
import { useRef, useEffect } from 'react'

import { wrap } from '@lib/helpers'

import {
  useRadioGroupContext,
  useRadioItemContext,
} from '@components/radio-group'

export default function RadioItem({ title, value, children, ...rest }) {
  const groupContext = useRadioGroupContext()
  const itemContext = useRadioItemContext()

  const isChecked = groupContext.value === value
  const itemRef = useRef()
  const isInitialMount = useRef(true)

  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false
      return
    }

    if (isChecked) {
      itemRef.current.focus()
    }
  }, [isChecked])

  function handleClick() {
    groupContext.onChange(value)
  }

  function handleKeyDown(ev) {
    const { items, onChange } = groupContext
    const index = itemContext

    let flag = false

    // listen for one of our key presses
    switch (ev.code) {
      case 'Space':
      case 'Enter': {
        onChange(value)
        flag = true
        break
      }

      case 'ArrowUp':
      case 'ArrowLeft': {
        onChange(items[wrap(index - 1, items.length)].props.value)
        flag = true
        break
      }

      case 'ArrowDown':
      case 'ArrowRight': {
        onChange(items[wrap(index + 1, items.length)].props.value)
        flag = true
        break
      }

      default:
        break
    }

    // if one of our keys were pressed (flagged), prevent default behavior
    if (flag) {
      ev.stopPropagation()
      ev.preventDefault()
    }
  }

  return (
    <button
      ref={itemRef}
      role="radio"
      title={title}
      tabIndex={isChecked ? 0 : -1}
      aria-checked={isChecked}
      onClick={handleClick}
      onKeyDown={handleKeyDown}
      {...rest}
    >
      {children}
    </button>
  )
}
