Skip to content

KeyboardProvider

Context provider that enables scoped keyboard handling for @diffgazer/keys hooks.

Context provider that enables scoped keyboard handling. Wraps your app (or a subtree) and listens for keydown events on the provider document's window.

tsx
import { KeyboardProvider } from "@diffgazer/keys";

function App() {
  return (
    <KeyboardProvider>
      <YourApp />
    </KeyboardProvider>
  );
}

Props

PropTypeDescription
childrenReactNodeRequired. Child elements.

Behavior

  • Creates a "global" scope on mount. All handlers registered without a scope push land here.
  • Maintains a scope stack. Declarative scopes follow React tree order, imperative pushScope calls sit above declarative scopes, and only handlers in the active scope fire.
  • Skips events where event.defaultPrevented is already true.
  • Skips handlers for text-editable targets (text-like input, textarea, and editable content) unless allowInInput is set. Non-text controls such as select, checkbox, radio, range, and button inputs are allowed by default.
  • When a handler specifies containerRef + focusWithinOnly, only fires if the event target is inside that container.
  • Handler priority: iterates entries from last-registered to first. The first handler that does not decline wins; a handler can return false to decline the match and continue to the next lower-priority handler.
  • preventDefault contract. When a handler with preventDefault enabled accepts the match (returns anything other than false), event.preventDefault() runs after that handler returns. A declining handler never prevents the default, so native behavior survives until a handler actually handles the key.
  • Errors in handlers are caught and logged: [@diffgazer/keys] Handler error for "${hotkey}": ...
  • Renders one extra DOM node: a hidden <span> before {children}, used to resolve the document the provider lives in so an iframe-mounted provider binds to that window. It is out of layout and out of the accessibility tree, but it does shift :first-child / :nth-child() selectors written against the provider's own children.

Provider-Aware Hooks

The following hooks participate in KeyboardProvider scope and dispatch: