useHotkeys
Installs window-level keyboard shortcuts. See Building a PDF application for the hotkeys walkthrough.
useHotkeys(mapping)mappingis a record of key strings to handlers. Keys are modifier chains ending with the key name, such asMod-z,Shift-Mod-z, orBackspace;Modmeans Cmd on macOS and Ctrl elsewhere.- Each handler is a
HotkeyHandler: a function with no arguments returningboolean | void. A handled shortcut consumes the event; returnfalseto report it unhandled, so the browser default is kept and the key reaches whatever else expects it. - The shortcuts listen on the whole window, including while the user types in an input. Wrap a handler with createUnfocusedHandler for block shortcuts, such as Backspace deleting the selected blocks, or with createViewportHandler for text formatting shortcuts, so they don't fire where they don't belong.
- The mapping must be memoized, or the listener re-installs on every render.
- Pass a falsy value instead of a mapping to disable the hotkeys, such as while a modal is open.
Example
import { useMemo } from 'react'
import {
createUnfocusedHandler,
useDeleteSelection,
useHotkeys,
useUndoRedo,
} from '@sdk-pdf/react'
function useDocumentHotkeys({ areDisabled }: { areDisabled: boolean }) {
const { undo, redo } = useUndoRedo()
const deleteSelection = useDeleteSelection()
useHotkeys(
useMemo(
() =>
!areDisabled && {
'Mod-z': undo,
'Shift-Mod-z': redo,
Backspace: createUnfocusedHandler(deleteSelection),
},
[areDisabled, undo, redo, deleteSelection]
)
)
}