createUnfocusedHandler

Wraps a useHotkeys handler so it runs only when no element has focus. Use it for block shortcuts, such as Backspace to delete the selected blocks or the arrow keys to move them, so they stay out of the way while the user edits text or types in a form field or in your own inputs.

const handler = createUnfocusedHandler(handler)
  • Takes a HotkeyHandler and returns a new one. While an element has focus, the returned handler skips yours and returns false, so the key keeps its default effect, such as deleting a character in a text field.
  • Selecting blocks in the viewport doesn't move the focus to an element, so block shortcuts work right after a click on a block.
  • For text formatting shortcuts, which must also work while editing text in the viewport, use createViewportHandler.

Example

import { useMemo } from 'react'
import {
  createUnfocusedHandler,
  useDeleteSelection,
  useHotkeys,
  useMoveSelection,
} from '@sdk-pdf/react'

function useBlockHotkeys() {
  const deleteSelection = useDeleteSelection()
  const moveSelection = useMoveSelection()

  useHotkeys(
    useMemo(
      () => ({
        Backspace: createUnfocusedHandler(deleteSelection),
        Delete: createUnfocusedHandler(deleteSelection),
        ArrowUp: createUnfocusedHandler(() => moveSelection('up')),
        ArrowDown: createUnfocusedHandler(() => moveSelection('down')),
      }),
      [deleteSelection, moveSelection]
    )
  )
}

On this page