@tanstack/hotkeys 0.6.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/hotkey-manager.cjs +16 -0
  2. package/dist/hotkey-manager.cjs.map +1 -1
  3. package/dist/hotkey-manager.d.cts +29 -2
  4. package/dist/hotkey-manager.d.ts +29 -2
  5. package/dist/hotkey-manager.js +16 -1
  6. package/dist/hotkey-manager.js.map +1 -1
  7. package/dist/hotkey-recorder.cjs +4 -0
  8. package/dist/hotkey-recorder.cjs.map +1 -1
  9. package/dist/hotkey-recorder.d.cts +8 -0
  10. package/dist/hotkey-recorder.d.ts +8 -0
  11. package/dist/hotkey-recorder.js +4 -0
  12. package/dist/hotkey-recorder.js.map +1 -1
  13. package/dist/hotkey-sequence-recorder.cjs +4 -0
  14. package/dist/hotkey-sequence-recorder.cjs.map +1 -1
  15. package/dist/hotkey-sequence-recorder.d.cts +8 -0
  16. package/dist/hotkey-sequence-recorder.d.ts +8 -0
  17. package/dist/hotkey-sequence-recorder.js +4 -0
  18. package/dist/hotkey-sequence-recorder.js.map +1 -1
  19. package/dist/hotkey.d.cts +22 -3
  20. package/dist/hotkey.d.ts +22 -3
  21. package/dist/index.cjs +1 -0
  22. package/dist/index.d.cts +3 -3
  23. package/dist/index.d.ts +3 -3
  24. package/dist/index.js +2 -2
  25. package/dist/manager.utils.cjs +1 -0
  26. package/dist/manager.utils.js +1 -1
  27. package/dist/sequence-manager.cjs +5 -1
  28. package/dist/sequence-manager.cjs.map +1 -1
  29. package/dist/sequence-manager.d.cts +2 -0
  30. package/dist/sequence-manager.d.ts +2 -0
  31. package/dist/sequence-manager.js +5 -1
  32. package/dist/sequence-manager.js.map +1 -1
  33. package/package.json +1 -1
  34. package/src/hotkey-manager.ts +42 -0
  35. package/src/hotkey-recorder.ts +20 -0
  36. package/src/hotkey-sequence-recorder.ts +20 -0
  37. package/src/hotkey.ts +22 -2
  38. package/src/sequence-manager.ts +7 -0
@@ -1,4 +1,5 @@
1
1
  const require_constants = require('./constants.cjs');
2
+ const require_manager_utils = require('./manager.utils.cjs');
2
3
  const require_recorder_chord = require('./recorder-chord.cjs');
3
4
  let _tanstack_store = require("@tanstack/store");
4
5
 
@@ -75,6 +76,9 @@ var HotkeySequenceRecorder = class {
75
76
  }));
