# All files / src/_hooks Hotkey.ts

100% Statements 23/23
76.47% Branches 13/17
80% Functions 4/5
100% Lines 17/17

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
    7165x

    4609x
    4609x
    4609x
    4609x
    4609x
    4609x

    4609x
    4609x

    4609x

    59x
    10x
    10x
    10x

    4609x
    4609x

    4609x

     import { Scope, useEventListener } from './EventListener'

    type EventType = 'keydown' | 'keyup'

    interface Config {
      /**
       * @since 10.19.0
       */
      dependencies?: any[]
      /**
       * @since 10.19.0
       */
      event?: EventType
      /**
       * @since 10.19.0
       */
      handler: (event: KeyboardEvent) => void
      /**
       * @since 10.19.0
       */
      key: string | string[]
      /**
       * @since 10.19.0
       */
      preventDefault?: boolean
      /**
       * @since 10.19.0
       */
      scope?: Scope
      /**
       * @since 10.19.0
       */
      stopPropagation?: boolean
    }

    function bindHotkeys({
      dependencies = [],
      event = 'keydown',
      handler = () => {},
      key,
      preventDefault,
      stopPropagation,
    }: Config) {
      return (scope: Scope) => {
        const keys = Array.isArray(key) ? key : [key]

        useEventListener({
          dependencies,
          event,
          handler: (e: KeyboardEvent) => {
            if (keys.includes(e.key)) {
              handler(e)
              preventDefault && e.preventDefault()
              stopPropagation && e.stopPropagation()
            }
          },
          scope,
        })
      }
    }

    /**
     * @deprecatedSince 9.7.0
     * @deprecated Pass functions directly to JSX elements. For window events, add a new listener and remove it in an effect
     */
    export function useHotkey({ scope = window, ...config }: Config) {
      const scopes = Array.isArray(scope) ? scope : [scope]

      scopes.forEach(bindHotkeys(config))
    }