All Downloads are FREE. Search and download functionalities are using the official Maven repository.

package.src.useRecordHotkeys.ts Maven / Gradle / Ivy

import { useCallback, useState } from 'react'
import { mapKey } from './parseHotkeys'

export default function useRecordHotkeys() {
  const [keys, setKeys] = useState(new Set())
  const [isRecording, setIsRecording] = useState(false)

  const handler = useCallback((event: KeyboardEvent) => {
    if (event.key === undefined) {
      // Synthetic event (e.g., Chrome autofill).  Ignore.
      return
    }

    event.preventDefault()
    event.stopPropagation()

    setKeys((prev) => {
      const newKeys = new Set(prev)

      newKeys.add(mapKey(event.code))

      return newKeys
    })
  }, [])

  const stop = useCallback(() => {
    if (typeof document !== 'undefined') {
      document.removeEventListener('keydown', handler)

      setIsRecording(false)
    }
  }, [handler])

  const start = useCallback(() => {
    setKeys(new Set())

    if (typeof document !== 'undefined') {
      stop()

      document.addEventListener('keydown', handler)

      setIsRecording(true)
    }
  }, [handler, stop])

  const resetKeys = useCallback(() => {
    setKeys(new Set())
  }, [])

  return [keys, { start, stop, resetKeys, isRecording }] as const
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy