createViewportHandler

Wraps a useHotkeys handler so it runs only when the focus is inside the Viewport or nowhere. Use it for text formatting shortcuts, such as bold and italic, which must work while the user edits text on a page but not while they type in your own inputs.

const handler = createViewportHandler(handler)
  • Takes a HotkeyHandler and returns a new one. While the focus is outside the viewport, the returned handler skips yours and returns false, so the key keeps its default effect.
  • The wrapper only checks the focus: your handler still decides whether the action applies, for example with isApplicable from useSelectionTextStyle.
  • For block shortcuts, such as deleting or moving the selected blocks, use createUnfocusedHandler: it keeps them inactive while the user edits text.

Example

import { useMemo } from 'react'
import { createViewportHandler, useHotkeys, useSelectionTextStyle } from '@sdk-pdf/react'

function useTextStyleHotkeys() {
  const { isApplicable, isBold, isItalic } = useSelectionTextStyle()

  useHotkeys(
    useMemo(
      () =>
        isApplicable && {
          'Mod-b': createViewportHandler(() => isBold.set(!isBold.value)),
          'Mod-i': createViewportHandler(() => isItalic.set(!isItalic.value)),
        },
      [isApplicable, isBold, isItalic]
    )
  )
}

On this page