76
77
  const handler = (event) => {
77
78
  if (!this.#keydownHandler) return;
79
+ if (this.#options.ignoreInputs !== false) {
80
+ if (require_manager_utils.isInputElement(typeof document !== "undefined" ? document.activeElement : null) && event.key !== "Escape") return;
81
+ }
78
82
  event.preventDefault();
79
83
  event.stopPropagation();
80
84
  if (event.key === "Escape") {
@@ -1 +1 @@
1
- {"version":3,"file":"hotkey-sequence-recorder.cjs","names":["Store","#options","#platform","detectPlatform","#idleTimer","#clearIdleTimer","#keydownHandler","#finishWithoutCommitCallback","#patchSteps","#scheduleIdleTimer","hotkeyChordFromKeydown","#addListener","#removeListener"],"sources":["../src/hotkey-sequence-recorder.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { detectPlatform } from './constants'\nimport { hotkeyChordFromKeydown } from './recorder-chord'\nimport type { HotkeySequence } from './sequence-manager'\n\n/**\n * How the user can commit a recorded sequence from the keyboard.\n * - `'enter'`: plain Enter (no modifiers) commits when at least one step exists.\n * - `'none'`: only {@link HotkeySequenceRecorder.commit} finishes recording (or idle timeout if set).\n */\nexport type HotkeySequenceRecorderCommitKeys = 'enter' | 'none'\n\n/**\n * State interface for the HotkeySequenceRecorder.\n */\nexport interface HotkeySequenceRecorderState {\n /** Whether recording is currently active */\n isRecording: boolean\n /** Chords captured so far in the current recording session */\n steps: HotkeySequence\n /** The last successfully committed sequence, or null if none / after starting a new session */\n recordedSequence: HotkeySequence | null\n}\n\n/**\n * Options for configuring a HotkeySequenceRecorder instance.\n */\nexport interface HotkeySequenceRecorderOptions {\n /** Callback when a sequence is successfully recorded (including empty array when cleared) */\n onRecord: (sequence: HotkeySequence) => void\n /** Optional callback when recording is cancelled (Escape pressed) */\n onCancel?: () => void\n /** Optional callback when the sequence is cleared (Backspace/Delete with no steps) */\n onClear?: () => void\n /**\n * Whether plain Enter commits the current steps. Ignored when {@link commitKeys} is `'none'`.\n * @default true\n */\n commitOnEnter?: boolean\n /**\n * Keyboard commit mode. When `'none'`, use {@link HotkeySequenceRecorder.commit} (and optional idle timeout).\n * @default 'enter'\n */\n commitKeys?: HotkeySequenceRecorderCommitKeys\n /**\n * Milliseconds of inactivity after the **last completed chord** before auto-committing.\n * The timer does not run while waiting for the first chord (`steps.length === 0`).\n */\n idleTimeoutMs?: number\n}\n\nconst defaultHotkeySequenceRecorderOptions: Pick<\n HotkeySequenceRecorderOptions,\n 'commitOnEnter' | 'commitKeys'\n> = {\n commitOnEnter: true,\n commitKeys: 'enter',\n}\n\nfunction resolvedCommitOnEnter(\n options: HotkeySequenceRecorderOptions,\n): boolean {\n if (options.commitKeys === 'none') {\n return false\n }\n return options.commitOnEnter !== false\n}\n\n/**\n * Framework-agnostic class for recording multi-chord sequences (Vim-style shortcuts).\n *\n * Each step is captured like a single hotkey chord. Press **Enter** (no modifiers) to commit\n * when {@link HotkeySequenceRecorderOptions.commitKeys} is `'enter'` (default), **Escape** to cancel,\n * **Backspace/Delete** to remove the last step or clear when empty.\n */\nexport class HotkeySequenceRecorder {\n readonly store: Store<HotkeySequenceRecorderState> =\n new Store<HotkeySequenceRecorderState>({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n })\n\n #keydownHandler: ((event: KeyboardEvent) => void) | null = null\n #options: HotkeySequenceRecorderOptions\n #platform: 'mac' | 'windows' | 'linux'\n #idleTimer: ReturnType<typeof setTimeout> | null = null\n\n constructor(options: HotkeySequenceRecorderOptions) {\n this.#options = {\n ...defaultHotkeySequenceRecorderOptions,\n ...options,\n }\n this.#platform = detectPlatform()\n }\n\n setOptions(options: Partial<HotkeySequenceRecorderOptions>): void {\n this.#options = {\n ...defaultHotkeySequenceRecorderOptions,\n ...this.#options,\n ...options,\n }\n }\n\n #clearIdleTimer(): void {\n if (this.#idleTimer !== null) {\n clearTimeout(this.#idleTimer)\n this.#idleTimer = null\n }\n }\n\n #scheduleIdleTimer(): void {\n this.#clearIdleTimer()\n const ms = this.#options.idleTimeoutMs\n if (ms === undefined || ms <= 0) {\n return\n }\n const steps = this.store.state.steps\n if (steps.length === 0) {\n return\n }\n this.#idleTimer = setTimeout(() => {\n this.#idleTimer = null\n if (!this.#keydownHandler) {\n return\n }\n if (this.store.state.steps.length >= 1) {\n this.commit()\n }\n }, ms)\n }\n\n #patchSteps(updater: (prev: HotkeySequence) => HotkeySequence): void {\n this.store.setState((s) => ({\n ...s,\n steps: updater(s.steps),\n }))\n }\n\n start(): void {\n if (this.#keydownHandler) {\n return\n }\n\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: true,\n steps: [],\n recordedSequence: null,\n }))\n\n const handler = (event: KeyboardEvent) => {\n if (!this.#keydownHandler) {\n return\n }\n\n event.preventDefault()\n event.stopPropagation()\n\n if (event.key === 'Escape') {\n this.cancel()\n return\n }\n\n if (event.key === 'Backspace' || event.key === 'Delete') {\n if (\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.metaKey\n ) {\n const steps = this.store.state.steps\n if (steps.length === 0) {\n this.#options.onClear?.()\n this.#options.onRecord([])\n this.#finishWithoutCommitCallback()\n return\n }\n this.#patchSteps((prev) => prev.slice(0, -1))\n const next = this.store.state.steps\n if (next.length === 0) {\n this.#clearIdleTimer()\n } else {\n this.#scheduleIdleTimer()\n }\n return\n }\n }\n\n const enterCommits =\n resolvedCommitOnEnter(this.#options) &&\n event.key === 'Enter' &&\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.metaKey\n\n if (enterCommits && this.store.state.steps.length >= 1) {\n this.commit()\n return\n }\n\n if (enterCommits && this.store.state.steps.length === 0) {\n return\n }\n\n const finalHotkey = hotkeyChordFromKeydown(event, this.#platform)\n if (finalHotkey === null) {\n return\n }\n\n this.#patchSteps((prev) => [...prev, finalHotkey])\n this.#scheduleIdleTimer()\n }\n\n this.#keydownHandler = handler\n this.#addListener(handler)\n }\n\n /**\n * Commit the current steps as a sequence. No-op if fewer than one step.\n */\n commit(): void {\n const steps = this.store.state.steps\n if (steps.length < 1) {\n return\n }\n\n const sequence = [...steps]\n\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: sequence,\n }))\n\n this.#options.onRecord(sequence)\n }\n\n #finishWithoutCommitCallback(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n\n stop(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n\n cancel(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n this.#options.onCancel?.()\n }\n\n #addListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return\n }\n document.addEventListener('keydown', handler, true)\n }\n\n #removeListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return\n }\n document.removeEventListener('keydown', handler, true)\n }\n\n destroy(): void {\n this.stop()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n}\n"],"mappings":";;;;;AAmDA,MAAM,uCAGF;CACF,eAAe;CACf,YAAY;CACb;AAED,SAAS,sBACP,SACS;AACT,KAAI,QAAQ,eAAe,OACzB,QAAO;AAET,QA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AC1C,SAAKA,iBAAkB;;AAEzB,QAAKD,gBAAiB;AACtB,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE;;CAGL,OAAa;AACX,MAAI,MAAKC,gBAAiB;AACxB,SAAKM,eAAgB,MAAKN,eAAgB;AAC1C,SAAKA,iBAAkB;;AAEzB,QAAKD,gBAAiB;AACtB,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE;;CAGL,SAAe;AACb,MAAI,MAAKC,gBAAiB;AACxB,SAAKM,eAAgB,MAAKN,eAAgB;AAC1C,SAAKA,iBAAkB;;AAEzB,QAAKD,gBAAiB;AACtB,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE;AACH,QAAKJ,QAAS,YAAY;;CAG5B,aAAa,SAA+C;AAC1D,MAAI,OAAO,aAAa,YACtB;AAEF,WAAS,iBAAiB,WAAW,SAAS,KAAK;;CAGrD,gBAAgB,SAA+C;AAC7D,MAAI,OAAO,aAAa,YACtB;AAEF,WAAS,oBAAoB,WAAW,SAAS,KAAK;;CAGxD,UAAgB;AACd,OAAK,MAAM;AACX,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE"}
1
+ {"version":3,"file":"hotkey-sequence-recorder.cjs","names":["Store","#options","#platform","detectPlatform","#idleTimer","#clearIdleTimer","#keydownHandler","isInputElement","#finishWithoutCommitCallback","#patchSteps","#scheduleIdleTimer","hotkeyChordFromKeydown","#addListener","#removeListener"],"sources":["../src/hotkey-sequence-recorder.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { detectPlatform } from './constants'\nimport { isInputElement } from './manager.utils'\nimport { hotkeyChordFromKeydown } from './recorder-chord'\nimport type { HotkeySequence } from './sequence-manager'\n\n/**\n * How the user can commit a recorded sequence from the keyboard.\n * - `'enter'`: plain Enter (no modifiers) commits when at least one step exists.\n * - `'none'`: only {@link HotkeySequenceRecorder.commit} finishes recording (or idle timeout if set).\n */\nexport type HotkeySequenceRecorderCommitKeys = 'enter' | 'none'\n\n/**\n * State interface for the HotkeySequenceRecorder.\n */\nexport interface HotkeySequenceRecorderState {\n /** Whether recording is currently active */\n isRecording: boolean\n /** Chords captured so far in the current recording session */\n steps: HotkeySequence\n /** The last successfully committed sequence, or null if none / after starting a new session */\n recordedSequence: HotkeySequence | null\n}\n\n/**\n * Options for configuring a HotkeySequenceRecorder instance.\n */\nexport interface HotkeySequenceRecorderOptions {\n /** Callback when a sequence is successfully recorded (including empty array when cleared) */\n onRecord: (sequence: HotkeySequence) => void\n /** Optional callback when recording is cancelled (Escape pressed) */\n onCancel?: () => void\n /** Optional callback when the sequence is cleared (Backspace/Delete with no steps) */\n onClear?: () => void\n /**\n * Whether plain Enter commits the current steps. Ignored when {@link commitKeys} is `'none'`.\n * @default true\n */\n commitOnEnter?: boolean\n /**\n * Keyboard commit mode. When `'none'`, use {@link HotkeySequenceRecorder.commit} (and optional idle timeout).\n * @default 'enter'\n */\n commitKeys?: HotkeySequenceRecorderCommitKeys\n /**\n * Milliseconds of inactivity after the **last completed chord** before auto-committing.\n * The timer does not run while waiting for the first chord (`steps.length === 0`).\n */\n idleTimeoutMs?: number\n /**\n * Whether to ignore keyboard events from input-like elements (text inputs,\n * textarea, select, contenteditable). When true, typing in inputs passes\n * through normally instead of being captured as a sequence recording.\n * Escape always works regardless of this setting.\n * @default true\n */\n ignoreInputs?: boolean\n}\n\nconst defaultHotkeySequenceRecorderOptions: Pick<\n HotkeySequenceRecorderOptions,\n 'commitOnEnter' | 'commitKeys'\n> = {\n commitOnEnter: true,\n commitKeys: 'enter',\n}\n\nfunction resolvedCommitOnEnter(\n options: HotkeySequenceRecorderOptions,\n): boolean {\n if (options.commitKeys === 'none') {\n return false\n }\n return options.commitOnEnter !== false\n}\n\n/**\n * Framework-agnostic class for recording multi-chord sequences (Vim-style shortcuts).\n *\n * Each step is captured like a single hotkey chord. Press **Enter** (no modifiers) to commit\n * when {@link HotkeySequenceRecorderOptions.commitKeys} is `'enter'` (default), **Escape** to cancel,\n * **Backspace/Delete** to remove the last step or clear when empty.\n */\nexport class HotkeySequenceRecorder {\n readonly store: Store<HotkeySequenceRecorderState> =\n new Store<HotkeySequenceRecorderState>({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n })\n\n #keydownHandler: ((event: KeyboardEvent) => void) | null = null\n #options: HotkeySequenceRecorderOptions\n #platform: 'mac' | 'windows' | 'linux'\n #idleTimer: ReturnType<typeof setTimeout> | null = null\n\n constructor(options: HotkeySequenceRecorderOptions) {\n this.#options = {\n ...defaultHotkeySequenceRecorderOptions,\n ...options,\n }\n this.#platform = detectPlatform()\n }\n\n setOptions(options: Partial<HotkeySequenceRecorderOptions>): void {\n this.#options = {\n ...defaultHotkeySequenceRecorderOptions,\n ...this.#options,\n ...options,\n }\n }\n\n #clearIdleTimer(): void {\n if (this.#idleTimer !== null) {\n clearTimeout(this.#idleTimer)\n this.#idleTimer = null\n }\n }\n\n #scheduleIdleTimer(): void {\n this.#clearIdleTimer()\n const ms = this.#options.idleTimeoutMs\n if (ms === undefined || ms <= 0) {\n return\n }\n const steps = this.store.state.steps\n if (steps.length === 0) {\n return\n }\n this.#idleTimer = setTimeout(() => {\n this.#idleTimer = null\n if (!this.#keydownHandler) {\n return\n }\n if (this.store.state.steps.length >= 1) {\n this.commit()\n }\n }, ms)\n }\n\n #patchSteps(updater: (prev: HotkeySequence) => HotkeySequence): void {\n this.store.setState((s) => ({\n ...s,\n steps: updater(s.steps),\n }))\n }\n\n start(): void {\n if (this.#keydownHandler) {\n return\n }\n\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: true,\n steps: [],\n recordedSequence: null,\n }))\n\n const handler = (event: KeyboardEvent) => {\n if (!this.#keydownHandler) {\n return\n }\n\n // If ignoreInputs is enabled (default) and focus is in an input element,\n // let the event pass through so the user can type normally.\n // Escape is the exception — it should always cancel recording.\n if (this.#options.ignoreInputs !== false) {\n const activeEl =\n typeof document !== 'undefined' ? document.activeElement : null\n if (isInputElement(activeEl) && event.key !== 'Escape') {\n return\n }\n }\n\n event.preventDefault()\n event.stopPropagation()\n\n if (event.key === 'Escape') {\n this.cancel()\n return\n }\n\n if (event.key === 'Backspace' || event.key === 'Delete') {\n if (\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.metaKey\n ) {\n const steps = this.store.state.steps\n if (steps.length === 0) {\n this.#options.onClear?.()\n this.#options.onRecord([])\n this.#finishWithoutCommitCallback()\n return\n }\n this.#patchSteps((prev) => prev.slice(0, -1))\n const next = this.store.state.steps\n if (next.length === 0) {\n this.#clearIdleTimer()\n } else {\n this.#scheduleIdleTimer()\n }\n return\n }\n }\n\n const enterCommits =\n resolvedCommitOnEnter(this.#options) &&\n event.key === 'Enter' &&\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.metaKey\n\n if (enterCommits && this.store.state.steps.length >= 1) {\n this.commit()\n return\n }\n\n if (enterCommits && this.store.state.steps.length === 0) {\n return\n }\n\n const finalHotkey = hotkeyChordFromKeydown(event, this.#platform)\n if (finalHotkey === null) {\n return\n }\n\n this.#patchSteps((prev) => [...prev, finalHotkey])\n this.#scheduleIdleTimer()\n }\n\n this.#keydownHandler = handler\n this.#addListener(handler)\n }\n\n /**\n * Commit the current steps as a sequence. No-op if fewer than one step.\n */\n commit(): void {\n const steps = this.store.state.steps\n if (steps.length < 1) {\n return\n }\n\n const sequence = [...steps]\n\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: sequence,\n }))\n\n this.#options.onRecord(sequence)\n }\n\n #finishWithoutCommitCallback(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n\n stop(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n\n cancel(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n this.#options.onCancel?.()\n }\n\n #addListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return\n }\n document.addEventListener('keydown', handler, true)\n }\n\n #removeListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return\n }\n document.removeEventListener('keydown', handler, true)\n }\n\n destroy(): void {\n this.stop()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n}\n"],"mappings":";;;;;;AA4DA,MAAM,uCAGF;CACF,eAAe;CACf,YAAY;CACb;AAED,SAAS,sBACP,SACS;AACT,KAAI,QAAQ,eAAe,OACzB,QAAO;AAET,QAAO,QAAQ,kBAAkB;;;;;;;;;AAUnC,IAAa,yBAAb,MAAoC;CAQlC,kBAA2D;CAC3D;CACA;CACA,aAAmD;CAEnD,YAAY,SAAwC;eAXlD,IAAIA,sBAAmC;GACrC,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,CAAC;AAQF,QAAKC,UAAW;GACd,GAAG;GACH,GAAG;GACJ;AACD,QAAKC,WAAYC,kCAAgB;;CAGnC,WAAW,SAAuD;AAChE,QAAKF,UAAW;GACd,GAAG;GACH,GAAG,MAAKA;GACR,GAAG;GACJ;;CAGH,kBAAwB;AACtB,MAAI,MAAKG,cAAe,MAAM;AAC5B,gBAAa,MAAKA,UAAW;AAC7B,SAAKA,YAAa;;;CAIt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GL,SAAe;AACb,MAAI,MAAKC,gBAAiB;AACxB,SAAKO,eAAgB,MAAKP,eAAgB;AAC1C,SAAKA,iBAAkB;;AAEzB,QAAKD,gBAAiB;AACtB,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE;AACH,QAAKJ,QAAS,YAAY;;CAG5B,aAAa,SAA+C;AAC1D,MAAI,OAAO,aAAa,YACtB;AAEF,WAAS,iBAAiB,WAAW,SAAS,KAAK;;CAGrD,gBAAgB,SAA+C;AAC7D,MAAI,OAAO,aAAa,YACtB;AAEF,WAAS,oBAAoB,WAAW,SAAS,KAAK;;CAGxD,UAAgB;AACd,OAAK,MAAM;AACX,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE"}
@@ -44,6 +44,14 @@ interface HotkeySequenceRecorderOptions {
44
44
  * The timer does not run while waiting for the first chord (`steps.length === 0`).
45
45
  */
46
46
  idleTimeoutMs?: number;
47
+ /**
48
+ * Whether to ignore keyboard events from input-like elements (text inputs,
49
+ * textarea, select, contenteditable). When true, typing in inputs passes
50
+ * through normally instead of being captured as a sequence recording.
51
+ * Escape always works regardless of this setting.
52
+ * @default true
53
+ */
54
+ ignoreInputs?: boolean;
47
55
  }
48
56
  /**
49
57
  * Framework-agnostic class for recording multi-chord sequences (Vim-style shortcuts).
@@ -44,6 +44,14 @@ interface HotkeySequenceRecorderOptions {
44
44
  * The timer does not run while waiting for the first chord (`steps.length === 0`).
45
45
  */
46
46
  idleTimeoutMs?: number;
47
+ /**
48
+ * Whether to ignore keyboard events from input-like elements (text inputs,
49
+ * textarea, select, contenteditable). When true, typing in inputs passes
50
+ * through normally instead of being captured as a sequence recording.
51
+ * Escape always works regardless of this setting.
52
+ * @default true
53
+ */
54
+ ignoreInputs?: boolean;
47
55
  }
48
56
  /**
49
57
  * Framework-agnostic class for recording multi-chord sequences (Vim-style shortcuts).
@@ -1,4 +1,5 @@
1
1
  import { detectPlatform } from "./constants.js";
2
+ import { isInputElement } from "./manager.utils.js";
2
3
  import { hotkeyChordFromKeydown } from "./recorder-chord.js";
3
4
  import { Store } from "@tanstack/store";
4
5
 
@@ -75,6 +76,9 @@ var HotkeySequenceRecorder = class {
75
76
  }));
76
77
  const handler = (event) => {
77
78
  if (!this.#keydownHandler) return;
79
+ if (this.#options.ignoreInputs !== false) {
80
+ if (isInputElement(typeof document !== "undefined" ? document.activeElement : null) && event.key !== "Escape") return;
81
+ }
78
82
  event.preventDefault();
79
83
  event.stopPropagation();
80
84
  if (event.key === "Escape") {
@@ -1 +1 @@
1
- {"version":3,"file":"hotkey-sequence-recorder.js","names":["#options","#platform","#idleTimer","#clearIdleTimer","#keydownHandler","#finishWithoutCommitCallback","#patchSteps","#scheduleIdleTimer","#addListener","#removeListener"],"sources":["../src/hotkey-sequence-recorder.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { detectPlatform } from './constants'\nimport { hotkeyChordFromKeydown } from './recorder-chord'\nimport type { HotkeySequence } from './sequence-manager'\n\n/**\n * How the user can commit a recorded sequence from the keyboard.\n * - `'enter'`: plain Enter (no modifiers) commits when at least one step exists.\n * - `'none'`: only {@link HotkeySequenceRecorder.commit} finishes recording (or idle timeout if set).\n */\nexport type HotkeySequenceRecorderCommitKeys = 'enter' | 'none'\n\n/**\n * State interface for the HotkeySequenceRecorder.\n */\nexport interface HotkeySequenceRecorderState {\n /** Whether recording is currently active */\n isRecording: boolean\n /** Chords captured so far in the current recording session */\n steps: HotkeySequence\n /** The last successfully committed sequence, or null if none / after starting a new session */\n recordedSequence: HotkeySequence | null\n}\n\n/**\n * Options for configuring a HotkeySequenceRecorder instance.\n */\nexport interface HotkeySequenceRecorderOptions {\n /** Callback when a sequence is successfully recorded (including empty array when cleared) */\n onRecord: (sequence: HotkeySequence) => void\n /** Optional callback when recording is cancelled (Escape pressed) */\n onCancel?: () => void\n /** Optional callback when the sequence is cleared (Backspace/Delete with no steps) */\n onClear?: () => void\n /**\n * Whether plain Enter commits the current steps. Ignored when {@link commitKeys} is `'none'`.\n * @default true\n */\n commitOnEnter?: boolean\n /**\n * Keyboard commit mode. When `'none'`, use {@link HotkeySequenceRecorder.commit} (and optional idle timeout).\n * @default 'enter'\n */\n commitKeys?: HotkeySequenceRecorderCommitKeys\n /**\n * Milliseconds of inactivity after the **last completed chord** before auto-committing.\n * The timer does not run while waiting for the first chord (`steps.length === 0`).\n */\n idleTimeoutMs?: number\n}\n\nconst defaultHotkeySequenceRecorderOptions: Pick<\n HotkeySequenceRecorderOptions,\n 'commitOnEnter' | 'commitKeys'\n> = {\n commitOnEnter: true,\n commitKeys: 'enter',\n}\n\nfunction resolvedCommitOnEnter(\n options: HotkeySequenceRecorderOptions,\n): boolean {\n if (options.commitKeys === 'none') {\n return false\n }\n return options.commitOnEnter !== false\n}\n\n/**\n * Framework-agnostic class for recording multi-chord sequences (Vim-style shortcuts).\n *\n * Each step is captured like a single hotkey chord. Press **Enter** (no modifiers) to commit\n * when {@link HotkeySequenceRecorderOptions.commitKeys} is `'enter'` (default), **Escape** to cancel,\n * **Backspace/Delete** to remove the last step or clear when empty.\n */\nexport class HotkeySequenceRecorder {\n readonly store: Store<HotkeySequenceRecorderState> =\n new Store<HotkeySequenceRecorderState>({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n })\n\n #keydownHandler: ((event: KeyboardEvent) => void) | null = null\n #options: HotkeySequenceRecorderOptions\n #platform: 'mac' | 'windows' | 'linux'\n #idleTimer: ReturnType<typeof setTimeout> | null = null\n\n constructor(options: HotkeySequenceRecorderOptions) {\n this.#options = {\n ...defaultHotkeySequenceRecorderOptions,\n ...options,\n }\n this.#platform = detectPlatform()\n }\n\n setOptions(options: Partial<HotkeySequenceRecorderOptions>): void {\n this.#options = {\n ...defaultHotkeySequenceRecorderOptions,\n ...this.#options,\n ...options,\n }\n }\n\n #clearIdleTimer(): void {\n if (this.#idleTimer !== null) {\n clearTimeout(this.#idleTimer)\n this.#idleTimer = null\n }\n }\n\n #scheduleIdleTimer(): void {\n this.#clearIdleTimer()\n const ms = this.#options.idleTimeoutMs\n if (ms === undefined || ms <= 0) {\n return\n }\n const steps = this.store.state.steps\n if (steps.length === 0) {\n return\n }\n this.#idleTimer = setTimeout(() => {\n this.#idleTimer = null\n if (!this.#keydownHandler) {\n return\n }\n if (this.store.state.steps.length >= 1) {\n this.commit()\n }\n }, ms)\n }\n\n #patchSteps(updater: (prev: HotkeySequence) => HotkeySequence): void {\n this.store.setState((s) => ({\n ...s,\n steps: updater(s.steps),\n }))\n }\n\n start(): void {\n if (this.#keydownHandler) {\n return\n }\n\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: true,\n steps: [],\n recordedSequence: null,\n }))\n\n const handler = (event: KeyboardEvent) => {\n if (!this.#keydownHandler) {\n return\n }\n\n event.preventDefault()\n event.stopPropagation()\n\n if (event.key === 'Escape') {\n this.cancel()\n return\n }\n\n if (event.key === 'Backspace' || event.key === 'Delete') {\n if (\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.metaKey\n ) {\n const steps = this.store.state.steps\n if (steps.length === 0) {\n this.#options.onClear?.()\n this.#options.onRecord([])\n this.#finishWithoutCommitCallback()\n return\n }\n this.#patchSteps((prev) => prev.slice(0, -1))\n const next = this.store.state.steps\n if (next.length === 0) {\n this.#clearIdleTimer()\n } else {\n this.#scheduleIdleTimer()\n }\n return\n }\n }\n\n const enterCommits =\n resolvedCommitOnEnter(this.#options) &&\n event.key === 'Enter' &&\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.metaKey\n\n if (enterCommits && this.store.state.steps.length >= 1) {\n this.commit()\n return\n }\n\n if (enterCommits && this.store.state.steps.length === 0) {\n return\n }\n\n const finalHotkey = hotkeyChordFromKeydown(event, this.#platform)\n if (finalHotkey === null) {\n return\n }\n\n this.#patchSteps((prev) => [...prev, finalHotkey])\n this.#scheduleIdleTimer()\n }\n\n this.#keydownHandler = handler\n this.#addListener(handler)\n }\n\n /**\n * Commit the current steps as a sequence. No-op if fewer than one step.\n */\n commit(): void {\n const steps = this.store.state.steps\n if (steps.length < 1) {\n return\n }\n\n const sequence = [...steps]\n\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: sequence,\n }))\n\n this.#options.onRecord(sequence)\n }\n\n #finishWithoutCommitCallback(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n\n stop(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n\n cancel(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n this.#options.onCancel?.()\n }\n\n #addListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return\n }\n document.addEventListener('keydown', handler, true)\n }\n\n #removeListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return\n }\n document.removeEventListener('keydown', handler, true)\n }\n\n destroy(): void {\n this.stop()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n}\n"],"mappings":";;;;;AAmDA,MAAM,uCAGF;CACF,eAAe;CACf,YAAY;CACb;AAED,SAAS,sBACP,SACS;AACT,KAAI,QAAQ,eAAe,OACzB,QAAO;AAET,QAAO,QAAQ,kBAAkB;;;;;;;;;AAUnC,IAAa,yBAAb,MAAoC;CAQlC,kBAA2D;CAC3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a;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE;;CAGL,OAAa;AACX,MAAI,MAAKC,gBAAiB;AACxB,SAAKK,eAAgB,MAAKL,eAAgB;AAC1C,SAAKA,iBAAkB;;AAEzB,QAAKD,gBAAiB;AACtB,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE;;CAGL,SAAe;AACb,MAAI,MAAKC,gBAAiB;AACxB,SAAKK,eAAgB,MAAKL,eAAgB;AAC1C,SAAKA,iBAAkB;;AAEzB,QAAKD,gBAAiB;AACtB,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE;AACH,QAAKH,QAAS,YAAY;;CAG5B,aAAa,SAA+C;AAC1D,MAAI,OAAO,aAAa,YACtB;AAEF,WAAS,iBAAiB,WAAW,SAAS,KAAK;;CAGrD,gBAAgB,SAA+C;AAC7D,MAAI,OAAO,aAAa,YACtB;AAEF,WAAS,oBAAoB,WAAW,SAAS,KAAK;;CAGxD,UAAgB;AACd,OAAK,MAAM;AACX,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE"}
1
+ {"version":3,"file":"hotkey-sequence-recorder.js","names":["#options","#platform","#idleTimer","#clearIdleTimer","#keydownHandler","#finishWithoutCommitCallback","#patchSteps","#scheduleIdleTimer","#addListener","#removeListener"],"sources":["../src/hotkey-sequence-recorder.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { detectPlatform } from './constants'\nimport { isInputElement } from './manager.utils'\nimport { hotkeyChordFromKeydown } from './recorder-chord'\nimport type { HotkeySequence } from './sequence-manager'\n\n/**\n * How the user can commit a recorded sequence from the keyboard.\n * - `'enter'`: plain Enter (no modifiers) commits when at least one step exists.\n * - `'none'`: only {@link HotkeySequenceRecorder.commit} finishes recording (or idle timeout if set).\n */\nexport type HotkeySequenceRecorderCommitKeys = 'enter' | 'none'\n\n/**\n * State interface for the HotkeySequenceRecorder.\n */\nexport interface HotkeySequenceRecorderState {\n /** Whether recording is currently active */\n isRecording: boolean\n /** Chords captured so far in the current recording session */\n steps: HotkeySequence\n /** The last successfully committed sequence, or null if none / after starting a new session */\n recordedSequence: HotkeySequence | null\n}\n\n/**\n * Options for configuring a HotkeySequenceRecorder instance.\n */\nexport interface HotkeySequenceRecorderOptions {\n /** Callback when a sequence is successfully recorded (including empty array when cleared) */\n onRecord: (sequence: HotkeySequence) => void\n /** Optional callback when recording is cancelled (Escape pressed) */\n onCancel?: () => void\n /** Optional callback when the sequence is cleared (Backspace/Delete with no steps) */\n onClear?: () => void\n /**\n * Whether plain Enter commits the current steps. Ignored when {@link commitKeys} is `'none'`.\n * @default true\n */\n commitOnEnter?: boolean\n /**\n * Keyboard commit mode. When `'none'`, use {@link HotkeySequenceRecorder.commit} (and optional idle timeout).\n * @default 'enter'\n */\n commitKeys?: HotkeySequenceRecorderCommitKeys\n /**\n * Milliseconds of inactivity after the **last completed chord** before auto-committing.\n * The timer does not run while waiting for the first chord (`steps.length === 0`).\n */\n idleTimeoutMs?: number\n /**\n * Whether to ignore keyboard events from input-like elements (text inputs,\n * textarea, select, contenteditable). When true, typing in inputs passes\n * through normally instead of being captured as a sequence recording.\n * Escape always works regardless of this setting.\n * @default true\n */\n ignoreInputs?: boolean\n}\n\nconst defaultHotkeySequenceRecorderOptions: Pick<\n HotkeySequenceRecorderOptions,\n 'commitOnEnter' | 'commitKeys'\n> = {\n commitOnEnter: true,\n commitKeys: 'enter',\n}\n\nfunction resolvedCommitOnEnter(\n options: HotkeySequenceRecorderOptions,\n): boolean {\n if (options.commitKeys === 'none') {\n return false\n }\n return options.commitOnEnter !== false\n}\n\n/**\n * Framework-agnostic class for recording multi-chord sequences (Vim-style shortcuts).\n *\n * Each step is captured like a single hotkey chord. Press **Enter** (no modifiers) to commit\n * when {@link HotkeySequenceRecorderOptions.commitKeys} is `'enter'` (default), **Escape** to cancel,\n * **Backspace/Delete** to remove the last step or clear when empty.\n */\nexport class HotkeySequenceRecorder {\n readonly store: Store<HotkeySequenceRecorderState> =\n new Store<HotkeySequenceRecorderState>({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n })\n\n #keydownHandler: ((event: KeyboardEvent) => void) | null = null\n #options: HotkeySequenceRecorderOptions\n #platform: 'mac' | 'windows' | 'linux'\n #idleTimer: ReturnType<typeof setTimeout> | null = null\n\n constructor(options: HotkeySequenceRecorderOptions) {\n this.#options = {\n ...defaultHotkeySequenceRecorderOptions,\n ...options,\n }\n this.#platform = detectPlatform()\n }\n\n setOptions(options: Partial<HotkeySequenceRecorderOptions>): void {\n this.#options = {\n ...defaultHotkeySequenceRecorderOptions,\n ...this.#options,\n ...options,\n }\n }\n\n #clearIdleTimer(): void {\n if (this.#idleTimer !== null) {\n clearTimeout(this.#idleTimer)\n this.#idleTimer = null\n }\n }\n\n #scheduleIdleTimer(): void {\n this.#clearIdleTimer()\n const ms = this.#options.idleTimeoutMs\n if (ms === undefined || ms <= 0) {\n return\n }\n const steps = this.store.state.steps\n if (steps.length === 0) {\n return\n }\n this.#idleTimer = setTimeout(() => {\n this.#idleTimer = null\n if (!this.#keydownHandler) {\n return\n }\n if (this.store.state.steps.length >= 1) {\n this.commit()\n }\n }, ms)\n }\n\n #patchSteps(updater: (prev: HotkeySequence) => HotkeySequence): void {\n this.store.setState((s) => ({\n ...s,\n steps: updater(s.steps),\n }))\n }\n\n start(): void {\n if (this.#keydownHandler) {\n return\n }\n\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: true,\n steps: [],\n recordedSequence: null,\n }))\n\n const handler = (event: KeyboardEvent) => {\n if (!this.#keydownHandler) {\n return\n }\n\n // If ignoreInputs is enabled (default) and focus is in an input element,\n // let the event pass through so the user can type normally.\n // Escape is the exception — it should always cancel recording.\n if (this.#options.ignoreInputs !== false) {\n const activeEl =\n typeof document !== 'undefined' ? document.activeElement : null\n if (isInputElement(activeEl) && event.key !== 'Escape') {\n return\n }\n }\n\n event.preventDefault()\n event.stopPropagation()\n\n if (event.key === 'Escape') {\n this.cancel()\n return\n }\n\n if (event.key === 'Backspace' || event.key === 'Delete') {\n if (\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.metaKey\n ) {\n const steps = this.store.state.steps\n if (steps.length === 0) {\n this.#options.onClear?.()\n this.#options.onRecord([])\n this.#finishWithoutCommitCallback()\n return\n }\n this.#patchSteps((prev) => prev.slice(0, -1))\n const next = this.store.state.steps\n if (next.length === 0) {\n this.#clearIdleTimer()\n } else {\n this.#scheduleIdleTimer()\n }\n return\n }\n }\n\n const enterCommits =\n resolvedCommitOnEnter(this.#options) &&\n event.key === 'Enter' &&\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.metaKey\n\n if (enterCommits && this.store.state.steps.length >= 1) {\n this.commit()\n return\n }\n\n if (enterCommits && this.store.state.steps.length === 0) {\n return\n }\n\n const finalHotkey = hotkeyChordFromKeydown(event, this.#platform)\n if (finalHotkey === null) {\n return\n }\n\n this.#patchSteps((prev) => [...prev, finalHotkey])\n this.#scheduleIdleTimer()\n }\n\n this.#keydownHandler = handler\n this.#addListener(handler)\n }\n\n /**\n * Commit the current steps as a sequence. No-op if fewer than one step.\n */\n commit(): void {\n const steps = this.store.state.steps\n if (steps.length < 1) {\n return\n }\n\n const sequence = [...steps]\n\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: sequence,\n }))\n\n this.#options.onRecord(sequence)\n }\n\n #finishWithoutCommitCallback(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n\n stop(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n\n cancel(): void {\n if (this.#keydownHandler) {\n this.#removeListener(this.#keydownHandler)\n this.#keydownHandler = null\n }\n this.#clearIdleTimer()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n this.#options.onCancel?.()\n }\n\n #addListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return\n }\n document.addEventListener('keydown', handler, true)\n }\n\n #removeListener(handler: (event: KeyboardEvent) => void): void {\n if (typeof document === 'undefined') {\n return\n }\n document.removeEventListener('keydown', handler, true)\n }\n\n destroy(): void {\n this.stop()\n this.store.setState(() => ({\n isRecording: false,\n steps: [],\n recordedSequence: null,\n }))\n }\n}\n"],"mappings":";;;;;;AA4DA,MAAM,uCAGF;CACF,eAAe;CACf,YAAY;CACb;AAED,SAAS,sBACP,SACS;AACT,KAAI,QAAQ,eAAe,OACzB,QAAO;AAET,QAAO,QAAQ,kBAAkB;;;;;;;;;AAUnC,IAAa,yBAAb,MAAoC;CAQlC,kBAA2D;CAC3D;CACA;CACA,aAAmD;CAEnD,YAAY,SAAwC;eAXlD,IAAI,MAAmC;GACrC,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,CAAC;AAQF,QAAKA,UAAW;GACd,GAAG;GACH,GAAG;GACJ;AACD,QAAKC,WAAY,gBAAgB;;CAGnC,WAAW,SAAuD;AAChE,QAAKD,UAAW;GACd,GAAG;GACH,GAAG,MAAKA;GACR,GAAG;GACJ;;CAGH,kBAAwB;AACtB,MAAI,MAAKE,cAAe,MAAM;AAC5B,gBAAa,MAAKA,UAAW;AAC7B,SAAKA,YAAa;;;CAItB,qBAA2B;AACzB,QAAKC,gBAAiB;EACtB,MAAM,KAAK,MAAKH,QAAS;AACzB,MAAI,OAAO,UAAa,MAAM,EAC5B;AAGF,MADc,KAAK,MAAM,M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AAM,gBAAgB;GACzB,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE;AACH,QAAKH,QAAS,YAAY;;CAG5B,aAAa,SAA+C;AAC1D,MAAI,OAAO,aAAa,YACtB;AAEF,WAAS,iBAAiB,WAAW,SAAS,KAAK;;CAGrD,gBAAgB,SAA+C;AAC7D,MAAI,OAAO,aAAa,YACtB;AAEF,WAAS,oBAAoB,WAAW,SAAS,KAAK;;CAGxD,UAAgB;AACd,OAAK,MAAM;AACX,OAAK,MAAM,gBAAgB;GACzB,aAAa;GACb,OAAO,EAAE;GACT,kBAAkB;GACnB,EAAE"}
package/dist/hotkey.d.cts CHANGED
@@ -54,10 +54,9 @@ type NonPunctuationKey = LetterKey | NumberKey | EditingKey | NavigationKey | Fu
54
54
  */
55
55
  type Key = NonPunctuationKey | PunctuationKey;
56
56
  /**
57
- * Keys that can be tracked as "held" (pressed down).
58
57
  * Includes both modifier keys and regular keys.
59
58
  */
60
- type HeldKey = CanonicalModifier | Key;
59
+ type IndividualKey = CanonicalModifier | Key;
61
60
  /**
62
61
  * Single modifier + key combinations.
63
62
  * Uses canonical modifiers (4) + Mod (1) = 5 modifiers.
@@ -277,6 +276,26 @@ interface HotkeyCallbackContext {
277
276
  * ```
278
277
  */
279
278
  type HotkeyCallback = (event: KeyboardEvent, context: HotkeyCallbackContext) => void;
279
+ /**
280
+ * Metadata for hotkey and sequence registrations.
281
+ * Includes `name` and `description` by default. Extend via declaration merging:
282
+ *
283
+ * @example
284
+ * ```ts
285
+ * declare module '@tanstack/hotkeys' {
286
+ * interface HotkeyMeta {
287
+ * category?: string
288
+ * icon?: string
289
+ * }
290
+ * }
291
+ * ```
292
+ */
293
+ interface HotkeyMeta {
294
+ /** Human-readable name for this hotkey (e.g., "Save Document") */
295
+ name?: string;
296
+ /** Description of what this hotkey does */
297
+ description?: string;
298
+ }
280
299
  //#endregion
281
- export { CanonicalModifier, EditingKey, FormatDisplayOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, Key, LetterKey, Modifier, NavigationKey, NumberKey, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, ValidationResult };
300
+ export { CanonicalModifier, EditingKey, FormatDisplayOptions, FunctionKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyMeta, IndividualKey, Key, LetterKey, Modifier, NavigationKey, NumberKey, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, ValidationResult };
282
301
  //# sourceMappingURL=hotkey.d.cts.map
package/dist/hotkey.d.ts CHANGED
@@ -54,10 +54,9 @@ type NonPunctuationKey = LetterKey | NumberKey | EditingKey | NavigationKey | Fu
54
54
  */
55
55
  type Key = NonPunctuationKey | PunctuationKey;
56
56
  /**
57
- * Keys that can be tracked as "held" (pressed down).
58
57
  * Includes both modifier keys and regular keys.
59
58
  */
60
- type HeldKey = CanonicalModifier | Key;
59
+ type IndividualKey = CanonicalModifier | Key;
61
60
  /**
62
61
  * Single modifier + key combinations.
63
62
  * Uses canonical modifiers (4) + Mod (1) = 5 modifiers.
@@ -277,6 +276,26 @@ interface HotkeyCallbackContext {
277
276
  * ```
278
277
  */
279
278
  type HotkeyCallback = (event: KeyboardEvent, context: HotkeyCallbackContext) => void;
279
+ /**
280
+ * Metadata for hotkey and sequence registrations.
281
+ * Includes `name` and `description` by default. Extend via declaration merging:
282
+ *
283
+ * @example
284
+ * ```ts
285
+ * declare module '@tanstack/hotkeys' {
286
+ * interface HotkeyMeta {
287
+ * category?: string
288
+ * icon?: string
289
+ * }
290
+ * }
291
+ * ```
292
+ */
293
+ interface HotkeyMeta {
294
+ /** Human-readable name for this hotkey (e.g., "Save Document") */
295
+ name?: string;
296
+ /** Description of what this hotkey does */
297
+ description?: string;
298
+ }
280
299
  //#endregion
281
- export { CanonicalModifier, EditingKey, FormatDisplayOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, Key, LetterKey, Modifier, NavigationKey, NumberKey, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, ValidationResult };
300
+ export { CanonicalModifier, EditingKey, FormatDisplayOptions, FunctionKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyMeta, IndividualKey, Key, LetterKey, Modifier, NavigationKey, NumberKey, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, ValidationResult };
282
301
  //# sourceMappingURL=hotkey.d.ts.map
package/dist/index.cjs CHANGED
@@ -59,4 +59,5 @@ exports.parseHotkey = require_parse.parseHotkey;
59
59
  exports.parseKeyboardEvent = require_parse.parseKeyboardEvent;
60
60
  exports.rawHotkeyToParsedHotkey = require_parse.rawHotkeyToParsedHotkey;
61
61
  exports.resolveModifier = require_constants.resolveModifier;
62
+ exports.toHotkeyRegistrationView = require_hotkey_manager.toHotkeyRegistrationView;
62
63
  exports.validateHotkey = require_validate.validateHotkey;
package/dist/index.d.cts CHANGED
@@ -1,8 +1,8 @@
1
- import { CanonicalModifier, EditingKey, FormatDisplayOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, Key, LetterKey, Modifier, NavigationKey, NumberKey, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, ValidationResult } from "./hotkey.cjs";
1
+ import { CanonicalModifier, EditingKey, FormatDisplayOptions, FunctionKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyMeta, IndividualKey, Key, LetterKey, Modifier, NavigationKey, NumberKey, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, ValidationResult } from "./hotkey.cjs";
2
2
  import { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, LINUX_MODIFIER_LABELS, MAC_MODIFIER_LABELS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, PUNCTUATION_KEY_DISPLAY_LABELS, WINDOWS_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier } from "./constants.cjs";
3
3
  import { formatForDisplay, formatHotkey, formatHotkeySequence, formatWithLabels } from "./format.cjs";
4
4
  import { ConflictBehavior } from "./manager.utils.cjs";
5
- import { HotkeyManager, HotkeyOptions, HotkeyRegistration, HotkeyRegistrationHandle, getHotkeyManager } from "./hotkey-manager.cjs";
5
+ import { HotkeyManager, HotkeyOptions, HotkeyRegistration, HotkeyRegistrationHandle, HotkeyRegistrationView, getHotkeyManager, toHotkeyRegistrationView } from "./hotkey-manager.cjs";
6
6
  import { KeyStateTracker, KeyStateTrackerState, getKeyStateTracker } from "./key-state-tracker.cjs";
7
7
  import { CreateHotkeyHandlerOptions, createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent } from "./match.cjs";
8
8
  import { hasNonModifierKey, isModifierKey, normalizeHotkey, normalizeHotkeyFromEvent, normalizeHotkeyFromParsed, normalizeRegisterableHotkey, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey } from "./parse.cjs";
@@ -10,4 +10,4 @@ import { HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState } from "./ho
10
10
  import { DEFAULT_SEQUENCE_TIMEOUT, HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager } from "./sequence-manager.cjs";
11
11
  import { HotkeySequenceRecorder, HotkeySequenceRecorderCommitKeys, HotkeySequenceRecorderOptions, HotkeySequenceRecorderState } from "./hotkey-sequence-recorder.cjs";
12
12
  import { assertValidHotkey, checkHotkey, validateHotkey } from "./validate.cjs";
13
- export { ALL_KEYS, CanonicalModifier, ConflictBehavior, CreateHotkeyHandlerOptions, DEFAULT_SEQUENCE_TIMEOUT, EDITING_KEYS, EditingKey, FUNCTION_KEYS, FormatDisplayOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyManager, HotkeyOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState, HotkeyRegistration, HotkeyRegistrationHandle, HotkeySequence, HotkeySequenceRecorder, HotkeySequenceRecorderCommitKeys, HotkeySequenceRecorderOptions, HotkeySequenceRecorderState, KEY_DISPLAY_SYMBOLS, Key, KeyStateTracker, KeyStateTrackerState, LETTER_KEYS, LINUX_MODIFIER_LABELS, LetterKey, MAC_MODIFIER_LABELS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, Modifier, NAVIGATION_KEYS, NUMBER_KEYS, NavigationKey, NumberKey, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, PUNCTUATION_KEY_DISPLAY_LABELS, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, ValidationResult, WINDOWS_MODIFIER_LABELS, assertValidHotkey, checkHotkey, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifierKey, isSingleLetterKey, matchesKeyboardEvent, normalizeHotkey, normalizeHotkeyFromEvent, normalizeHotkeyFromParsed, normalizeKeyName, normalizeRegisterableHotkey, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
13
+ export { ALL_KEYS, CanonicalModifier, ConflictBehavior, CreateHotkeyHandlerOptions, DEFAULT_SEQUENCE_TIMEOUT, EDITING_KEYS, EditingKey, FUNCTION_KEYS, FormatDisplayOptions, FunctionKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyManager, HotkeyMeta, HotkeyOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState, HotkeyRegistration, HotkeyRegistrationHandle, HotkeyRegistrationView, HotkeySequence, HotkeySequenceRecorder, HotkeySequenceRecorderCommitKeys, HotkeySequenceRecorderOptions, HotkeySequenceRecorderState, IndividualKey, KEY_DISPLAY_SYMBOLS, Key, KeyStateTracker, KeyStateTrackerState, LETTER_KEYS, LINUX_MODIFIER_LABELS, LetterKey, MAC_MODIFIER_LABELS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, Modifier, NAVIGATION_KEYS, NUMBER_KEYS, NavigationKey, NumberKey, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, PUNCTUATION_KEY_DISPLAY_LABELS, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, ValidationResult, WINDOWS_MODIFIER_LABELS, assertValidHotkey, checkHotkey, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifierKey, isSingleLetterKey, matchesKeyboardEvent, normalizeHotkey, normalizeHotkeyFromEvent, normalizeHotkeyFromParsed, normalizeKeyName, normalizeRegisterableHotkey, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, toHotkeyRegistrationView, validateHotkey };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { CanonicalModifier, EditingKey, FormatDisplayOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, Key, LetterKey, Modifier, NavigationKey, NumberKey, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, ValidationResult } from "./hotkey.js";
1
+ import { CanonicalModifier, EditingKey, FormatDisplayOptions, FunctionKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyMeta, IndividualKey, Key, LetterKey, Modifier, NavigationKey, NumberKey, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, ValidationResult } from "./hotkey.js";
2
2
  import { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS, LINUX_MODIFIER_LABELS, MAC_MODIFIER_LABELS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, PUNCTUATION_KEY_DISPLAY_LABELS, WINDOWS_MODIFIER_LABELS, detectPlatform, isSingleLetterKey, normalizeKeyName, resolveModifier } from "./constants.js";
3
3
  import { formatForDisplay, formatHotkey, formatHotkeySequence, formatWithLabels } from "./format.js";
4
4
  import { ConflictBehavior } from "./manager.utils.js";
5
- import { HotkeyManager, HotkeyOptions, HotkeyRegistration, HotkeyRegistrationHandle, getHotkeyManager } from "./hotkey-manager.js";
5
+ import { HotkeyManager, HotkeyOptions, HotkeyRegistration, HotkeyRegistrationHandle, HotkeyRegistrationView, getHotkeyManager, toHotkeyRegistrationView } from "./hotkey-manager.js";
6
6
  import { KeyStateTracker, KeyStateTrackerState, getKeyStateTracker } from "./key-state-tracker.js";
7
7
  import { CreateHotkeyHandlerOptions, createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent } from "./match.js";
8
8
  import { hasNonModifierKey, isModifierKey, normalizeHotkey, normalizeHotkeyFromEvent, normalizeHotkeyFromParsed, normalizeRegisterableHotkey, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey } from "./parse.js";
@@ -10,4 +10,4 @@ import { HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState } from "./ho
10
10
  import { DEFAULT_SEQUENCE_TIMEOUT, HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager } from "./sequence-manager.js";
11
11
  import { HotkeySequenceRecorder, HotkeySequenceRecorderCommitKeys, HotkeySequenceRecorderOptions, HotkeySequenceRecorderState } from "./hotkey-sequence-recorder.js";
12
12
  import { assertValidHotkey, checkHotkey, validateHotkey } from "./validate.js";
13
- export { ALL_KEYS, CanonicalModifier, ConflictBehavior, CreateHotkeyHandlerOptions, DEFAULT_SEQUENCE_TIMEOUT, EDITING_KEYS, EditingKey, FUNCTION_KEYS, FormatDisplayOptions, FunctionKey, HeldKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyManager, HotkeyOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState, HotkeyRegistration, HotkeyRegistrationHandle, HotkeySequence, HotkeySequenceRecorder, HotkeySequenceRecorderCommitKeys, HotkeySequenceRecorderOptions, HotkeySequenceRecorderState, KEY_DISPLAY_SYMBOLS, Key, KeyStateTracker, KeyStateTrackerState, LETTER_KEYS, LINUX_MODIFIER_LABELS, LetterKey, MAC_MODIFIER_LABELS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, Modifier, NAVIGATION_KEYS, NUMBER_KEYS, NavigationKey, NumberKey, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, PUNCTUATION_KEY_DISPLAY_LABELS, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, ValidationResult, WINDOWS_MODIFIER_LABELS, assertValidHotkey, checkHotkey, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifierKey, isSingleLetterKey, matchesKeyboardEvent, normalizeHotkey, normalizeHotkeyFromEvent, normalizeHotkeyFromParsed, normalizeKeyName, normalizeRegisterableHotkey, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
13
+ export { ALL_KEYS, CanonicalModifier, ConflictBehavior, CreateHotkeyHandlerOptions, DEFAULT_SEQUENCE_TIMEOUT, EDITING_KEYS, EditingKey, FUNCTION_KEYS, FormatDisplayOptions, FunctionKey, Hotkey, HotkeyCallback, HotkeyCallbackContext, HotkeyManager, HotkeyMeta, HotkeyOptions, HotkeyRecorder, HotkeyRecorderOptions, HotkeyRecorderState, HotkeyRegistration, HotkeyRegistrationHandle, HotkeyRegistrationView, HotkeySequence, HotkeySequenceRecorder, HotkeySequenceRecorderCommitKeys, HotkeySequenceRecorderOptions, HotkeySequenceRecorderState, IndividualKey, KEY_DISPLAY_SYMBOLS, Key, KeyStateTracker, KeyStateTrackerState, LETTER_KEYS, LINUX_MODIFIER_LABELS, LetterKey, MAC_MODIFIER_LABELS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, Modifier, NAVIGATION_KEYS, NUMBER_KEYS, NavigationKey, NumberKey, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, PUNCTUATION_KEY_DISPLAY_LABELS, ParsedHotkey, PunctuationKey, RawHotkey, RegisterableHotkey, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, ValidationResult, WINDOWS_MODIFIER_LABELS, assertValidHotkey, checkHotkey, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifierKey, isSingleLetterKey, matchesKeyboardEvent, normalizeHotkey, normalizeHotkeyFromEvent, normalizeHotkeyFromParsed, normalizeKeyName, normalizeRegisterableHotkey, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, toHotkeyRegistrationView, validateHotkey };
package/dist/index.js CHANGED
@@ -2,11 +2,11 @@ import { ALL_KEYS, EDITING_KEYS, FUNCTION_KEYS, KEY_DISPLAY_SYMBOLS, LETTER_KEYS
2
2
  import { hasNonModifierKey, isModifierKey, normalizeHotkey, normalizeHotkeyFromEvent, normalizeHotkeyFromParsed, normalizeRegisterableHotkey, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey } from "./parse.js";
3
3
  import { formatForDisplay, formatHotkey, formatHotkeySequence, formatWithLabels } from "./format.js";
4
4
  import { createHotkeyHandler, createMultiHotkeyHandler, matchesKeyboardEvent } from "./match.js";
5
- import { HotkeyManager, getHotkeyManager } from "./hotkey-manager.js";
5
+ import { HotkeyManager, getHotkeyManager, toHotkeyRegistrationView } from "./hotkey-manager.js";
6
6
  import { KeyStateTracker, getKeyStateTracker } from "./key-state-tracker.js";
7
7
  import { HotkeyRecorder } from "./hotkey-recorder.js";
8
8
  import { HotkeySequenceRecorder } from "./hotkey-sequence-recorder.js";
9
9
  import { DEFAULT_SEQUENCE_TIMEOUT, SequenceManager, createSequenceMatcher, getSequenceManager } from "./sequence-manager.js";
10
10
  import { assertValidHotkey, checkHotkey, validateHotkey } from "./validate.js";
11
11
 
12
- export { ALL_KEYS, DEFAULT_SEQUENCE_TIMEOUT, EDITING_KEYS, FUNCTION_KEYS, HotkeyManager, HotkeyRecorder, HotkeySequenceRecorder, KEY_DISPLAY_SYMBOLS, KeyStateTracker, LETTER_KEYS, LINUX_MODIFIER_LABELS, MAC_MODIFIER_LABELS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, PUNCTUATION_KEY_DISPLAY_LABELS, SequenceManager, WINDOWS_MODIFIER_LABELS, assertValidHotkey, checkHotkey, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifierKey, isSingleLetterKey, matchesKeyboardEvent, normalizeHotkey, normalizeHotkeyFromEvent, normalizeHotkeyFromParsed, normalizeKeyName, normalizeRegisterableHotkey, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, validateHotkey };
12
+ export { ALL_KEYS, DEFAULT_SEQUENCE_TIMEOUT, EDITING_KEYS, FUNCTION_KEYS, HotkeyManager, HotkeyRecorder, HotkeySequenceRecorder, KEY_DISPLAY_SYMBOLS, KeyStateTracker, LETTER_KEYS, LINUX_MODIFIER_LABELS, MAC_MODIFIER_LABELS, MAC_MODIFIER_SYMBOLS, MODIFIER_ALIASES, MODIFIER_KEYS, MODIFIER_ORDER, NAVIGATION_KEYS, NUMBER_KEYS, PUNCTUATION_CODE_MAP, PUNCTUATION_KEYS, PUNCTUATION_KEY_DISPLAY_LABELS, SequenceManager, WINDOWS_MODIFIER_LABELS, assertValidHotkey, checkHotkey, createHotkeyHandler, createMultiHotkeyHandler, createSequenceMatcher, detectPlatform, formatForDisplay, formatHotkey, formatHotkeySequence, formatWithLabels, getHotkeyManager, getKeyStateTracker, getSequenceManager, hasNonModifierKey, isModifierKey, isSingleLetterKey, matchesKeyboardEvent, normalizeHotkey, normalizeHotkeyFromEvent, normalizeHotkeyFromParsed, normalizeKeyName, normalizeRegisterableHotkey, parseHotkey, parseKeyboardEvent, rawHotkeyToParsedHotkey, resolveModifier, toHotkeyRegistrationView, validateHotkey };
@@ -110,5 +110,6 @@ exports.defaultHotkeyOptions = defaultHotkeyOptions;
110
110
  exports.getDefaultIgnoreInputs = getDefaultIgnoreInputs;
111
111
  exports.handleConflict = handleConflict;
112
112
  exports.isEventForTarget = isEventForTarget;
113
+ exports.isInputElement = isInputElement;
113
114
  exports.shouldIgnoreInputEvent = shouldIgnoreInputEvent;
114
115
  //# sourceMappingURL=manager.utils.cjs.map
@@ -105,5 +105,5 @@ function handleConflict(conflictingId, keyDisplay, conflictBehavior, unregister)
105
105
  }
106
106
 
107
107
  //#endregion
108
- export { defaultHotkeyOptions, getDefaultIgnoreInputs, handleConflict, isEventForTarget, shouldIgnoreInputEvent };
108
+ export { defaultHotkeyOptions, getDefaultIgnoreInputs, handleConflict, isEventForTarget, isInputElement, shouldIgnoreInputEvent };
109
109
  //# sourceMappingURL=manager.utils.js.map
@@ -61,6 +61,7 @@ function toRegistrationView(reg) {
61
61
  options: reg.options,
62
62
  target: reg.target,
63
63
  triggerCount: reg.triggerCount,
64
+ hasFired: reg.hasFired,
64
65
  matchedStepCount: inProgress ? reg.currentIndex : 0,
65
66
  partialMatchLastKeyTime: inProgress ? reg.lastKeyTime : 0
66
67
  };
@@ -128,7 +129,8 @@ var SequenceManager = class SequenceManager {
128
129
  target,
129
130
  currentIndex: 0,
130
131
  lastKeyTime: 0,
131
- triggerCount: 0
132
+ triggerCount: 0,
133
+ hasFired: false
132
134
  };
133
135
  this.#registrations.set(id, registration);
134
136
  this.registrations.setState((prev) => new Map(prev).set(id, toRegistrationView(registration)));
@@ -262,6 +264,7 @@ var SequenceManager = class SequenceManager {
262
264
  parsedHotkey: registration.parsedSequence[registration.parsedSequence.length - 1]
263
265
  };
264
266
  registration.triggerCount++;
267
+ registration.hasFired = true;
265
268
  registration.currentIndex = 0;
266
269
  this.#syncRegistrationView(registration);
267
270
  registration.callback(event, context);
@@ -316,6 +319,7 @@ var SequenceManager = class SequenceManager {
316
319
  cancelable: true
317
320
  });
318
321
  registration.triggerCount++;
322
+ registration.hasFired = true;
319
323
  this.#syncRegistrationView(registration);
320
324
  const context = {
321
325
  hotkey: registration.sequence.join(" "),
@@ -1 +1 @@
1
- {"version":3,"file":"sequence-manager.cjs","names":["#instance","Store","#platform","detectPlatform","parseHotkey","#findConflictingSequence","formatHotkeySequence","#unregister","getDefaultIgnoreInputs","defaultHotkeyOptions","#registrations","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","#processTargetEvent","isModifierKey","normalizeKeyName","isEventForTarget","shouldIgnoreInputEvent","#syncRegistrationView","matchesKeyboardEvent"],"sources":["../src/sequence-manager.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { formatHotkeySequence } from './format'\nimport { detectPlatform, normalizeKeyName } from './constants'\nimport { isModifierKey, parseHotkey } from './parse'\nimport { matchesKeyboardEvent } from './match'\nimport {\n defaultHotkeyOptions,\n getDefaultIgnoreInputs,\n handleConflict,\n isEventForTarget,\n shouldIgnoreInputEvent,\n} from './manager.utils'\nimport type { HotkeyOptions } from './hotkey-manager'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\ntype Target = HTMLElement | Document | Window\n\n/**\n * Options for hotkey sequence matching.\n * Extends HotkeyOptions but excludes requireReset (not applicable to sequences).\n */\nexport interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {\n /** Timeout between keys in milliseconds. Default: 1000 */\n timeout?: number\n}\n\n/**\n * A sequence of hotkeys for Vim-style shortcuts.\n *\n * Each element is one step (a `Hotkey` string). Steps may include modifiers;\n * the same modifier can appear on consecutive steps (e.g. `Shift+R` then\n * `Shift+T`). Modifier-only key events do not advance or reset matching—see\n * `SequenceManager`.\n *\n * @example\n * ```ts\n * const gotoTop: HotkeySequence = ['G', 'G'] // gg\n * const deleteLine: HotkeySequence = ['D', 'D'] // dd\n * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw\n * const chainedShift: HotkeySequence = ['Shift+R', 'Shift+T']\n * ```\n */\nexport type HotkeySequence = Array<Hotkey>\n\n/**\n * Default timeout between keys in a sequence (in milliseconds).\n * Exported for consumers that display sequence state (e.g. devtools).\n */\nexport const DEFAULT_SEQUENCE_TIMEOUT = 1000\n\nlet sequenceIdCounter = 0\n\n/**\n * Generates a unique ID for sequence registrations.\n */\nfunction generateSequenceId(): string {\n return `sequence_${++sequenceIdCounter}`\n}\n\n/**\n * Returns a canonical string for sequence conflict comparison.\n */\nfunction sequenceKey(sequence: HotkeySequence): string {\n return sequence.join('|')\n}\n\n/**\n * View of a sequence registration for devtools display.\n * Progress fields reflect an in-progress match (between first key and completion or timeout).\n */\nexport interface SequenceRegistrationView {\n id: string\n sequence: HotkeySequence\n options: SequenceOptions\n target: Target\n triggerCount: number\n /** Steps matched in the current attempt (0 when idle or just completed). */\n matchedStepCount: number\n /** `Date.now()` when the last step in the current attempt matched; 0 if none. */\n partialMatchLastKeyTime: number\n}\n\n/**\n * Internal representation of a sequence registration.\n */\ninterface SequenceRegistration {\n id: string\n sequence: HotkeySequence\n parsedSequence: Array<ParsedHotkey>\n callback: HotkeyCallback\n options: SequenceOptions\n target: Target\n currentIndex: number\n lastKeyTime: number\n triggerCount: number\n}\n\n/**\n * A handle returned from SequenceManager.register() that allows updating\n * the callback and options without re-registering the sequence.\n *\n * @example\n * ```ts\n * const handle = manager.register(['G', 'G'], callback, options)\n *\n * handle.callback = newCallback\n * handle.setOptions({ timeout: 500 })\n * handle.unregister()\n * ```\n */\nexport interface SequenceRegistrationHandle {\n readonly id: string\n readonly isActive: boolean\n callback: HotkeyCallback\n setOptions: (options: Partial<SequenceOptions>) => void\n unregister: () => void\n}\n\n/**\n * Manages keyboard sequence matching for Vim-style shortcuts.\n *\n * This class allows registering multi-key sequences like 'g g' or 'd d'\n * that trigger callbacks when the full sequence is pressed within\n * a configurable timeout.\n *\n * Modifier-only `keydown` / `keyup` events (Shift, Control, Alt, or Meta\n * alone) are not processed: they neither match a step nor reset progress.\n * That supports chained modifier chords (e.g. `Shift+R` then `Shift+T`) when\n * the user presses a modifier alone between steps.\n *\n * @example\n * ```ts\n * const matcher = SequenceManager.getInstance()\n *\n * // Register 'g g' to go to top\n * const unregister = matcher.register(['G', 'G'], (event, context) => {\n * scrollToTop()\n * }, { timeout: 500 })\n *\n * // Later, to unregister:\n * unregister()\n * ```\n */\n/**\n * Builds a devtools view from an internal registration.\n */\nfunction toRegistrationView(\n reg: SequenceRegistration,\n): SequenceRegistrationView {\n const len = reg.parsedSequence.length\n const inProgress = reg.currentIndex > 0 && reg.currentIndex < len\n return {\n id: reg.id,\n sequence: reg.sequence,\n options: reg.options,\n target: reg.target,\n triggerCount: reg.triggerCount,\n matchedStepCount: inProgress ? reg.currentIndex : 0,\n partialMatchLastKeyTime: inProgress ? reg.lastKeyTime : 0,\n }\n}\n\nexport class SequenceManager {\n static #instance: SequenceManager | null = null\n\n /**\n * The TanStack Store containing sequence registration views for devtools.\n * Subscribe to this to observe registration changes.\n */\n readonly registrations: Store<Map<string, SequenceRegistrationView>> =\n new Store(new Map())\n\n #registrations: Map<string, SequenceRegistration> = new Map()\n #targetListeners: Map<\n Target,\n {\n keydown: (event: KeyboardEvent) => void\n keyup: (event: KeyboardEvent) => void\n }\n > = new Map()\n #targetRegistrations: Map<Target, Set<string>> = new Map()\n #platform: 'mac' | 'windows' | 'linux'\n\n private constructor() {\n this.#platform = detectPlatform()\n }\n\n /**\n * Gets the singleton instance of SequenceManager.\n */\n static getInstance(): SequenceManager {\n if (!SequenceManager.#instance) {\n SequenceManager.#instance = new SequenceManager()\n }\n return SequenceManager.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (SequenceManager.#instance) {\n SequenceManager.#instance.destroy()\n SequenceManager.#instance = null\n }\n }\n\n #syncRegistrationView(registration: SequenceRegistration): void {\n this.registrations.setState((prev) =>\n new Map(prev).set(registration.id, toRegistrationView(registration)),\n )\n }\n\n /**\n * Registers a hotkey sequence handler.\n *\n * @param sequence - Array of hotkey strings that form the sequence\n * @param callback - Function to call when the sequence is completed\n * @param options - Options for the sequence behavior\n * @returns A handle to update or unregister the sequence\n */\n register(\n sequence: HotkeySequence,\n callback: HotkeyCallback,\n options: SequenceOptions = {},\n ): SequenceRegistrationHandle {\n if (sequence.length === 0) {\n throw new Error('Sequence must contain at least one hotkey')\n }\n\n const id = generateSequenceId()\n const platform = options.platform ?? this.#platform\n const parsedSequence = sequence.map((hotkey) =>\n parseHotkey(hotkey, platform),\n )\n\n // Resolve target: default to document if not provided or null\n const target: Target =\n options.target ??\n (typeof document !== 'undefined' ? document : ({} as Document))\n\n // Resolve conflict behavior\n const conflictBehavior = options.conflictBehavior ?? 'warn'\n\n // Check for existing registrations with the same sequence and target\n const conflictingRegistration = this.#findConflictingSequence(\n sequence,\n target,\n )\n\n if (conflictingRegistration) {\n handleConflict(\n conflictingRegistration.id,\n formatHotkeySequence(sequence),\n conflictBehavior,\n (regId) => this.#unregister(regId),\n )\n }\n\n const firstStep = parsedSequence[0]!\n const resolvedIgnoreInputs =\n options.ignoreInputs ?? getDefaultIgnoreInputs(firstStep)\n\n const baseOptions = {\n ...defaultHotkeyOptions,\n timeout: DEFAULT_SEQUENCE_TIMEOUT,\n ...options,\n platform,\n ignoreInputs: resolvedIgnoreInputs,\n }\n\n const registration: SequenceRegistration = {\n id,\n sequence,\n parsedSequence,\n callback,\n options: baseOptions,\n target,\n currentIndex: 0,\n lastKeyTime: 0,\n triggerCount: 0,\n }\n\n this.#registrations.set(id, registration)\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n // Track registration for this target\n if (!this.#targetRegistrations.has(target)) {\n this.#targetRegistrations.set(target, new Set())\n }\n this.#targetRegistrations.get(target)!.add(id)\n\n // Ensure listeners are attached for this target\n this.#ensureListenersForTarget(target)\n\n const manager = this\n const handle: SequenceRegistrationHandle = {\n get id() {\n return id\n },\n get isActive() {\n return manager.#registrations.has(id)\n },\n get callback() {\n const reg = manager.#registrations.get(id)\n return reg?.callback ?? callback\n },\n set callback(newCallback: HotkeyCallback) {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.callback = newCallback\n }\n },\n setOptions: (newOptions: Partial<SequenceOptions>) => {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.options = { ...reg.options, ...newOptions }\n manager.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(reg)),\n )\n }\n },\n unregister: () => {\n manager.#unregister(id)\n },\n }\n\n return handle\n }\n\n /**\n * Unregisters a sequence by its registration ID.\n */\n #unregister(id: string): void {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return\n }\n\n const target = registration.target\n\n this.#registrations.delete(id)\n this.registrations.setState((prev) => {\n const next = new Map(prev)\n next.delete(id)\n return next\n })\n\n // Remove from target registrations tracking\n const targetRegs = this.#targetRegistrations.get(target)\n if (targetRegs) {\n targetRegs.delete(id)\n if (targetRegs.size === 0) {\n this.#removeListenersForTarget(target)\n }\n }\n }\n\n /**\n * Ensures event listeners are attached for a specific target.\n */\n #ensureListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n if (this.#targetListeners.has(target)) {\n return\n }\n\n const keydownHandler = this.#createTargetKeyDownHandler(target)\n const keyupHandler = this.#createTargetKeyUpHandler(target)\n\n target.addEventListener('keydown', keydownHandler as EventListener)\n target.addEventListener('keyup', keyupHandler as EventListener)\n\n this.#targetListeners.set(target, {\n keydown: keydownHandler,\n keyup: keyupHandler,\n })\n }\n\n /**\n * Removes event listeners for a specific target.\n */\n #removeListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const listeners = this.#targetListeners.get(target)\n if (!listeners) {\n return\n }\n\n target.removeEventListener('keydown', listeners.keydown as EventListener)\n target.removeEventListener('keyup', listeners.keyup as EventListener)\n\n this.#targetListeners.delete(target)\n this.#targetRegistrations.delete(target)\n }\n\n /**\n * Creates a keydown handler for a specific target.\n */\n #createTargetKeyDownHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keydown')\n }\n }\n\n /**\n * Creates a keyup handler for a specific target.\n */\n #createTargetKeyUpHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keyup')\n }\n }\n\n /**\n * Processes keyboard events for a specific target and event type.\n */\n #processTargetEvent(\n event: KeyboardEvent,\n target: Target,\n eventType: 'keydown' | 'keyup',\n ): void {\n // Skip modifier-only events so pressing e.g. Shift before Shift+C does not reset the sequence.\n if (isModifierKey(normalizeKeyName(event.key))) {\n return\n }\n\n const targetRegs = this.#targetRegistrations.get(target)\n if (!targetRegs) {\n return\n }\n\n const now = Date.now()\n\n registrationIds: for (const id of targetRegs) {\n const registration = this.#registrations.get(id)\n if (!registration) {\n continue\n }\n\n if (!isEventForTarget(event, target)) {\n continue\n }\n\n if (!registration.options.enabled) {\n continue\n }\n\n // Check if we should ignore input elements (defaults to true)\n if (registration.options.ignoreInputs !== false) {\n if (shouldIgnoreInputEvent(event, target, registration.target)) {\n continue registrationIds\n }\n }\n\n // Only process registrations that listen for this event type\n if (registration.options.eventType !== eventType) {\n continue\n }\n\n const timeout = registration.options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n\n // Check if sequence has timed out\n if (\n registration.currentIndex > 0 &&\n now - registration.lastKeyTime > timeout\n ) {\n registration.currentIndex = 0\n this.#syncRegistrationView(registration)\n }\n\n const expectedHotkey =\n registration.parsedSequence[registration.currentIndex]\n if (!expectedHotkey) {\n continue\n }\n\n if (\n matchesKeyboardEvent(\n event,\n expectedHotkey,\n registration.options.platform,\n )\n ) {\n registration.lastKeyTime = now\n registration.currentIndex++\n\n if (registration.currentIndex >= registration.parsedSequence.length) {\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey:\n registration.parsedSequence[\n registration.parsedSequence.length - 1\n ]!,\n }\n\n registration.triggerCount++\n registration.currentIndex = 0\n\n this.#syncRegistrationView(registration)\n\n registration.callback(event, context)\n } else {\n this.#syncRegistrationView(registration)\n }\n } else if (registration.currentIndex > 0) {\n const firstHotkey = registration.parsedSequence[0]!\n if (\n matchesKeyboardEvent(\n event,\n firstHotkey,\n registration.options.platform,\n )\n ) {\n registration.currentIndex = 1\n registration.lastKeyTime = now\n } else {\n registration.currentIndex = 0\n }\n this.#syncRegistrationView(registration)\n }\n }\n }\n\n /**\n * Finds an existing registration with the same sequence and target.\n */\n #findConflictingSequence(\n sequence: HotkeySequence,\n target: Target,\n ): SequenceRegistration | null {\n const key = sequenceKey(sequence)\n for (const registration of this.#registrations.values()) {\n if (\n sequenceKey(registration.sequence) === key &&\n registration.target === target\n ) {\n return registration\n }\n }\n return null\n }\n\n /**\n * Resets all sequence progress.\n */\n resetAll(): void {\n for (const registration of this.#registrations.values()) {\n registration.currentIndex = 0\n registration.lastKeyTime = 0\n this.#syncRegistrationView(registration)\n }\n }\n\n /**\n * Triggers a sequence's callback programmatically from devtools.\n * Creates a synthetic KeyboardEvent from the last key in the sequence.\n *\n * @param id - The registration ID to trigger\n * @returns True if the registration was found and triggered\n */\n triggerSequence(id: string): boolean {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return false\n }\n\n const lastParsed =\n registration.parsedSequence[registration.parsedSequence.length - 1]\n if (!lastParsed) {\n return false\n }\n\n const syntheticEvent = new KeyboardEvent(\n registration.options.eventType ?? 'keydown',\n {\n key: lastParsed.key,\n ctrlKey: lastParsed.ctrl,\n shiftKey: lastParsed.shift,\n altKey: lastParsed.alt,\n metaKey: lastParsed.meta,\n bubbles: true,\n cancelable: true,\n },\n )\n\n registration.triggerCount++\n\n this.#syncRegistrationView(registration)\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey: lastParsed,\n }\n\n registration.callback(syntheticEvent, context)\n\n return true\n }\n\n /**\n * Gets the number of registered sequences.\n */\n getRegistrationCount(): number {\n return this.#registrations.size\n }\n\n /**\n * Destroys the manager and removes all listeners.\n */\n destroy(): void {\n for (const target of this.#targetListeners.keys()) {\n this.#removeListenersForTarget(target)\n }\n this.#registrations.clear()\n this.registrations.setState(() => new Map())\n }\n}\n\n/**\n * Gets the singleton SequenceManager instance.\n * Convenience function for accessing the manager.\n */\nexport function getSequenceManager(): SequenceManager {\n return SequenceManager.getInstance()\n}\n\n/**\n * Creates a simple sequence matcher for one-off use.\n *\n * This is a low-level helper that does not support ignoreInputs, target,\n * or other HotkeyOptions. Callers must handle input filtering themselves\n * if attaching to document.\n *\n * @param sequence - The sequence of hotkeys to match\n * @param options - Options including timeout\n * @returns An object with match() and reset() methods\n *\n * @example\n * ```ts\n * const matcher = createSequenceMatcher(['G', 'G'], { timeout: 500 })\n *\n * document.addEventListener('keydown', (event) => {\n * if (matcher.match(event)) {\n * console.log('Sequence matched!')\n * }\n * })\n * ```\n */\nexport function createSequenceMatcher(\n sequence: HotkeySequence,\n options: { timeout?: number; platform?: 'mac' | 'windows' | 'linux' } = {},\n): {\n match: (event: KeyboardEvent) => boolean\n reset: () => void\n getProgress: () => number\n} {\n const platform = options.platform ?? detectPlatform()\n const timeout = options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n const parsedSequence = sequence.map((hotkey) => parseHotkey(hotkey, platform))\n\n let currentIndex = 0\n let lastKeyTime = 0\n\n return {\n match(event: KeyboardEvent): boolean {\n const now = Date.now()\n\n if (currentIndex > 0 && now - lastKeyTime > timeout) {\n currentIndex = 0\n }\n\n const expected = parsedSequence[currentIndex]\n if (!expected) {\n return false\n }\n\n if (matchesKeyboardEvent(event, expected, platform)) {\n lastKeyTime = now\n currentIndex++\n\n if (currentIndex >= parsedSequence.length) {\n currentIndex = 0\n return true\n }\n } else if (currentIndex > 0) {\n if (matchesKeyboardEvent(event, parsedSequence[0]!, platform)) {\n currentIndex = 1\n lastKeyTime = now\n } else {\n currentIndex = 0\n }\n }\n\n return false\n },\n\n reset(): void {\n currentIndex = 0\n lastKeyTime = 0\n },\n\n getProgress(): number {\n return currentIndex\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;AAqDA,MAAa,2BAA2B;AAExC,IAAI,oBAAoB;;;;AAKxB,SAAS,qBAA6B;AACpC,QAAO,YAAY,EAAE;;;;;AAMvB,SAAS,YAAY,UAAkC;AACrD,QAAO,SAAS,KAAK,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmF3B,SAAS,mBACP,KAC0B;CAC1B,MAAM,MAAM,IAAI,eAAe;CAC/B,MAAM,aAAa,IAAI,eAAe,KAAK,IAAI,eAAe;AAC9D,QAAO;EACL,IAA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SAAS,CAAC;CAE9E,IAAI,eAAe;CACnB,IAAI,cAAc;AAElB,QAAO;EACL,MAAM,OAA+B;GACnC,MAAM,MAAM,KAAK,KAAK;AAEtB,OAAI,eAAe,KAAK,MAAM,cAAc,QAC1C,gBAAe;GAGjB,MAAM,WAAW,eAAe;AAChC,OAAI,CAAC,SACH,QAAO;AAGT,OAAImB,mCAAqB,OAAO,UAAU,SAAS,EAAE;AACnD,kBAAc;AACd;AAEA,QAAI,gBAAgB,eAAe,QAAQ;AACzC,oBAAe;AACf,YAAO;;cAEA,eAAe,EACxB,KAAIA,mCAAqB,OAAO,eAAe,IAAK,SAAS,EAAE;AAC7D,mBAAe;AACf,kBAAc;SAEd,gBAAe;AAInB,UAAO;;EAGT,QAAc;AACZ,kBAAe;AACf,iBAAc;;EAGhB,cAAsB;AACpB,UAAO;;EAEV"}
1
+ {"version":3,"file":"sequence-manager.cjs","names":["#instance","Store","#platform","detectPlatform","parseHotkey","#findConflictingSequence","formatHotkeySequence","#unregister","getDefaultIgnoreInputs","defaultHotkeyOptions","#registrations","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","#processTargetEvent","isModifierKey","normalizeKeyName","isEventForTarget","shouldIgnoreInputEvent","#syncRegistrationView","matchesKeyboardEvent"],"sources":["../src/sequence-manager.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport { formatHotkeySequence } from './format'\nimport { detectPlatform, normalizeKeyName } from './constants'\nimport { isModifierKey, parseHotkey } from './parse'\nimport { matchesKeyboardEvent } from './match'\nimport {\n defaultHotkeyOptions,\n getDefaultIgnoreInputs,\n handleConflict,\n isEventForTarget,\n shouldIgnoreInputEvent,\n} from './manager.utils'\nimport type { HotkeyOptions } from './hotkey-manager'\nimport type {\n Hotkey,\n HotkeyCallback,\n HotkeyCallbackContext,\n ParsedHotkey,\n} from './hotkey'\n\ntype Target = HTMLElement | Document | Window\n\n/**\n * Options for hotkey sequence matching.\n * Extends HotkeyOptions but excludes requireReset (not applicable to sequences).\n */\nexport interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {\n /** Timeout between keys in milliseconds. Default: 1000 */\n timeout?: number\n}\n\n/**\n * A sequence of hotkeys for Vim-style shortcuts.\n *\n * Each element is one step (a `Hotkey` string). Steps may include modifiers;\n * the same modifier can appear on consecutive steps (e.g. `Shift+R` then\n * `Shift+T`). Modifier-only key events do not advance or reset matching—see\n * `SequenceManager`.\n *\n * @example\n * ```ts\n * const gotoTop: HotkeySequence = ['G', 'G'] // gg\n * const deleteLine: HotkeySequence = ['D', 'D'] // dd\n * const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw\n * const chainedShift: HotkeySequence = ['Shift+R', 'Shift+T']\n * ```\n */\nexport type HotkeySequence = Array<Hotkey>\n\n/**\n * Default timeout between keys in a sequence (in milliseconds).\n * Exported for consumers that display sequence state (e.g. devtools).\n */\nexport const DEFAULT_SEQUENCE_TIMEOUT = 1000\n\nlet sequenceIdCounter = 0\n\n/**\n * Generates a unique ID for sequence registrations.\n */\nfunction generateSequenceId(): string {\n return `sequence_${++sequenceIdCounter}`\n}\n\n/**\n * Returns a canonical string for sequence conflict comparison.\n */\nfunction sequenceKey(sequence: HotkeySequence): string {\n return sequence.join('|')\n}\n\n/**\n * View of a sequence registration for devtools display.\n * Progress fields reflect an in-progress match (between first key and completion or timeout).\n */\nexport interface SequenceRegistrationView {\n id: string\n sequence: HotkeySequence\n options: SequenceOptions\n target: Target\n triggerCount: number\n /** Whether this sequence has been triggered at least once. */\n hasFired: boolean\n /** Steps matched in the current attempt (0 when idle or just completed). */\n matchedStepCount: number\n /** `Date.now()` when the last step in the current attempt matched; 0 if none. */\n partialMatchLastKeyTime: number\n}\n\n/**\n * Internal representation of a sequence registration.\n */\ninterface SequenceRegistration {\n id: string\n sequence: HotkeySequence\n parsedSequence: Array<ParsedHotkey>\n callback: HotkeyCallback\n options: SequenceOptions\n target: Target\n currentIndex: number\n lastKeyTime: number\n triggerCount: number\n hasFired: boolean\n}\n\n/**\n * A handle returned from SequenceManager.register() that allows updating\n * the callback and options without re-registering the sequence.\n *\n * @example\n * ```ts\n * const handle = manager.register(['G', 'G'], callback, options)\n *\n * handle.callback = newCallback\n * handle.setOptions({ timeout: 500 })\n * handle.unregister()\n * ```\n */\nexport interface SequenceRegistrationHandle {\n readonly id: string\n readonly isActive: boolean\n callback: HotkeyCallback\n setOptions: (options: Partial<SequenceOptions>) => void\n unregister: () => void\n}\n\n/**\n * Manages keyboard sequence matching for Vim-style shortcuts.\n *\n * This class allows registering multi-key sequences like 'g g' or 'd d'\n * that trigger callbacks when the full sequence is pressed within\n * a configurable timeout.\n *\n * Modifier-only `keydown` / `keyup` events (Shift, Control, Alt, or Meta\n * alone) are not processed: they neither match a step nor reset progress.\n * That supports chained modifier chords (e.g. `Shift+R` then `Shift+T`) when\n * the user presses a modifier alone between steps.\n *\n * @example\n * ```ts\n * const matcher = SequenceManager.getInstance()\n *\n * // Register 'g g' to go to top\n * const unregister = matcher.register(['G', 'G'], (event, context) => {\n * scrollToTop()\n * }, { timeout: 500 })\n *\n * // Later, to unregister:\n * unregister()\n * ```\n */\n/**\n * Builds a devtools view from an internal registration.\n */\nfunction toRegistrationView(\n reg: SequenceRegistration,\n): SequenceRegistrationView {\n const len = reg.parsedSequence.length\n const inProgress = reg.currentIndex > 0 && reg.currentIndex < len\n return {\n id: reg.id,\n sequence: reg.sequence,\n options: reg.options,\n target: reg.target,\n triggerCount: reg.triggerCount,\n hasFired: reg.hasFired,\n matchedStepCount: inProgress ? reg.currentIndex : 0,\n partialMatchLastKeyTime: inProgress ? reg.lastKeyTime : 0,\n }\n}\n\nexport class SequenceManager {\n static #instance: SequenceManager | null = null\n\n /**\n * The TanStack Store containing sequence registration views for devtools.\n * Subscribe to this to observe registration changes.\n */\n readonly registrations: Store<Map<string, SequenceRegistrationView>> =\n new Store(new Map())\n\n #registrations: Map<string, SequenceRegistration> = new Map()\n #targetListeners: Map<\n Target,\n {\n keydown: (event: KeyboardEvent) => void\n keyup: (event: KeyboardEvent) => void\n }\n > = new Map()\n #targetRegistrations: Map<Target, Set<string>> = new Map()\n #platform: 'mac' | 'windows' | 'linux'\n\n private constructor() {\n this.#platform = detectPlatform()\n }\n\n /**\n * Gets the singleton instance of SequenceManager.\n */\n static getInstance(): SequenceManager {\n if (!SequenceManager.#instance) {\n SequenceManager.#instance = new SequenceManager()\n }\n return SequenceManager.#instance\n }\n\n /**\n * Resets the singleton instance. Useful for testing.\n */\n static resetInstance(): void {\n if (SequenceManager.#instance) {\n SequenceManager.#instance.destroy()\n SequenceManager.#instance = null\n }\n }\n\n #syncRegistrationView(registration: SequenceRegistration): void {\n this.registrations.setState((prev) =>\n new Map(prev).set(registration.id, toRegistrationView(registration)),\n )\n }\n\n /**\n * Registers a hotkey sequence handler.\n *\n * @param sequence - Array of hotkey strings that form the sequence\n * @param callback - Function to call when the sequence is completed\n * @param options - Options for the sequence behavior\n * @returns A handle to update or unregister the sequence\n */\n register(\n sequence: HotkeySequence,\n callback: HotkeyCallback,\n options: SequenceOptions = {},\n ): SequenceRegistrationHandle {\n if (sequence.length === 0) {\n throw new Error('Sequence must contain at least one hotkey')\n }\n\n const id = generateSequenceId()\n const platform = options.platform ?? this.#platform\n const parsedSequence = sequence.map((hotkey) =>\n parseHotkey(hotkey, platform),\n )\n\n // Resolve target: default to document if not provided or null\n const target: Target =\n options.target ??\n (typeof document !== 'undefined' ? document : ({} as Document))\n\n // Resolve conflict behavior\n const conflictBehavior = options.conflictBehavior ?? 'warn'\n\n // Check for existing registrations with the same sequence and target\n const conflictingRegistration = this.#findConflictingSequence(\n sequence,\n target,\n )\n\n if (conflictingRegistration) {\n handleConflict(\n conflictingRegistration.id,\n formatHotkeySequence(sequence),\n conflictBehavior,\n (regId) => this.#unregister(regId),\n )\n }\n\n const firstStep = parsedSequence[0]!\n const resolvedIgnoreInputs =\n options.ignoreInputs ?? getDefaultIgnoreInputs(firstStep)\n\n const baseOptions = {\n ...defaultHotkeyOptions,\n timeout: DEFAULT_SEQUENCE_TIMEOUT,\n ...options,\n platform,\n ignoreInputs: resolvedIgnoreInputs,\n }\n\n const registration: SequenceRegistration = {\n id,\n sequence,\n parsedSequence,\n callback,\n options: baseOptions,\n target,\n currentIndex: 0,\n lastKeyTime: 0,\n triggerCount: 0,\n hasFired: false,\n }\n\n this.#registrations.set(id, registration)\n this.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(registration)),\n )\n\n // Track registration for this target\n if (!this.#targetRegistrations.has(target)) {\n this.#targetRegistrations.set(target, new Set())\n }\n this.#targetRegistrations.get(target)!.add(id)\n\n // Ensure listeners are attached for this target\n this.#ensureListenersForTarget(target)\n\n const manager = this\n const handle: SequenceRegistrationHandle = {\n get id() {\n return id\n },\n get isActive() {\n return manager.#registrations.has(id)\n },\n get callback() {\n const reg = manager.#registrations.get(id)\n return reg?.callback ?? callback\n },\n set callback(newCallback: HotkeyCallback) {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.callback = newCallback\n }\n },\n setOptions: (newOptions: Partial<SequenceOptions>) => {\n const reg = manager.#registrations.get(id)\n if (reg) {\n reg.options = { ...reg.options, ...newOptions }\n manager.registrations.setState((prev) =>\n new Map(prev).set(id, toRegistrationView(reg)),\n )\n }\n },\n unregister: () => {\n manager.#unregister(id)\n },\n }\n\n return handle\n }\n\n /**\n * Unregisters a sequence by its registration ID.\n */\n #unregister(id: string): void {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return\n }\n\n const target = registration.target\n\n this.#registrations.delete(id)\n this.registrations.setState((prev) => {\n const next = new Map(prev)\n next.delete(id)\n return next\n })\n\n // Remove from target registrations tracking\n const targetRegs = this.#targetRegistrations.get(target)\n if (targetRegs) {\n targetRegs.delete(id)\n if (targetRegs.size === 0) {\n this.#removeListenersForTarget(target)\n }\n }\n }\n\n /**\n * Ensures event listeners are attached for a specific target.\n */\n #ensureListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return // SSR safety\n }\n\n if (this.#targetListeners.has(target)) {\n return\n }\n\n const keydownHandler = this.#createTargetKeyDownHandler(target)\n const keyupHandler = this.#createTargetKeyUpHandler(target)\n\n target.addEventListener('keydown', keydownHandler as EventListener)\n target.addEventListener('keyup', keyupHandler as EventListener)\n\n this.#targetListeners.set(target, {\n keydown: keydownHandler,\n keyup: keyupHandler,\n })\n }\n\n /**\n * Removes event listeners for a specific target.\n */\n #removeListenersForTarget(target: Target): void {\n if (typeof document === 'undefined') {\n return\n }\n\n const listeners = this.#targetListeners.get(target)\n if (!listeners) {\n return\n }\n\n target.removeEventListener('keydown', listeners.keydown as EventListener)\n target.removeEventListener('keyup', listeners.keyup as EventListener)\n\n this.#targetListeners.delete(target)\n this.#targetRegistrations.delete(target)\n }\n\n /**\n * Creates a keydown handler for a specific target.\n */\n #createTargetKeyDownHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keydown')\n }\n }\n\n /**\n * Creates a keyup handler for a specific target.\n */\n #createTargetKeyUpHandler(target: Target): (event: KeyboardEvent) => void {\n return (event: KeyboardEvent) => {\n this.#processTargetEvent(event, target, 'keyup')\n }\n }\n\n /**\n * Processes keyboard events for a specific target and event type.\n */\n #processTargetEvent(\n event: KeyboardEvent,\n target: Target,\n eventType: 'keydown' | 'keyup',\n ): void {\n // Skip modifier-only events so pressing e.g. Shift before Shift+C does not reset the sequence.\n if (isModifierKey(normalizeKeyName(event.key))) {\n return\n }\n\n const targetRegs = this.#targetRegistrations.get(target)\n if (!targetRegs) {\n return\n }\n\n const now = Date.now()\n\n registrationIds: for (const id of targetRegs) {\n const registration = this.#registrations.get(id)\n if (!registration) {\n continue\n }\n\n if (!isEventForTarget(event, target)) {\n continue\n }\n\n if (!registration.options.enabled) {\n continue\n }\n\n // Check if we should ignore input elements (defaults to true)\n if (registration.options.ignoreInputs !== false) {\n if (shouldIgnoreInputEvent(event, target, registration.target)) {\n continue registrationIds\n }\n }\n\n // Only process registrations that listen for this event type\n if (registration.options.eventType !== eventType) {\n continue\n }\n\n const timeout = registration.options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n\n // Check if sequence has timed out\n if (\n registration.currentIndex > 0 &&\n now - registration.lastKeyTime > timeout\n ) {\n registration.currentIndex = 0\n this.#syncRegistrationView(registration)\n }\n\n const expectedHotkey =\n registration.parsedSequence[registration.currentIndex]\n if (!expectedHotkey) {\n continue\n }\n\n if (\n matchesKeyboardEvent(\n event,\n expectedHotkey,\n registration.options.platform,\n )\n ) {\n registration.lastKeyTime = now\n registration.currentIndex++\n\n if (registration.currentIndex >= registration.parsedSequence.length) {\n if (registration.options.preventDefault) {\n event.preventDefault()\n }\n if (registration.options.stopPropagation) {\n event.stopPropagation()\n }\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey:\n registration.parsedSequence[\n registration.parsedSequence.length - 1\n ]!,\n }\n\n registration.triggerCount++\n registration.hasFired = true\n registration.currentIndex = 0\n\n this.#syncRegistrationView(registration)\n\n registration.callback(event, context)\n } else {\n this.#syncRegistrationView(registration)\n }\n } else if (registration.currentIndex > 0) {\n const firstHotkey = registration.parsedSequence[0]!\n if (\n matchesKeyboardEvent(\n event,\n firstHotkey,\n registration.options.platform,\n )\n ) {\n registration.currentIndex = 1\n registration.lastKeyTime = now\n } else {\n registration.currentIndex = 0\n }\n this.#syncRegistrationView(registration)\n }\n }\n }\n\n /**\n * Finds an existing registration with the same sequence and target.\n */\n #findConflictingSequence(\n sequence: HotkeySequence,\n target: Target,\n ): SequenceRegistration | null {\n const key = sequenceKey(sequence)\n for (const registration of this.#registrations.values()) {\n if (\n sequenceKey(registration.sequence) === key &&\n registration.target === target\n ) {\n return registration\n }\n }\n return null\n }\n\n /**\n * Resets all sequence progress.\n */\n resetAll(): void {\n for (const registration of this.#registrations.values()) {\n registration.currentIndex = 0\n registration.lastKeyTime = 0\n this.#syncRegistrationView(registration)\n }\n }\n\n /**\n * Triggers a sequence's callback programmatically from devtools.\n * Creates a synthetic KeyboardEvent from the last key in the sequence.\n *\n * @param id - The registration ID to trigger\n * @returns True if the registration was found and triggered\n */\n triggerSequence(id: string): boolean {\n const registration = this.#registrations.get(id)\n if (!registration) {\n return false\n }\n\n const lastParsed =\n registration.parsedSequence[registration.parsedSequence.length - 1]\n if (!lastParsed) {\n return false\n }\n\n const syntheticEvent = new KeyboardEvent(\n registration.options.eventType ?? 'keydown',\n {\n key: lastParsed.key,\n ctrlKey: lastParsed.ctrl,\n shiftKey: lastParsed.shift,\n altKey: lastParsed.alt,\n metaKey: lastParsed.meta,\n bubbles: true,\n cancelable: true,\n },\n )\n\n registration.triggerCount++\n registration.hasFired = true\n\n this.#syncRegistrationView(registration)\n\n const context: HotkeyCallbackContext = {\n hotkey: registration.sequence.join(' ') as Hotkey,\n parsedHotkey: lastParsed,\n }\n\n registration.callback(syntheticEvent, context)\n\n return true\n }\n\n /**\n * Gets the number of registered sequences.\n */\n getRegistrationCount(): number {\n return this.#registrations.size\n }\n\n /**\n * Destroys the manager and removes all listeners.\n */\n destroy(): void {\n for (const target of this.#targetListeners.keys()) {\n this.#removeListenersForTarget(target)\n }\n this.#registrations.clear()\n this.registrations.setState(() => new Map())\n }\n}\n\n/**\n * Gets the singleton SequenceManager instance.\n * Convenience function for accessing the manager.\n */\nexport function getSequenceManager(): SequenceManager {\n return SequenceManager.getInstance()\n}\n\n/**\n * Creates a simple sequence matcher for one-off use.\n *\n * This is a low-level helper that does not support ignoreInputs, target,\n * or other HotkeyOptions. Callers must handle input filtering themselves\n * if attaching to document.\n *\n * @param sequence - The sequence of hotkeys to match\n * @param options - Options including timeout\n * @returns An object with match() and reset() methods\n *\n * @example\n * ```ts\n * const matcher = createSequenceMatcher(['G', 'G'], { timeout: 500 })\n *\n * document.addEventListener('keydown', (event) => {\n * if (matcher.match(event)) {\n * console.log('Sequence matched!')\n * }\n * })\n * ```\n */\nexport function createSequenceMatcher(\n sequence: HotkeySequence,\n options: { timeout?: number; platform?: 'mac' | 'windows' | 'linux' } = {},\n): {\n match: (event: KeyboardEvent) => boolean\n reset: () => void\n getProgress: () => number\n} {\n const platform = options.platform ?? detectPlatform()\n const timeout = options.timeout ?? DEFAULT_SEQUENCE_TIMEOUT\n const parsedSequence = sequence.map((hotkey) => parseHotkey(hotkey, platform))\n\n let currentIndex = 0\n let lastKeyTime = 0\n\n return {\n match(event: KeyboardEvent): boolean {\n const now = Date.now()\n\n if (currentIndex > 0 && now - lastKeyTime > timeout) {\n currentIndex = 0\n }\n\n const expected = parsedSequence[currentIndex]\n if (!expected) {\n return false\n }\n\n if (matchesKeyboardEvent(event, expected, platform)) {\n lastKeyTime = now\n currentIndex++\n\n if (currentIndex >= parsedSequence.length) {\n currentIndex = 0\n return true\n }\n } else if (currentIndex > 0) {\n if (matchesKeyboardEvent(event, parsedSequence[0]!, platform)) {\n currentIndex = 1\n lastKeyTime = now\n } else {\n currentIndex = 0\n }\n }\n\n return false\n },\n\n reset(): void {\n currentIndex = 0\n lastKeyTime = 0\n },\n\n getProgress(): number {\n return currentIndex\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;AAqDA,MAAa,2BAA2B;AAExC,IAAI,oBAAoB;;;;AAKxB,SAAS,qBAA6B;AACpC,QAAO,YAAY,EAAE;;;;;AAMvB,SAAS,YAAY,UAAkC;AACrD,QAAO,SAAS,KAAK,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsF3B,SAAS,mBACP,KAC0B;CAC1B,MAAM,MAAM,IAAI,eAAe;CAC/B,MAAM,aAAa,IAAI,eAAe,KAAK,IAAI,eAAe;AAC9D,QAAO;EACL,IAAI,IAAI;EACR,UAAU,IAAI;EACd,SAAS,IAAI;EACb,QAAQ,IAAI;EACZ,cAAc,IAAI;EAClB,UAAU,IAAI;EACd,kBAAkB,aAAa,IAAI,eAAe;EAClD,yBAAyB,aAAa,IAAI,cAAc;EACzD;;AAGH,IAAa,kBAAb,MAAa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,KAAK,MAAM,cAAc,QAC1C,gBAAe;GAGjB,MAAM,WAAW,eAAe;AAChC,OAAI,CAAC,SACH,QAAO;AAGT,OAAImB,mCAAqB,OAAO,UAAU,SAAS,EAAE;AACnD,kBAAc;AACd;AAEA,QAAI,gBAAgB,eAAe,QAAQ;AACzC,oBAAe;AACf,YAAO;;cAEA,eAAe,EACxB,KAAIA,mCAAqB,OAAO,eAAe,IAAK,SAAS,EAAE;AAC7D,mBAAe;AACf,kBAAc;SAEd,gBAAe;AAInB,UAAO;;EAGT,QAAc;AACZ,kBAAe;AACf,iBAAc;;EAGhB,cAAsB;AACpB,UAAO;;EAEV"}
@@ -44,6 +44,8 @@ interface SequenceRegistrationView {
44
44
  options: SequenceOptions;
45
45
  target: Target;
46
46
  triggerCount: number;
47
+ /** Whether this sequence has been triggered at least once. */
48
+ hasFired: boolean;
47
49
  /** Steps matched in the current attempt (0 when idle or just completed). */
48
50
  matchedStepCount: number;
49
51
  /** `Date.now()` when the last step in the current attempt matched; 0 if none. */
@@ -44,6 +44,8 @@ interface SequenceRegistrationView {
44
44
  options: SequenceOptions;
45
45
  target: Target;
46
46
  triggerCount: number;
47
+ /** Whether this sequence has been triggered at least once. */
48
+ hasFired: boolean;
47
49
  /** Steps matched in the current attempt (0 when idle or just completed). */
48
50
  matchedStepCount: number;
49
51
  /** `Date.now()` when the last step in the current attempt matched; 0 if none. */
@@ -61,6 +61,7 @@ function toRegistrationView(reg) {
61
61
  options: reg.options,
62
62
  target: reg.target,
63
63
  triggerCount: reg.triggerCount,
64
+ hasFired: reg.hasFired,
64
65
  matchedStepCount: inProgress ? reg.currentIndex : 0,
65
66
  partialMatchLastKeyTime: inProgress ? reg.lastKeyTime : 0
66
67
  };
@@ -128,7 +129,8 @@ var SequenceManager = class SequenceManager {
128
129
  target,
129
130
  currentIndex: 0,
130
131
  lastKeyTime: 0,
131
- triggerCount: 0
132
+ triggerCount: 0,
133
+ hasFired: false
132
134
  };
133
135
  this.#registrations.set(id, registration);
134
136
  this.registrations.setState((prev) => new Map(prev).set(id, toRegistrationView(registration)));
@@ -262,6 +264,7 @@ var SequenceManager = class SequenceManager {
262
264
  parsedHotkey: registration.parsedSequence[registration.parsedSequence.length - 1]
263
265
  };
264
266
  registration.triggerCount++;
267
+ registration.hasFired = true;
265
268
  registration.currentIndex = 0;
266
269
  this.#syncRegistrationView(registration);
267
270
  registration.callback(event, context);
@@ -316,6 +319,7 @@ var SequenceManager = class SequenceManager {
316
319
  cancelable: true
317
320
  });
318
321
  registration.triggerCount++;
322
+ registration.hasFired = true;
319
323
  this.#syncRegistrationView(registration);
320
324
  const context = {
321
325
  hotkey: registration.sequence.join(" "),