matchEvent.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { getSequenceManager, matchesKeyboardEvent } from '@tanstack/react-hotkeys'
  2. import { SHORTCUT_DEFINITIONS } from './registry'
  3. import type { RegistryDefinations } from './types'
  4. /**
  5. * Returns true if the given keyboard event matches a shortcut that is both:
  6. *
  7. * 1. **In the target registry** (defaults to every known shortcut, but callers
  8. * can pass a subset like `tableEditorRegistry` to scope the check)
  9. * 2. **Currently active and enabled** — i.e. a `useShortcut` is mounted for it
  10. * AND its `enabled` option is not `false`
  11. *
  12. * Chord sequences (e.g. `['G', 'T']`) match on any individual step, so
  13. * pressing `G` counts as a match while the chord is in flight.
  14. *
  15. * Respecting the live `enabled` state matters: if a shortcut is registered but
  16. * gated off (e.g. `enabled: !!snap.selectedCellPosition`), we must NOT suppress
  17. * the default behavior on its behalf, because the shortcut won't actually fire.
  18. */
  19. export function eventMatchesAnyShortcut(
  20. event: KeyboardEvent,
  21. registry: RegistryDefinations<string> = SHORTCUT_DEFINITIONS
  22. ): boolean {
  23. const scopedSteps = new Set(Object.values(registry).flatMap((def) => def.sequence))
  24. const activeRegistrations = getSequenceManager().registrations.state.values()
  25. for (const view of activeRegistrations) {
  26. if (view.options.enabled === false) continue
  27. const matches = view.sequence.some(
  28. (step) => scopedSteps.has(step) && matchesKeyboardEvent(event, step)
  29. )
  30. if (matches) return true
  31. }
  32. return false
  33. }