@tanstack/hotkeys 0.8.0 → 0.10.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.
- package/README.md +15 -1
- package/dist/{manager.utils.js → _event-target.js} +2 -41
- package/dist/_keyboard-event.js +75 -0
- package/dist/_match.js +48 -0
- package/dist/_named-keys.d.ts +6 -0
- package/dist/_named-keys.js +65 -0
- package/dist/_recorder-chord.js +42 -0
- package/dist/_recording-guard.js +55 -0
- package/dist/_registration.js +49 -0
- package/dist/conflicts.d.ts +36 -0
- package/dist/conflicts.js +54 -0
- package/dist/constants.d.ts +16 -144
- package/dist/constants.js +55 -172
- package/dist/display-labels.d.ts +90 -0
- package/dist/display-labels.js +112 -0
- package/dist/format.d.ts +48 -12
- package/dist/format.js +35 -39
- package/dist/hint.d.ts +20 -0
- package/dist/hint.js +23 -0
- package/dist/hotkey-manager.d.ts +14 -12
- package/dist/hotkey-manager.js +70 -21
- package/dist/hotkey-recorder.d.ts +8 -8
- package/dist/hotkey-recorder.js +74 -15
- package/dist/hotkey-sequence-recorder.d.ts +13 -9
- package/dist/hotkey-sequence-recorder.js +90 -28
- package/dist/{hotkey.d.ts → hotkey.types.d.ts} +58 -126
- package/dist/index.d.ts +14 -9
- package/dist/index.js +10 -6
- package/dist/key-state-tracker.d.ts +4 -7
- package/dist/key-state-tracker.js +30 -27
- package/dist/key.types.d.ts +79 -0
- package/dist/match.d.ts +24 -11
- package/dist/match.js +19 -30
- package/dist/parse.d.ts +18 -15
- package/dist/parse.js +39 -22
- package/dist/platform.d.ts +41 -0
- package/dist/platform.js +52 -0
- package/dist/recorder-options.d.ts +31 -0
- package/dist/sequence-manager.d.ts +27 -15
- package/dist/sequence-manager.js +61 -30
- package/dist/validate.d.ts +16 -8
- package/dist/validate.js +8 -13
- package/package.json +8 -13
- package/dist/constants.cjs +0 -535
- package/dist/constants.cjs.map +0 -1
- package/dist/constants.d.cts +0 -290
- package/dist/constants.js.map +0 -1
- package/dist/format.cjs +0 -91
- package/dist/format.cjs.map +0 -1
- package/dist/format.d.cts +0 -60
- package/dist/format.js.map +0 -1
- package/dist/hotkey-manager.cjs +0 -383
- package/dist/hotkey-manager.cjs.map +0 -1
- package/dist/hotkey-manager.d.cts +0 -230
- package/dist/hotkey-manager.js.map +0 -1
- package/dist/hotkey-recorder.cjs +0 -179
- package/dist/hotkey-recorder.cjs.map +0 -1
- package/dist/hotkey-recorder.d.cts +0 -116
- package/dist/hotkey-recorder.js.map +0 -1
- package/dist/hotkey-sequence-recorder.cjs +0 -192
- package/dist/hotkey-sequence-recorder.cjs.map +0 -1
- package/dist/hotkey-sequence-recorder.d.cts +0 -79
- package/dist/hotkey-sequence-recorder.js.map +0 -1
- package/dist/hotkey.d.cts +0 -301
- package/dist/index.cjs +0 -63
- package/dist/index.d.cts +0 -13
- package/dist/key-state-tracker.cjs +0 -197
- package/dist/key-state-tracker.cjs.map +0 -1
- package/dist/key-state-tracker.d.cts +0 -107
- package/dist/key-state-tracker.js.map +0 -1
- package/dist/manager.utils.cjs +0 -115
- package/dist/manager.utils.cjs.map +0 -1
- package/dist/manager.utils.d.cts +0 -13
- package/dist/manager.utils.d.ts +0 -13
- package/dist/manager.utils.js.map +0 -1
- package/dist/match.cjs +0 -153
- package/dist/match.cjs.map +0 -1
- package/dist/match.d.cts +0 -85
- package/dist/match.js.map +0 -1
- package/dist/parse.cjs +0 -228
- package/dist/parse.cjs.map +0 -1
- package/dist/parse.d.cts +0 -128
- package/dist/parse.js.map +0 -1
- package/dist/recorder-chord.cjs +0 -18
- package/dist/recorder-chord.cjs.map +0 -1
- package/dist/recorder-chord.js +0 -18
- package/dist/recorder-chord.js.map +0 -1
- package/dist/sequence-manager.cjs +0 -415
- package/dist/sequence-manager.cjs.map +0 -1
- package/dist/sequence-manager.d.cts +0 -157
- package/dist/sequence-manager.js.map +0 -1
- package/dist/validate.cjs +0 -116
- package/dist/validate.cjs.map +0 -1
- package/dist/validate.d.cts +0 -56
- package/dist/validate.js.map +0 -1
- package/src/constants.ts +0 -603
- package/src/format.ts +0 -142
- package/src/hotkey-manager.ts +0 -759
- package/src/hotkey-recorder.ts +0 -272
- package/src/hotkey-sequence-recorder.ts +0 -328
- package/src/hotkey.ts +0 -436
- package/src/index.ts +0 -11
- package/src/key-state-tracker.ts +0 -249
- package/src/manager.utils.ts +0 -231
- package/src/match.ts +0 -259
- package/src/parse.ts +0 -328
- package/src/recorder-chord.ts +0 -25
- package/src/sequence-manager.ts +0 -734
- package/src/validate.ts +0 -171
|
@@ -1 +0,0 @@
|
|
|
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,gBAAgB;CAC3B,QAAOA,WAAoC;CAS3C,iCAAoD,IAAI,KAAK;CAC7D,mCAMI,IAAI,KAAK;CACb,uCAAiD,IAAI,KAAK;CAC1D;CAEA,AAAQ,cAAc;uBAbpB,IAAIC,sCAAM,IAAI,KAAK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,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,157 +0,0 @@
|
|
|
1
|
-
import { Hotkey, HotkeyCallback } from "./hotkey.cjs";
|
|
2
|
-
import { HotkeyOptions } from "./hotkey-manager.cjs";
|
|
3
|
-
import { Store } from "@tanstack/store";
|
|
4
|
-
|
|
5
|
-
//#region src/sequence-manager.d.ts
|
|
6
|
-
type Target = HTMLElement | Document | Window;
|
|
7
|
-
/**
|
|
8
|
-
* Options for hotkey sequence matching.
|
|
9
|
-
* Extends HotkeyOptions but excludes requireReset (not applicable to sequences).
|
|
10
|
-
*/
|
|
11
|
-
interface SequenceOptions extends Omit<HotkeyOptions, 'requireReset'> {
|
|
12
|
-
/** Timeout between keys in milliseconds. Default: 1000 */
|
|
13
|
-
timeout?: number;
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* A sequence of hotkeys for Vim-style shortcuts.
|
|
17
|
-
*
|
|
18
|
-
* Each element is one step (a `Hotkey` string). Steps may include modifiers;
|
|
19
|
-
* the same modifier can appear on consecutive steps (e.g. `Shift+R` then
|
|
20
|
-
* `Shift+T`). Modifier-only key events do not advance or reset matching—see
|
|
21
|
-
* `SequenceManager`.
|
|
22
|
-
*
|
|
23
|
-
* @example
|
|
24
|
-
* ```ts
|
|
25
|
-
* const gotoTop: HotkeySequence = ['G', 'G'] // gg
|
|
26
|
-
* const deleteLine: HotkeySequence = ['D', 'D'] // dd
|
|
27
|
-
* const deleteWord: HotkeySequence = ['D', 'I', 'W'] // diw
|
|
28
|
-
* const chainedShift: HotkeySequence = ['Shift+R', 'Shift+T']
|
|
29
|
-
* ```
|
|
30
|
-
*/
|
|
31
|
-
type HotkeySequence = Array<Hotkey>;
|
|
32
|
-
/**
|
|
33
|
-
* Default timeout between keys in a sequence (in milliseconds).
|
|
34
|
-
* Exported for consumers that display sequence state (e.g. devtools).
|
|
35
|
-
*/
|
|
36
|
-
declare const DEFAULT_SEQUENCE_TIMEOUT = 1000;
|
|
37
|
-
/**
|
|
38
|
-
* View of a sequence registration for devtools display.
|
|
39
|
-
* Progress fields reflect an in-progress match (between first key and completion or timeout).
|
|
40
|
-
*/
|
|
41
|
-
interface SequenceRegistrationView {
|
|
42
|
-
id: string;
|
|
43
|
-
sequence: HotkeySequence;
|
|
44
|
-
options: SequenceOptions;
|
|
45
|
-
target: Target;
|
|
46
|
-
triggerCount: number;
|
|
47
|
-
/** Whether this sequence has been triggered at least once. */
|
|
48
|
-
hasFired: boolean;
|
|
49
|
-
/** Steps matched in the current attempt (0 when idle or just completed). */
|
|
50
|
-
matchedStepCount: number;
|
|
51
|
-
/** `Date.now()` when the last step in the current attempt matched; 0 if none. */
|
|
52
|
-
partialMatchLastKeyTime: number;
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* A handle returned from SequenceManager.register() that allows updating
|
|
56
|
-
* the callback and options without re-registering the sequence.
|
|
57
|
-
*
|
|
58
|
-
* @example
|
|
59
|
-
* ```ts
|
|
60
|
-
* const handle = manager.register(['G', 'G'], callback, options)
|
|
61
|
-
*
|
|
62
|
-
* handle.callback = newCallback
|
|
63
|
-
* handle.setOptions({ timeout: 500 })
|
|
64
|
-
* handle.unregister()
|
|
65
|
-
* ```
|
|
66
|
-
*/
|
|
67
|
-
interface SequenceRegistrationHandle {
|
|
68
|
-
readonly id: string;
|
|
69
|
-
readonly isActive: boolean;
|
|
70
|
-
callback: HotkeyCallback;
|
|
71
|
-
setOptions: (options: Partial<SequenceOptions>) => void;
|
|
72
|
-
unregister: () => void;
|
|
73
|
-
}
|
|
74
|
-
declare class SequenceManager {
|
|
75
|
-
#private;
|
|
76
|
-
/**
|
|
77
|
-
* The TanStack Store containing sequence registration views for devtools.
|
|
78
|
-
* Subscribe to this to observe registration changes.
|
|
79
|
-
*/
|
|
80
|
-
readonly registrations: Store<Map<string, SequenceRegistrationView>>;
|
|
81
|
-
private constructor();
|
|
82
|
-
/**
|
|
83
|
-
* Gets the singleton instance of SequenceManager.
|
|
84
|
-
*/
|
|
85
|
-
static getInstance(): SequenceManager;
|
|
86
|
-
/**
|
|
87
|
-
* Resets the singleton instance. Useful for testing.
|
|
88
|
-
*/
|
|
89
|
-
static resetInstance(): void;
|
|
90
|
-
/**
|
|
91
|
-
* Registers a hotkey sequence handler.
|
|
92
|
-
*
|
|
93
|
-
* @param sequence - Array of hotkey strings that form the sequence
|
|
94
|
-
* @param callback - Function to call when the sequence is completed
|
|
95
|
-
* @param options - Options for the sequence behavior
|
|
96
|
-
* @returns A handle to update or unregister the sequence
|
|
97
|
-
*/
|
|
98
|
-
register(sequence: HotkeySequence, callback: HotkeyCallback, options?: SequenceOptions): SequenceRegistrationHandle;
|
|
99
|
-
/**
|
|
100
|
-
* Resets all sequence progress.
|
|
101
|
-
*/
|
|
102
|
-
resetAll(): void;
|
|
103
|
-
/**
|
|
104
|
-
* Triggers a sequence's callback programmatically from devtools.
|
|
105
|
-
* Creates a synthetic KeyboardEvent from the last key in the sequence.
|
|
106
|
-
*
|
|
107
|
-
* @param id - The registration ID to trigger
|
|
108
|
-
* @returns True if the registration was found and triggered
|
|
109
|
-
*/
|
|
110
|
-
triggerSequence(id: string): boolean;
|
|
111
|
-
/**
|
|
112
|
-
* Gets the number of registered sequences.
|
|
113
|
-
*/
|
|
114
|
-
getRegistrationCount(): number;
|
|
115
|
-
/**
|
|
116
|
-
* Destroys the manager and removes all listeners.
|
|
117
|
-
*/
|
|
118
|
-
destroy(): void;
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* Gets the singleton SequenceManager instance.
|
|
122
|
-
* Convenience function for accessing the manager.
|
|
123
|
-
*/
|
|
124
|
-
declare function getSequenceManager(): SequenceManager;
|
|
125
|
-
/**
|
|
126
|
-
* Creates a simple sequence matcher for one-off use.
|
|
127
|
-
*
|
|
128
|
-
* This is a low-level helper that does not support ignoreInputs, target,
|
|
129
|
-
* or other HotkeyOptions. Callers must handle input filtering themselves
|
|
130
|
-
* if attaching to document.
|
|
131
|
-
*
|
|
132
|
-
* @param sequence - The sequence of hotkeys to match
|
|
133
|
-
* @param options - Options including timeout
|
|
134
|
-
* @returns An object with match() and reset() methods
|
|
135
|
-
*
|
|
136
|
-
* @example
|
|
137
|
-
* ```ts
|
|
138
|
-
* const matcher = createSequenceMatcher(['G', 'G'], { timeout: 500 })
|
|
139
|
-
*
|
|
140
|
-
* document.addEventListener('keydown', (event) => {
|
|
141
|
-
* if (matcher.match(event)) {
|
|
142
|
-
* console.log('Sequence matched!')
|
|
143
|
-
* }
|
|
144
|
-
* })
|
|
145
|
-
* ```
|
|
146
|
-
*/
|
|
147
|
-
declare function createSequenceMatcher(sequence: HotkeySequence, options?: {
|
|
148
|
-
timeout?: number;
|
|
149
|
-
platform?: 'mac' | 'windows' | 'linux';
|
|
150
|
-
}): {
|
|
151
|
-
match: (event: KeyboardEvent) => boolean;
|
|
152
|
-
reset: () => void;
|
|
153
|
-
getProgress: () => number;
|
|
154
|
-
};
|
|
155
|
-
//#endregion
|
|
156
|
-
export { DEFAULT_SEQUENCE_TIMEOUT, HotkeySequence, SequenceManager, SequenceOptions, SequenceRegistrationHandle, SequenceRegistrationView, createSequenceMatcher, getSequenceManager };
|
|
157
|
-
//# sourceMappingURL=sequence-manager.d.cts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sequence-manager.js","names":["#instance","#platform","#findConflictingSequence","#unregister","#registrations","#targetRegistrations","#ensureListenersForTarget","#removeListenersForTarget","#targetListeners","#createTargetKeyDownHandler","#createTargetKeyUpHandler","#processTargetEvent","#syncRegistrationView"],"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;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;AAyBtC,SAAgB,sBACd,UACA,UAAwE,EAAE,EAK1E;CACA,MAAM,WAAW,QAAQ,YAAY,gBAAgB;CACrD,MAAM,UAAU,QAAQ;CACxB,MAAM,iBAAiB,SAAS,KAAK,WAAW,YAAY,QAAQ,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,OAAI,qBAAqB,OAAO,UAAU,SAAS,EAAE;AACnD,kBAAc;AACd;AAEA,QAAI,gBAAgB,eAAe,QAAQ;AACzC,oBAAe;AACf,YAAO;;cAEA,eAAe,EACxB,KAAI,qBAAqB,OAAO,eAAe,IAAK,SAAS,EAAE;AAC7D,mBAAe;AACf,kBAAc;SAEd,gBAAe;AAInB,UAAO;;EAGT,QAAc;AACZ,kBAAe;AACf,iBAAc;;EAGhB,cAAsB;AACpB,UAAO;;EAEV"}
|
package/dist/validate.cjs
DELETED
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
const require_constants = require('./constants.cjs');
|
|
2
|
-
|
|
3
|
-
//#region src/validate.ts
|
|
4
|
-
/**
|
|
5
|
-
* Validates a hotkey string and returns any warnings or errors.
|
|
6
|
-
*
|
|
7
|
-
* Checks for:
|
|
8
|
-
* - Valid syntax (modifier+...+key format)
|
|
9
|
-
* - Known modifiers
|
|
10
|
-
* - Known keys
|
|
11
|
-
*
|
|
12
|
-
* @param hotkey - The hotkey string to validate
|
|
13
|
-
* @returns A ValidationResult with validity status, warnings, and errors
|
|
14
|
-
*
|
|
15
|
-
* @example
|
|
16
|
-
* ```ts
|
|
17
|
-
* validateHotkey('Mod+S')
|
|
18
|
-
* // { valid: true, warnings: [], errors: [] }
|
|
19
|
-
*
|
|
20
|
-
* validateHotkey('')
|
|
21
|
-
* // { valid: false, warnings: [], errors: ['Hotkey cannot be empty'] }
|
|
22
|
-
* ```
|
|
23
|
-
*/
|
|
24
|
-
function validateHotkey(hotkey) {
|
|
25
|
-
const warnings = [];
|
|
26
|
-
const errors = [];
|
|
27
|
-
if (!hotkey || hotkey.trim() === "") return {
|
|
28
|
-
valid: false,
|
|
29
|
-
warnings: [],
|
|
30
|
-
errors: ["Hotkey cannot be empty"]
|
|
31
|
-
};
|
|
32
|
-
const parts = hotkey.split("+").map((p) => p.trim());
|
|
33
|
-
if (parts.length === 0 || parts.some((p) => p === "")) return {
|
|
34
|
-
valid: false,
|
|
35
|
-
warnings: [],
|
|
36
|
-
errors: ["Invalid hotkey format: empty parts detected"]
|
|
37
|
-
};
|
|
38
|
-
const modifierParts = parts.slice(0, -1);
|
|
39
|
-
const keyPart = parts[parts.length - 1];
|
|
40
|
-
for (const modifier of modifierParts) if (!(require_constants.MODIFIER_ALIASES[modifier] ?? require_constants.MODIFIER_ALIASES[modifier.toLowerCase()])) errors.push(`Unknown modifier: '${modifier}'`);
|
|
41
|
-
if (!isKnownKey(normalizeKeyForValidation(keyPart)) && !isKnownKey(keyPart)) warnings.push(`Unknown key: '${keyPart}'. This may still work but won't have type-safe autocomplete.`);
|
|
42
|
-
return {
|
|
43
|
-
valid: errors.length === 0,
|
|
44
|
-
warnings,
|
|
45
|
-
errors
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Normalizes a key for validation checking.
|
|
50
|
-
*/
|
|
51
|
-
function normalizeKeyForValidation(key) {
|
|
52
|
-
if (key.length === 1 && /^[a-zA-Z]$/.test(key)) return key.toUpperCase();
|
|
53
|
-
if (/^f([1-9]|1[0-2])$/i.test(key)) return key.toUpperCase();
|
|
54
|
-
return key;
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
|
-
* Checks if a key is in the known keys set.
|
|
58
|
-
*/
|
|
59
|
-
function isKnownKey(key) {
|
|
60
|
-
if (require_constants.ALL_KEYS.has(key)) return true;
|
|
61
|
-
if (key.length === 1 && require_constants.ALL_KEYS.has(key.toUpperCase())) return true;
|
|
62
|
-
return key in {
|
|
63
|
-
Esc: true,
|
|
64
|
-
Return: true,
|
|
65
|
-
Space: true,
|
|
66
|
-
" ": true,
|
|
67
|
-
Del: true,
|
|
68
|
-
Up: true,
|
|
69
|
-
Down: true,
|
|
70
|
-
Left: true,
|
|
71
|
-
Right: true
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
/**
|
|
75
|
-
* Validates a hotkey and throws an error if invalid.
|
|
76
|
-
* Useful for development-time validation.
|
|
77
|
-
*
|
|
78
|
-
* @param hotkey - The hotkey string to validate
|
|
79
|
-
* @throws Error if the hotkey is invalid
|
|
80
|
-
*
|
|
81
|
-
* @example
|
|
82
|
-
* ```ts
|
|
83
|
-
* assertValidHotkey('Mod+S') // OK
|
|
84
|
-
* assertValidHotkey('') // Throws Error: Invalid hotkey: Hotkey cannot be empty
|
|
85
|
-
* ```
|
|
86
|
-
*/
|
|
87
|
-
function assertValidHotkey(hotkey) {
|
|
88
|
-
const result = validateHotkey(hotkey);
|
|
89
|
-
if (!result.valid) throw new Error(`Invalid hotkey '${hotkey}': ${result.errors.join(", ")}`);
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* Validates a hotkey and logs warnings to the console.
|
|
93
|
-
* Useful for development-time feedback.
|
|
94
|
-
*
|
|
95
|
-
* @param hotkey - The hotkey string to validate
|
|
96
|
-
* @returns True if the hotkey is valid (may still have warnings)
|
|
97
|
-
*
|
|
98
|
-
* @example
|
|
99
|
-
* ```ts
|
|
100
|
-
* checkHotkey('Alt+C')
|
|
101
|
-
* // Console: Warning: Alt+C may not work reliably on macOS...
|
|
102
|
-
* // Returns: true
|
|
103
|
-
* ```
|
|
104
|
-
*/
|
|
105
|
-
function checkHotkey(hotkey) {
|
|
106
|
-
const result = validateHotkey(hotkey);
|
|
107
|
-
if (result.errors.length > 0) console.error(`Hotkey '${hotkey}' errors:`, result.errors.join("; "));
|
|
108
|
-
if (result.warnings.length > 0) console.warn(`Hotkey '${hotkey}' warnings:`, result.warnings.join("; "));
|
|
109
|
-
return result.valid;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
//#endregion
|
|
113
|
-
exports.assertValidHotkey = assertValidHotkey;
|
|
114
|
-
exports.checkHotkey = checkHotkey;
|
|
115
|
-
exports.validateHotkey = validateHotkey;
|
|
116
|
-
//# sourceMappingURL=validate.cjs.map
|
package/dist/validate.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validate.cjs","names":["MODIFIER_ALIASES","ALL_KEYS"],"sources":["../src/validate.ts"],"sourcesContent":["import { ALL_KEYS, MODIFIER_ALIASES } from './constants'\nimport type { Hotkey, ValidationResult } from './hotkey'\n\n/**\n * Validates a hotkey string and returns any warnings or errors.\n *\n * Checks for:\n * - Valid syntax (modifier+...+key format)\n * - Known modifiers\n * - Known keys\n *\n * @param hotkey - The hotkey string to validate\n * @returns A ValidationResult with validity status, warnings, and errors\n *\n * @example\n * ```ts\n * validateHotkey('Mod+S')\n * // { valid: true, warnings: [], errors: [] }\n *\n * validateHotkey('')\n * // { valid: false, warnings: [], errors: ['Hotkey cannot be empty'] }\n * ```\n */\nexport function validateHotkey(\n hotkey: Hotkey | (string & {}),\n): ValidationResult {\n const warnings: Array<string> = []\n const errors: Array<string> = []\n\n // Check for empty string\n if (!hotkey || hotkey.trim() === '') {\n return {\n valid: false,\n warnings: [],\n errors: ['Hotkey cannot be empty'],\n }\n }\n\n const parts = hotkey.split('+').map((p) => p.trim())\n\n // Must have at least one part (the key)\n if (parts.length === 0 || parts.some((p) => p === '')) {\n return {\n valid: false,\n warnings: [],\n errors: ['Invalid hotkey format: empty parts detected'],\n }\n }\n\n // Validate modifiers (all parts except the last)\n const modifierParts = parts.slice(0, -1)\n const keyPart = parts[parts.length - 1]!\n\n // Check for unknown modifiers\n for (const modifier of modifierParts) {\n const normalized =\n MODIFIER_ALIASES[modifier] ?? MODIFIER_ALIASES[modifier.toLowerCase()]\n if (!normalized) {\n errors.push(`Unknown modifier: '${modifier}'`)\n }\n }\n\n // Check if key is known\n const normalizedKey = normalizeKeyForValidation(keyPart)\n if (!isKnownKey(normalizedKey) && !isKnownKey(keyPart)) {\n warnings.push(\n `Unknown key: '${keyPart}'. This may still work but won't have type-safe autocomplete.`,\n )\n }\n\n return {\n valid: errors.length === 0,\n warnings,\n errors,\n }\n}\n\n/**\n * Normalizes a key for validation checking.\n */\nfunction normalizeKeyForValidation(key: string): string {\n // Single letter to uppercase\n if (key.length === 1 && /^[a-zA-Z]$/.test(key)) {\n return key.toUpperCase()\n }\n\n // Function keys to uppercase\n if (/^f([1-9]|1[0-2])$/i.test(key)) {\n return key.toUpperCase()\n }\n\n return key\n}\n\n/**\n * Checks if a key is in the known keys set.\n */\nfunction isKnownKey(key: string): boolean {\n // Check direct match\n if (ALL_KEYS.has(key as any)) {\n return true\n }\n\n // Check uppercase version for letters\n if (key.length === 1 && ALL_KEYS.has(key.toUpperCase() as any)) {\n return true\n }\n\n // Check common aliases\n const aliases: Record<string, boolean> = {\n Esc: true,\n Return: true,\n Space: true,\n ' ': true,\n Del: true,\n Up: true,\n Down: true,\n Left: true,\n Right: true,\n }\n\n return key in aliases\n}\n\n/**\n * Validates a hotkey and throws an error if invalid.\n * Useful for development-time validation.\n *\n * @param hotkey - The hotkey string to validate\n * @throws Error if the hotkey is invalid\n *\n * @example\n * ```ts\n * assertValidHotkey('Mod+S') // OK\n * assertValidHotkey('') // Throws Error: Invalid hotkey: Hotkey cannot be empty\n * ```\n */\nexport function assertValidHotkey(hotkey: Hotkey | (string & {})): void {\n const result = validateHotkey(hotkey)\n if (!result.valid) {\n throw new Error(`Invalid hotkey '${hotkey}': ${result.errors.join(', ')}`)\n }\n}\n\n/**\n * Validates a hotkey and logs warnings to the console.\n * Useful for development-time feedback.\n *\n * @param hotkey - The hotkey string to validate\n * @returns True if the hotkey is valid (may still have warnings)\n *\n * @example\n * ```ts\n * checkHotkey('Alt+C')\n * // Console: Warning: Alt+C may not work reliably on macOS...\n * // Returns: true\n * ```\n */\nexport function checkHotkey(hotkey: Hotkey | (string & {})): boolean {\n const result = validateHotkey(hotkey)\n\n if (result.errors.length > 0) {\n console.error(`Hotkey '${hotkey}' errors:`, result.errors.join('; '))\n }\n\n if (result.warnings.length > 0) {\n console.warn(`Hotkey '${hotkey}' warnings:`, result.warnings.join('; '))\n }\n\n return result.valid\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,eACd,QACkB;CAClB,MAAM,WAA0B,EAAE;CAClC,MAAM,SAAwB,EAAE;AAGhC,KAAI,CAAC,UAAU,OAAO,MAAM,KAAK,GAC/B,QAAO;EACL,OAAO;EACP,UAAU,EAAE;EACZ,QAAQ,CAAC,yBAAyB;EACnC;CAGH,MAAM,QAAQ,OAAO,MAAM,IAAI,CAAC,KAAK,MAAM,EAAE,MAAM,CAAC;AAGpD,KAAI,MAAM,WAAW,KAAK,MAAM,MAAM,MAAM,MAAM,GAAG,CACnD,QAAO;EACL,OAAO;EACP,UAAU,EAAE;EACZ,QAAQ,CAAC,8CAA8C;EACxD;CAIH,MAAM,gBAAgB,MAAM,MAAM,GAAG,GAAG;CACxC,MAAM,UAAU,MAAM,MAAM,SAAS;AAGrC,MAAK,MAAM,YAAY,cAGrB,KAAI,EADFA,mCAAiB,aAAaA,mCAAiB,SAAS,aAAa,GAErE,QAAO,KAAK,sBAAsB,SAAS,GAAG;AAMlD,KAAI,CAAC,WADiB,0BAA0B,QAAQ,CAC1B,IAAI,CAAC,WAAW,QAAQ,CACpD,UAAS,KACP,iBAAiB,QAAQ,+DAC1B;AAGH,QAAO;EACL,OAAO,OAAO,WAAW;EACzB;EACA;EACD;;;;;AAMH,SAAS,0BAA0B,KAAqB;AAEtD,KAAI,IAAI,WAAW,KAAK,aAAa,KAAK,IAAI,CAC5C,QAAO,IAAI,aAAa;AAI1B,KAAI,qBAAqB,KAAK,IAAI,CAChC,QAAO,IAAI,aAAa;AAG1B,QAAO;;;;;AAMT,SAAS,WAAW,KAAsB;AAExC,KAAIC,2BAAS,IAAI,IAAW,CAC1B,QAAO;AAIT,KAAI,IAAI,WAAW,KAAKA,2BAAS,IAAI,IAAI,aAAa,CAAQ,CAC5D,QAAO;AAgBT,QAAO,OAZkC;EACvC,KAAK;EACL,QAAQ;EACR,OAAO;EACP,KAAK;EACL,KAAK;EACL,IAAI;EACJ,MAAM;EACN,MAAM;EACN,OAAO;EACR;;;;;;;;;;;;;;;AAkBH,SAAgB,kBAAkB,QAAsC;CACtE,MAAM,SAAS,eAAe,OAAO;AACrC,KAAI,CAAC,OAAO,MACV,OAAM,IAAI,MAAM,mBAAmB,OAAO,KAAK,OAAO,OAAO,KAAK,KAAK,GAAG;;;;;;;;;;;;;;;;AAkB9E,SAAgB,YAAY,QAAyC;CACnE,MAAM,SAAS,eAAe,OAAO;AAErC,KAAI,OAAO,OAAO,SAAS,EACzB,SAAQ,MAAM,WAAW,OAAO,YAAY,OAAO,OAAO,KAAK,KAAK,CAAC;AAGvE,KAAI,OAAO,SAAS,SAAS,EAC3B,SAAQ,KAAK,WAAW,OAAO,cAAc,OAAO,SAAS,KAAK,KAAK,CAAC;AAG1E,QAAO,OAAO"}
|
package/dist/validate.d.cts
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import { Hotkey, ValidationResult } from "./hotkey.cjs";
|
|
2
|
-
|
|
3
|
-
//#region src/validate.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* Validates a hotkey string and returns any warnings or errors.
|
|
6
|
-
*
|
|
7
|
-
* Checks for:
|
|
8
|
-
* - Valid syntax (modifier+...+key format)
|
|
9
|
-
* - Known modifiers
|
|
10
|
-
* - Known keys
|
|
11
|
-
*
|
|
12
|
-
* @param hotkey - The hotkey string to validate
|
|
13
|
-
* @returns A ValidationResult with validity status, warnings, and errors
|
|
14
|
-
*
|
|
15
|
-
* @example
|
|
16
|
-
* ```ts
|
|
17
|
-
* validateHotkey('Mod+S')
|
|
18
|
-
* // { valid: true, warnings: [], errors: [] }
|
|
19
|
-
*
|
|
20
|
-
* validateHotkey('')
|
|
21
|
-
* // { valid: false, warnings: [], errors: ['Hotkey cannot be empty'] }
|
|
22
|
-
* ```
|
|
23
|
-
*/
|
|
24
|
-
declare function validateHotkey(hotkey: Hotkey | (string & {})): ValidationResult;
|
|
25
|
-
/**
|
|
26
|
-
* Validates a hotkey and throws an error if invalid.
|
|
27
|
-
* Useful for development-time validation.
|
|
28
|
-
*
|
|
29
|
-
* @param hotkey - The hotkey string to validate
|
|
30
|
-
* @throws Error if the hotkey is invalid
|
|
31
|
-
*
|
|
32
|
-
* @example
|
|
33
|
-
* ```ts
|
|
34
|
-
* assertValidHotkey('Mod+S') // OK
|
|
35
|
-
* assertValidHotkey('') // Throws Error: Invalid hotkey: Hotkey cannot be empty
|
|
36
|
-
* ```
|
|
37
|
-
*/
|
|
38
|
-
declare function assertValidHotkey(hotkey: Hotkey | (string & {})): void;
|
|
39
|
-
/**
|
|
40
|
-
* Validates a hotkey and logs warnings to the console.
|
|
41
|
-
* Useful for development-time feedback.
|
|
42
|
-
*
|
|
43
|
-
* @param hotkey - The hotkey string to validate
|
|
44
|
-
* @returns True if the hotkey is valid (may still have warnings)
|
|
45
|
-
*
|
|
46
|
-
* @example
|
|
47
|
-
* ```ts
|
|
48
|
-
* checkHotkey('Alt+C')
|
|
49
|
-
* // Console: Warning: Alt+C may not work reliably on macOS...
|
|
50
|
-
* // Returns: true
|
|
51
|
-
* ```
|
|
52
|
-
*/
|
|
53
|
-
declare function checkHotkey(hotkey: Hotkey | (string & {})): boolean;
|
|
54
|
-
//#endregion
|
|
55
|
-
export { assertValidHotkey, checkHotkey, validateHotkey };
|
|
56
|
-
//# sourceMappingURL=validate.d.cts.map
|
package/dist/validate.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validate.js","names":[],"sources":["../src/validate.ts"],"sourcesContent":["import { ALL_KEYS, MODIFIER_ALIASES } from './constants'\nimport type { Hotkey, ValidationResult } from './hotkey'\n\n/**\n * Validates a hotkey string and returns any warnings or errors.\n *\n * Checks for:\n * - Valid syntax (modifier+...+key format)\n * - Known modifiers\n * - Known keys\n *\n * @param hotkey - The hotkey string to validate\n * @returns A ValidationResult with validity status, warnings, and errors\n *\n * @example\n * ```ts\n * validateHotkey('Mod+S')\n * // { valid: true, warnings: [], errors: [] }\n *\n * validateHotkey('')\n * // { valid: false, warnings: [], errors: ['Hotkey cannot be empty'] }\n * ```\n */\nexport function validateHotkey(\n hotkey: Hotkey | (string & {}),\n): ValidationResult {\n const warnings: Array<string> = []\n const errors: Array<string> = []\n\n // Check for empty string\n if (!hotkey || hotkey.trim() === '') {\n return {\n valid: false,\n warnings: [],\n errors: ['Hotkey cannot be empty'],\n }\n }\n\n const parts = hotkey.split('+').map((p) => p.trim())\n\n // Must have at least one part (the key)\n if (parts.length === 0 || parts.some((p) => p === '')) {\n return {\n valid: false,\n warnings: [],\n errors: ['Invalid hotkey format: empty parts detected'],\n }\n }\n\n // Validate modifiers (all parts except the last)\n const modifierParts = parts.slice(0, -1)\n const keyPart = parts[parts.length - 1]!\n\n // Check for unknown modifiers\n for (const modifier of modifierParts) {\n const normalized =\n MODIFIER_ALIASES[modifier] ?? MODIFIER_ALIASES[modifier.toLowerCase()]\n if (!normalized) {\n errors.push(`Unknown modifier: '${modifier}'`)\n }\n }\n\n // Check if key is known\n const normalizedKey = normalizeKeyForValidation(keyPart)\n if (!isKnownKey(normalizedKey) && !isKnownKey(keyPart)) {\n warnings.push(\n `Unknown key: '${keyPart}'. This may still work but won't have type-safe autocomplete.`,\n )\n }\n\n return {\n valid: errors.length === 0,\n warnings,\n errors,\n }\n}\n\n/**\n * Normalizes a key for validation checking.\n */\nfunction normalizeKeyForValidation(key: string): string {\n // Single letter to uppercase\n if (key.length === 1 && /^[a-zA-Z]$/.test(key)) {\n return key.toUpperCase()\n }\n\n // Function keys to uppercase\n if (/^f([1-9]|1[0-2])$/i.test(key)) {\n return key.toUpperCase()\n }\n\n return key\n}\n\n/**\n * Checks if a key is in the known keys set.\n */\nfunction isKnownKey(key: string): boolean {\n // Check direct match\n if (ALL_KEYS.has(key as any)) {\n return true\n }\n\n // Check uppercase version for letters\n if (key.length === 1 && ALL_KEYS.has(key.toUpperCase() as any)) {\n return true\n }\n\n // Check common aliases\n const aliases: Record<string, boolean> = {\n Esc: true,\n Return: true,\n Space: true,\n ' ': true,\n Del: true,\n Up: true,\n Down: true,\n Left: true,\n Right: true,\n }\n\n return key in aliases\n}\n\n/**\n * Validates a hotkey and throws an error if invalid.\n * Useful for development-time validation.\n *\n * @param hotkey - The hotkey string to validate\n * @throws Error if the hotkey is invalid\n *\n * @example\n * ```ts\n * assertValidHotkey('Mod+S') // OK\n * assertValidHotkey('') // Throws Error: Invalid hotkey: Hotkey cannot be empty\n * ```\n */\nexport function assertValidHotkey(hotkey: Hotkey | (string & {})): void {\n const result = validateHotkey(hotkey)\n if (!result.valid) {\n throw new Error(`Invalid hotkey '${hotkey}': ${result.errors.join(', ')}`)\n }\n}\n\n/**\n * Validates a hotkey and logs warnings to the console.\n * Useful for development-time feedback.\n *\n * @param hotkey - The hotkey string to validate\n * @returns True if the hotkey is valid (may still have warnings)\n *\n * @example\n * ```ts\n * checkHotkey('Alt+C')\n * // Console: Warning: Alt+C may not work reliably on macOS...\n * // Returns: true\n * ```\n */\nexport function checkHotkey(hotkey: Hotkey | (string & {})): boolean {\n const result = validateHotkey(hotkey)\n\n if (result.errors.length > 0) {\n console.error(`Hotkey '${hotkey}' errors:`, result.errors.join('; '))\n }\n\n if (result.warnings.length > 0) {\n console.warn(`Hotkey '${hotkey}' warnings:`, result.warnings.join('; '))\n }\n\n return result.valid\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,eACd,QACkB;CAClB,MAAM,WAA0B,EAAE;C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