UNPKG

@tanstack/hotkeys

Version:

Type-safe, framework-agnostic keyboard hotkey management for the browser

959 lines (957 loc) • 40.2 kB
import { chordHasKey, isKeyNameShape, parsedStepsEqual } from "./_chord.js"; import { canWarn } from "./_dev.js"; import { getTargetDocument, isDocumentLevel, shouldIgnoreInputEvent, targetHasFocus, yieldsEscape } from "./_event-target.js"; import { isSequenceStep, keepsSequenceProgress } from "./_keyboard-event.js"; import { keysEqual } from "./_keys.js"; import { managerRef } from "./_manager-ref.js"; import { matchKeyboardEvent } from "./_match.js"; import { isRecordingEvent, onRecordingStart } from "./_recording-guard.js"; import { GLOBAL_SCOPE, defaultHotkeyOptions, definedOptions, getDefaultIgnoreInputs, handleConflict, optionsEqual } from "./_registration.js"; import { createStore } from "./_store.js"; import { TargetListeners } from "./_target-listeners.js"; import { normalizeKeyName } from "./constants.js"; import { formatHotkey } from "./format.js"; import { DEFAULT_SEQUENCE_TIMEOUT, areHotkeysEqual } from "./match.js"; import { isHotkeySequence, parseHotkey, simplifyHotkey } from "./parse.js"; import { detectPlatform } from "./platform.js"; // src/hotkey-manager.ts /** Whether a registration can fire now. Without a manager, scopes don't apply. */ function getRegistrationStatus(options, manager) { if (options.enabled === false) return "disabled"; return manager?.isScopeActive(options.scope) === false ? "suspended" : "active"; } /** Creates a public view from an internal registration, stripping the callback. */ function toHotkeyRegistrationView(reg) { const base = { id: reg.id, status: getRegistrationStatus(reg.options, managerRef.current), target: reg.target, triggerCount: reg.triggerCount, hasFired: reg.hasFired }; if (reg.kind === "chord") return { ...base, kind: "chord", hotkey: reg.hotkey, parsedChord: reg.parsedChord, options: reg.options }; const length = reg.parsedSequence.length; const inProgress = reg.currentIndex > 0 && reg.currentIndex < length; return { ...base, kind: "sequence", hotkey: reg.hotkey, parsedSequence: reg.parsedSequence, options: reg.options, matchedStepCount: inProgress ? reg.currentIndex : 0, partialMatchLastKeyTime: inProgress ? reg.lastKeyTime : 0 }; } let registrationIdCounter = 0; /** The string a chord registers as: strings as written, objects formatted from their parsed form. */ function chordString(chord, parsed) { return typeof chord === "string" ? chord : formatHotkey(parsed); } /** * Generates a unique ID for hotkey registrations. */ function generateId() { return `hotkey_${++registrationIdCounter}`; } /** A handle for a registration that listens for nothing. */ function inactiveHandle(callback) { let currentCallback = callback; return { id: generateId(), unregister: () => {}, get callback() { return currentCallback; }, set callback(newCallback) { currentCallback = newCallback; }, setOptions: () => {}, get isActive() { return false; } }; } /** Defaults for a registration of the given kind. */ function registrationDefaults(kind) { return { ...defaultHotkeyOptions, ...kind === "sequence" ? { timeout: DEFAULT_SEQUENCE_TIMEOUT } : { requireReset: false } }; } /** Drops options that do not apply to a registration's kind. */ function optionsForKind(kind, options) { if (kind === "chord") { const { timeout: _timeout, ...rest } = options; return rest; } const { requireReset: _requireReset, ...rest } = options; return rest; } /** * Where a registration listens: its target, or for an element target that * runs after delegated handlers in the bubble phase, the node where handlers * delegated around it have already run. That is its document, unless the * element is in a closed shadow root, which hides it from listeners outside, * or in a tree outside any document, which events never leave. */ function listenerTarget({ target, options }) { if (!options.afterDelegatedHandlers || options.capture || isDocumentLevel(target)) return target; let root = target.getRootNode(); while ("host" in root && root.mode === "open") root = root.host.getRootNode(); return root; } /** Whether a registration's shared listener moves after listeners added before it joins. */ function movesAfterDelegatedHandlers(options) { return !!options.afterDelegatedHandlers && !options.capture; } /** Steps with Mod already resolved for the registration's platform. */ function resolvedSteps(registration) { return registration.kind === "chord" ? [registration.parsedChord] : registration.parsedSequence; } /** Whether a registration skips keys that focused controls use, resolving `'auto'`. */ function ignoresInputs(registration) { const { ignoreInputs = "auto" } = registration.options; return ignoreInputs === "auto" ? getDefaultIgnoreInputs(resolvedSteps(registration)[0]) : ignoreInputs; } /** Whether the registration leaves the key to a focused control inside `target`. */ function ignoredInInput(registration, event, target) { return ignoresInputs(registration) && shouldIgnoreInputEvent(event, target); } /** The longest pause a sequence allows between two steps, in milliseconds. */ function sequenceTimeout(registration) { return registration.options.timeout ?? 1e3; } function formatForMessage(hotkey) { return isHotkeySequence(hotkey) ? hotkey.join(" ") : hotkey; } /** * Singleton manager for hotkey registrations, including sequences. * * This class provides a centralized way to register and manage keyboard * hotkeys. It shares one keydown and one keyup listener per target and * capture phase across registrations. * * Sequences (Vim-style hotkeys such as `['G', 'G']`) match when every step is * pressed within the timeout. Modifier-only events (Shift, Control, Alt, or * Meta alone) neither advance nor reset a sequence, so chained modifier chords * such as `['Shift+R', 'Shift+T']` work. * * @example * ```ts * const manager = HotkeyManager.getInstance() * * const save = manager.register('Mod+S', (event, context) => { * console.log('Save triggered!') * }) * const top = manager.register(['G', 'G'], () => scrollToTop(), { timeout: 500 }) * * // Later, to unregister: * save.unregister() * top.unregister() * ``` */ /** Mac shifted-symbol hotkeys already warned about, in development only. */ let warnedOnMac; var HotkeyManager = class HotkeyManager { /** * The TanStack Store containing all hotkey registrations, chords and sequences. * Use this to subscribe to registration changes or access current registrations. * * @example * ```ts * const manager = HotkeyManager.getInstance() * * // Subscribe to registration changes * const unsubscribe = manager.registrations.subscribe(() => { * console.log('Registrations changed:', manager.registrations.state.size) * }) * * // Access current registrations * for (const [id, reg] of manager.registrations.state) { * console.log(reg.hotkey, reg.options.enabled) * } * ``` */ registrations = createStore(/* @__PURE__ */ new Map()); /** * The app hotkeys store published by a framework provider, so tools such as * devtools can list declared hotkeys that are not registered. */ appHotkeys = createStore(null); /** Active scopes. Subscribe to show which hotkeys are suspended. */ scopes = createStore({ active: [], exclusive: null, allowed: [], suspended: [] }); #platform; #scopeActivations = /* @__PURE__ */ new Set(); #scopeActivationCount = 0; /** Active scopes, lowest precedence first, derived from activations. */ #scopeOrder = []; /** Scopes that can fire while a scope is exclusive, or `null` when none is. */ #liveScopes = null; #listeners = new TargetListeners((...args) => this.#processTargetEvent(...args), (event) => { this.#keydown = event; if (!event.repeat) { this.#liveDuring.clear(); this.#scopeLiveDuring.clear(); } }); /** The last keydown a window listener saw, which may still be dispatching. */ #keydown; /** * The key event being dispatched when a registration went live, or when a * scope was activated, such as the Enter that opened a dialog. Those * registrations don't fire on that event. Cleared at the next keydown. */ #liveDuring = /* @__PURE__ */ new Map(); #scopeLiveDuring = /* @__PURE__ */ new Map(); /** Where each registration listens, kept so cleanup finds a target that moved documents. */ #listenerTargets = /* @__PURE__ */ new Map(); /** Events that continue a sequence in progress, decided before any listener runs. */ #sequenceOwned = /* @__PURE__ */ new WeakMap(); /** * Keyup chords whose keydown matched. Releasing one of the chord's * modifiers fires them, because the key's own keyup may come after the * modifier's or, on macOS while Command is held, not at all. A press that * another key cancelled, or that `ignoreDefaultPrevented` skipped, has no * entry, so its release doesn't fire. */ #pendingReleases = /* @__PURE__ */ new Map(); /** The keyup chords' presses each release ended, by registration id. */ #endedPresses = /* @__PURE__ */ new WeakMap(); /** Events this manager prevented, so its own prevention never skips a hotkey. */ #prevented = /* @__PURE__ */ new WeakSet(); /** Physical keys whose keydown a sequence owned, so their repeats and keyup are owned too. */ #sequenceOwnedKeys = /* @__PURE__ */ new Set(); /** Timers that clear a sequence's progress once its timeout passes. */ #sequenceResetTimers = /* @__PURE__ */ new Map(); constructor() { this.#platform = detectPlatform(); onRecordingStart(() => { let changed = false; for (const registration of this.registrations.state.values()) if (registration.kind === "sequence" && registration.currentIndex > 0) { registration.currentIndex = 0; this.#clearSequenceReset(registration.id); changed = true; } if (changed) this.#notify(); }); } /** * Gets the singleton instance of HotkeyManager. */ static getInstance() { return managerRef.current ??= new HotkeyManager(); } /** * Resets the singleton instance. Useful for testing. */ static resetInstance() { managerRef.current?.destroy(); managerRef.current = null; } /** * Activates a scope until the returned function is called. Activations are * counted, so a scope stays active until every activation is released. * Framework providers call this while mounted. * * When active scopes share a hotkey, a nested scope takes precedence over * its ancestors, and otherwise the most recently activated scope wins. The * same order picks the exclusive scope when several are active, and only * that scope's `allow` list applies. * * @example * ```ts * const release = manager.activateScope('dialog', { exclusive: true }) * // Only hotkeys with scope 'dialog', or scopes nested in it, fire now. * release() * * manager.activateScope('dialog', { exclusive: { allow: ['global'] } }) * // Hotkeys with scope 'global' fire too. * ``` */ activateScope(scope, options = {}) { if (scope === "global") return () => {}; const event = this.#currentEvent(); if (event) this.#scopeLiveDuring.set(scope, event); const { exclusive } = options; const allow = exclusive ? exclusive === true ? [] : exclusive.allow : null; if (canWarn && process.env.NODE_ENV !== "production" && allow && [...this.#scopeActivations].some((other) => other.allow && other.scope === scope)) console.warn(`[hotkeys] Exclusive scope '${scope}' is already active`); const activation = { scope, parent: options.parent ?? "global", allow, order: ++this.#scopeActivationCount }; this.#scopeActivations.add(activation); this.#updateScopes(); return () => { if (this.#scopeActivations.delete(activation)) this.#updateScopes(); }; } /** * Whether hotkeys in a scope can fire: the scope is `'global'` or * activated, and either no scope is exclusive or this scope is the * exclusive one, nested in it, or allowed by it. */ isScopeActive(scope = GLOBAL_SCOPE) { if (this.#liveScopes) return this.#liveScopes.has(scope); return scope === "global" || this.#scopeOrder.includes(scope); } /** Higher for scopes with higher precedence; `'global'` is 0. */ #scopeRank(scope = GLOBAL_SCOPE) { return this.#scopeOrder.indexOf(scope) + 1; } /** Recomputes scope precedence and publishes it. */ #updateScopes() { const parents = /* @__PURE__ */ new Map(); const latest = /* @__PURE__ */ new Map(); for (const activation of this.#scopeActivations) { if (activation.parent !== activation.scope) parents.set(activation.scope, activation.parent); latest.set(activation.scope, Math.max(latest.get(activation.scope) ?? 0, activation.order)); } const depth = (scope) => { let result = 0; const seen = /* @__PURE__ */ new Set(); for (let current = parents.get(scope); current !== void 0 && !seen.has(current); current = parents.get(current)) { seen.add(current); result++; } return result; }; const since = /* @__PURE__ */ new Map(); for (const [scope, order] of latest) { const seen = /* @__PURE__ */ new Set(); for (let current = scope; current !== void 0 && !seen.has(current); current = parents.get(current)) { seen.add(current); const own = latest.get(current); if (own !== void 0) since.set(current, Math.min(since.get(current) ?? own, order)); } } const compare = (a, b) => since.get(a) - since.get(b) || depth(a) - depth(b) || latest.get(a) - latest.get(b); this.#scopeOrder = [...latest.keys()].sort(compare); const exclusive = [...this.#scopeActivations].filter((activation) => activation.allow).sort((a, b) => compare(a.scope, b.scope) || a.order - b.order).pop(); const activated = [GLOBAL_SCOPE, ...this.#scopeOrder]; let allowed = []; this.#liveScopes = null; if (exclusive?.allow) { const { allow } = exclusive; const isNested = (scope) => { const seen = /* @__PURE__ */ new Set(); for (let current = scope; current !== void 0 && !seen.has(current); current = parents.get(current)) { if (current === exclusive.scope) return true; seen.add(current); } return false; }; allowed = activated.filter((scope) => !isNested(scope) && allow.includes(scope)); this.#liveScopes = /* @__PURE__ */ new Set([...activated.filter(isNested), ...allowed]); } const live = this.#liveScopes; this.scopes.setState(() => ({ active: this.#scopeOrder, exclusive: exclusive?.scope ?? null, allowed, suspended: live ? activated.filter((scope) => !live.has(scope)) : [] })); this.#notify(); } /** Whether a registration can fire now: enabled, in an active scope. */ #isLive(registration) { return getRegistrationStatus(registration.options, this) === "active"; } /** * Whether a hotkey that can fire would handle this key on any listener the * event reaches, including other targets and phases. A sequence counts when * the key matches its next step or its first step. */ #handledByLiveHotkey(event, eventType) { const path = event.composedPath(); return [...this.registrations.state.values()].some((registration) => this.#isLive(registration) && registration.options.eventType === eventType && !this.#skips(registration, event) && path.includes(registration.target) && !ignoredInInput(registration, event, registration.target) && (registration.kind === "chord" ? [registration.parsedChord] : [registration.parsedSequence[registration.currentIndex], registration.parsedSequence[0]]).some((step) => matchKeyboardEvent(event, step, registration.options.platform).matched)); } /** Notifies subscribers after in-place updates such as counts and sequence progress. */ #notify() { this.registrations.setState((prev) => new Map(prev)); } register(input, callback, options = {}) { const hotkey = simplifyHotkey(input); if (hotkey == null || isHotkeySequence(hotkey) && hotkey.length === 0 || options.target === null || typeof document === "undefined" && !options.target) return inactiveHandle(callback); const id = generateId(); const platform = options.platform ?? this.#platform; const target = options.target ?? document; const sequence = isHotkeySequence(hotkey); const kind = sequence ? "sequence" : "chord"; const common = { id, callback, options: { ...registrationDefaults(kind), ...optionsForKind(kind, definedOptions(options)), platform }, target, triggerCount: 0, hasFired: false }; let registration; if (sequence) { const parsedSequence = parseHotkey(hotkey, platform); registration = { ...common, kind: "sequence", hotkey: hotkey.map((step, index) => chordString(step, parsedSequence[index])), parsedSequence, currentIndex: 0, lastKeyTime: 0 }; } else { const parsedChord = parseHotkey(hotkey, platform); registration = { ...common, kind: "chord", hotkey: chordString(hotkey, parsedChord), parsedChord }; } const steps = resolvedSteps(registration); if (!steps.every(chordHasKey)) { if (canWarn && process.env.NODE_ENV !== "production" && hotkey !== "") console.warn(`[hotkeys] Invalid hotkey ${JSON.stringify(hotkey)} was not registered`); return inactiveHandle(callback); } if (canWarn && process.env.NODE_ENV !== "production") for (const { key, meta, alt } of steps) { if (key !== void 0 && !isKeyNameShape(key)) console.warn(`[hotkeys] Unknown key '${key}' in '${formatForMessage(registration.hotkey)}' (names are case-sensitive)`); const index = key ? "!@#$%^&*()<>".indexOf(key) : -1; const text = formatForMessage(registration.hotkey); if (platform === "mac" && meta && !alt && index >= 0 && !(warnedOnMac ??= /* @__PURE__ */ new Set()).has(text)) { warnedOnMac.add(text); const usKey = "1234567890,."[index]; console.warn(`[hotkeys] '${text}' does not fire on a US Mac keyboard, where Command+Shift+${usKey} reports '${usKey}'. Register it with Shift and that key too.`); } } if (this.#findConflictingRegistration(registration)) handleConflict(formatForMessage(registration.hotkey), options.conflictBehavior ?? "warn"); const listenOn = listenerTarget(registration); this.#listeners.add(listenOn, !!registration.options.capture, id, movesAfterDelegatedHandlers(registration.options)); this.#listenerTargets.set(id, listenOn); this.#markLive(id); this.registrations.setState((prev) => new Map(prev).set(id, registration)); const manager = this; return { get id() { return id; }, unregister: () => { manager.#unregister(id); }, get callback() { return manager.registrations.state.get(id)?.callback ?? callback; }, set callback(newCallback) { const reg = manager.registrations.state.get(id); if (reg) reg.callback = newCallback; }, setOptions: (newOptions) => { manager.registrations.setState((prev) => { const reg = prev.get(id); if (!reg) return prev; const defaults = { ...registrationDefaults(reg.kind), platform: reg.options.platform }; const options = { ...reg.options }; const entries = Object.entries(optionsForKind(reg.kind, newOptions)); for (const [key, value] of entries) if (value !== void 0) options[key] = value; else if (key in defaults) options[key] = defaults[key]; else delete options[key]; if (optionsEqual(reg.options, options)) { if ("meta" in options) reg.options.meta = options.meta; return prev; } const capture = !!reg.options.capture; const from = manager.#listenerTargets.get(id) ?? reg.target; const to = listenerTarget({ target: reg.target, options }); if (capture !== !!options.capture || from !== to) { manager.#listeners.remove(from, capture, id); manager.#listeners.add(to, !!options.capture, id, movesAfterDelegatedHandlers(options)); manager.#listenerTargets.set(id, to); } else if (movesAfterDelegatedHandlers(options) && !movesAfterDelegatedHandlers(reg.options)) manager.#listeners.add(to, capture, id, true); if (getRegistrationStatus(reg.options, manager) !== "active" && getRegistrationStatus(options, manager) === "active" && !(reg.kind === "chord" && options.eventType === "keyup")) manager.#markLive(id); return new Map(prev).set(id, { ...reg, options }); }); }, get isActive() { return manager.registrations.state.has(id); } }; } /** * Unregisters a hotkey by its registration ID. */ #unregister(id) { const registration = this.registrations.state.get(id); if (!registration) return; this.#pendingReleases.delete(id); this.#liveDuring.delete(id); this.registrations.setState((prev) => { const next = new Map(prev); next.delete(id); return next; }); this.#listeners.remove(this.#listenerTargets.get(id) ?? registration.target, !!registration.options.capture, id); this.#listenerTargets.delete(id); this.#clearSequenceReset(id); } /** * Clears a sequence's progress, and notifies subscribers, once its timeout * passes without another step. Key presses check the timeout too, so this * only keeps views such as `matchedStepCount` current. */ #scheduleSequenceReset(id, delay) { this.#clearSequenceReset(id); this.#sequenceResetTimers.set(id, setTimeout(() => { this.#sequenceResetTimers.delete(id); const registration = this.registrations.state.get(id); if (registration?.kind !== "sequence" || registration.currentIndex === 0) return; const remaining = registration.lastKeyTime + sequenceTimeout(registration) - Date.now(); if (remaining >= 0) { this.#scheduleSequenceReset(id, remaining + 1); return; } registration.currentIndex = 0; registration.lastKeyTime = 0; this.#notify(); }, delay)); } #clearSequenceReset(id) { const timer = this.#sequenceResetTimers.get(id); if (timer === void 0) return; clearTimeout(timer); this.#sequenceResetTimers.delete(id); } /** Registrations of one kind in the listener phase, in registration order. */ #registrationsIn(ids, capture, kind) { const result = []; for (const id of ids) { const registration = this.registrations.state.get(id); if (registration?.kind === kind && !!registration.options.capture === capture) result.push(registration); } return result; } /** The live registration, unless it was removed or moved to another phase. */ #currentIn(registration, capture) { const current = this.registrations.state.get(registration.id); return current && !!current.options.capture === capture ? current : void 0; } /** * Processes keyboard events for a specific target and event type. * A key that continues a sequence in progress belongs to that sequence, so * chords and other sequences' first steps skip it. Otherwise chords and * first steps of sequences may both fire. */ #processTargetEvent(event, target, eventType, capture, ids, first) { if (first) { this.#sequenceOwned.set(event, this.#isOwnedBySequence(event, eventType)); this.#endPresses(event, eventType); } if (capture) { this.#processRound(event, target, eventType, capture, ids); return; } const rounds = /* @__PURE__ */ new Map(); for (const id of ids) { const registration = this.registrations.state.get(id); if (!registration) continue; const round = rounds.get(registration.target) ?? /* @__PURE__ */ new Set(); rounds.set(registration.target, round.add(id)); } const path = rounds.size > 1 || !rounds.has(target) ? event.composedPath() : []; const order = [...rounds.keys()].filter((other) => other === target || path.includes(other)).sort((a, b) => a === target ? 1 : b === target ? -1 : path.indexOf(a) - path.indexOf(b)); const arrivedStopped = event.cancelBubble; for (const roundTarget of order) { const round = /* @__PURE__ */ new Set(); for (const id of rounds.get(roundTarget)) { const delegated = this.registrations.state.get(id)?.options.afterDelegatedHandlers; if (!event.cancelBubble || !delegated && arrivedStopped) round.add(id); } this.#processRound(event, roundTarget, eventType, capture, round); } } #processRound(event, target, eventType, capture, ids) { this.#processChords(event, target, eventType, capture, this.#registrationsIn(ids, capture, "chord")); this.#processSequences(event, target, eventType, capture, this.#registrationsIn(ids, capture, "sequence")); } #processChords(event, target, eventType, capture, registrations) { if (eventType === "keyup") { let cleared = false; for (const registration of registrations) if (registration.hasFired && this.#shouldResetRegistration(registration, event)) { registration.hasFired = false; registration.activeMatch = void 0; cleared = true; } if (cleared) this.#notify(); } if (isRecordingEvent(event) || this.#sequenceOwned.get(event)) return; const matches = /* @__PURE__ */ new Map(); let reserved = false; for (const registration of registrations) { const live = this.#isLive(registration); const { eventType: firesOn, preventDefault } = registration.options; const press = eventType === "keydown" && firesOn === "keyup"; const skipped = this.#skips(registration, event); const { parsedChord, id } = registration; const { platform } = registration.options; const released = this.#endedPresses.get(event)?.get(id); if (firesOn !== eventType && !press || ignoredInInput(registration, event, target)) continue; let result = matchKeyboardEvent(event, parsedChord, platform); if (press) { if (result.matched) { if (skipped) this.#pendingReleases.delete(id); else { if (live && preventDefault) this.#prevent(event); else if (!live && preventDefault === "always") reserved = true; if (!event.repeat) this.#pendingReleases.set(id, result); } } continue; } if (!live && preventDefault !== "always") continue; if (eventType === "keyup") { if (!released || skipped) continue; if (!result.matched) result = released; } if (skipped || !result.matched) continue; if (!live) { reserved = true; continue; } matches.set(registration.id, result); } if (reserved && matches.size === 0 && !this.#handledByLiveHotkey(event, eventType)) this.#prevent(event); let bestRank = -1; for (const registration of registrations) if (matches.has(registration.id)) bestRank = Math.max(bestRank, this.#scopeRank(registration.options.scope)); let bestScore = 0; for (const registration of registrations) { const match = matches.get(registration.id); if (match && this.#scopeRank(registration.options.scope) === bestRank) bestScore = Math.max(bestScore, match.score); } const best = registrations.filter((registration) => matches.get(registration.id)?.score === bestScore && this.#scopeRank(registration.options.scope) === bestRank); const physical = best.some(({ parsedChord }) => parsedChord.code); for (const snapshot of best) { const match = matches.get(snapshot.id); if (physical && !snapshot.parsedChord.code) continue; if (this.#scopeRank(snapshot.options.scope) !== bestRank) continue; const registration = this.#currentIn(snapshot, capture); if (!registration || !this.#isLive(registration)) continue; this.#consume(registration, event); if (eventType === "keyup") { this.#fire(registration, event); continue; } if (!registration.options.requireReset || !registration.hasFired || !event.repeat) { if (registration.options.requireReset) { registration.hasFired = true; registration.activeMatch = match.identity; } this.#fire(registration, event); } } } /** * Whether the event continues or completes a sequence in progress whose * target the event reaches. The repeats and keyup of a keydown that a * sequence owns belong to the sequence too. */ #isOwnedBySequence(event, eventType) { const key = event.code || normalizeKeyName(event.key); if (eventType === "keyup") { const ownedKeydown = this.#sequenceOwnedKeys.delete(key); return this.#continuesSequence(event, eventType) || ownedKeydown; } if (event.repeat) return this.#sequenceOwnedKeys.has(key); const owned = this.#continuesSequence(event, eventType); if (owned) this.#sequenceOwnedKeys.add(key); else this.#sequenceOwnedKeys.delete(key); return owned; } #continuesSequence(event, eventType) { if (isRecordingEvent(event) || !isSequenceStep(event)) return false; const path = event.composedPath(); const now = Date.now(); for (const registration of this.registrations.state.values()) { if (registration.kind !== "sequence" || registration.currentIndex === 0 || !this.#isLive(registration) || registration.options.eventType !== eventType || this.#skips(registration, event) || now - registration.lastKeyTime > sequenceTimeout(registration)) continue; const target = registration.target; if (path.includes(isDocumentLevel(target) ? getTargetDocument(target) : target) && !ignoredInInput(registration, event, target) && matchKeyboardEvent(event, registration.parsedSequence[registration.currentIndex], registration.options.platform).matched) return true; } return false; } #processSequences(event, target, eventType, capture, registrations) { if (registrations.length === 0) return; if (isRecordingEvent(event)) { let changed = false; for (const registration of registrations) if (registration.currentIndex > 0) { registration.currentIndex = 0; this.#clearSequenceReset(registration.id); changed = true; } if (changed) this.#notify(); return; } if (!isSequenceStep(event)) return; const now = Date.now(); let changed = false; const candidates = /* @__PURE__ */ new Map(); const bestScores = /* @__PURE__ */ new Map(); let bestScore = 0; for (const registration of registrations) { if (!this.#isLive(registration) || ignoredInInput(registration, event, target) || registration.options.eventType !== eventType || this.#skips(registration, event)) continue; if (registration.currentIndex > 0 && now - registration.lastKeyTime > sequenceTimeout(registration)) { registration.currentIndex = 0; changed = true; } const expected = registration.parsedSequence[registration.currentIndex]; if (!expected) continue; let match = matchKeyboardEvent(event, expected, registration.options.platform); let nextIndex = registration.currentIndex + 1; if (!match.matched && registration.currentIndex > 0) { match = matchKeyboardEvent(event, registration.parsedSequence[0], registration.options.platform); nextIndex = 1; } const score = nextIndex === 1 && this.#sequenceOwned.get(event) ? 0 : match.score; const rank = this.#scopeRank(registration.options.scope); candidates.set(registration.id, { score, nextIndex, rank }); bestScores.set(rank, Math.max(bestScores.get(rank) ?? 0, score)); bestScore = Math.max(bestScore, score); } const completed = []; for (const registration of registrations) { const candidate = candidates.get(registration.id); if (!candidate) continue; if (candidate.score > 0 && candidate.score === bestScores.get(candidate.rank)) { registration.lastKeyTime = now; registration.currentIndex = candidate.nextIndex; changed = true; if (registration.currentIndex >= registration.parsedSequence.length) { registration.currentIndex = 0; completed.push(registration); } else if (registration.options.preventDefault) this.#prevent(event); } else if (registration.currentIndex > 0 && !(bestScore === 0 && keepsSequenceProgress(event))) { registration.currentIndex = 0; changed = true; } } for (const registration of registrations) { if (!candidates.has(registration.id)) continue; if (registration.currentIndex > 0) this.#scheduleSequenceReset(registration.id, registration.lastKeyTime + sequenceTimeout(registration) + 1 - now); else this.#clearSequenceReset(registration.id); } if (changed && completed.length === 0) this.#notify(); const bestRank = Math.max(...completed.map((registration) => this.#scopeRank(registration.options.scope))); for (const snapshot of completed) { if (this.#scopeRank(snapshot.options.scope) !== bestRank) continue; const registration = this.#currentIn(snapshot, capture); if (!registration || !this.#isLive(registration)) continue; this.#consume(registration, event); this.#fire(registration, event); } } /** * Ends keyup chords' presses at the first listener an event reaches, so a * key that a chord's own listener never receives still counts. A new press * cancels every press in progress, and a release of the pressed key or of * one of the chord's modifiers ends that press. The chord's own listener * then fires it, if the release reaches it. */ #endPresses(event, eventType) { if (eventType === "keydown") { if (!event.repeat) this.#pendingReleases.clear(); return; } const ended = /* @__PURE__ */ new Map(); const eventKey = normalizeKeyName(event.key); for (const [id, press] of this.#pendingReleases) { const { parsedChord, options } = this.registrations.state.get(id); const pressed = press.identity.code; if (matchKeyboardEvent(event, parsedChord, options.platform).matched || pressed !== "" && pressed === event.code || parsedChord.modifiers.includes(eventKey) && !event.getModifierState(eventKey)) { ended.set(id, press); this.#pendingReleases.delete(id); } } this.#endedPresses.set(event, ended); } /** * The event being dispatched in the target's window. A listener inside a * shadow root can't read `window.event`, so the last keydown stands in. */ /** * The key event being dispatched now, if any. The keydown a window listener * saw wins while it is still dispatching, so a click or focus handler that * the keydown triggered still counts as that keydown. */ #currentEvent() { const keydown = this.#keydown; if (keydown?.eventPhase) return keydown; const event = typeof window === "undefined" ? void 0 : window.event; return event?.eventPhase && event.type.startsWith("key") ? event : void 0; } /** Marks a registration that went live during the current key event. */ #markLive(id) { const event = this.#currentEvent(); if (event) this.#liveDuring.set(id, event); } #prevent(event) { if (!event.defaultPrevented) this.#prevented.add(event); event.preventDefault(); } /** * Whether the registration skips the event: Escape belongs to a dialog, * popover, or menu outside its target, another listener prevented the * event and the registration skips such events, or the event was being * dispatched when the registration went live. */ #skips(registration, event) { return this.#wentLiveDuring(registration, event) || yieldsEscape(event, registration.target, registration.options.scope !== "global") || !!registration.options.ignoreDefaultPrevented && event.defaultPrevented && !this.#prevented.has(event); } /** * Whether the registration, or its scope, went live during this event's * dispatch, or, for a sequence, this is the release of the key press it * went live during. Keyup chords track their releases themselves. */ #wentLiveDuring(registration, event) { return [this.#liveDuring.get(registration.id), this.#scopeLiveDuring.get(registration.options.scope)].some((live) => live === event || !!live && registration.kind === "sequence" && event.type === "keyup" && live.type === "keydown" && (live.code || live.key) === (event.code || event.key)); } /** Applies a matched registration's preventDefault and stopPropagation options. */ #consume(registration, event) { if (registration.options.preventDefault) this.#prevent(event); if (registration.options.stopPropagation) event.stopPropagation(); } /** Counts a trigger, notifies subscribers (such as devtools), and runs the callback. */ #fire(registration, event, context = this.#callbackContext(registration)) { registration.triggerCount++; if (registration.kind === "sequence") registration.hasFired = true; this.#notify(); const prevented = event.defaultPrevented; try { registration.callback(event, context); } catch (error) { queueMicrotask(() => { throw error; }); } if (!prevented && event.defaultPrevented) this.#prevented.add(event); } #callbackContext(registration) { return registration.kind === "chord" ? { kind: "chord", hotkey: registration.hotkey, parsedChord: registration.parsedChord } : { kind: "sequence", hotkey: registration.hotkey, parsedSequence: registration.parsedSequence }; } /** * Finds an existing registration on the same target, scope, and event type whose steps * resolve to the same identity. Each side keeps its own platform, so `Mod+S` on macOS * and `Mod+S` on Windows are different bindings. */ #findConflictingRegistration(candidate) { const steps = resolvedSteps(candidate); for (const registration of this.registrations.state.values()) if (registration.target === candidate.target && registration.options.scope === candidate.options.scope && registration.options.eventType === candidate.options.eventType && parsedStepsEqual(resolvedSteps(registration), steps)) return registration; return null; } /** * Determines if a registration should be reset based on the keyup event. */ #shouldResetRegistration(registration, event) { const parsed = registration.parsedChord; const releasedKey = normalizeKeyName(event.key); const code = registration.activeMatch?.code; if (code && event.code === code) return true; return (parsed.code !== void 0 ? event.code === parsed.code : keysEqual(releasedKey, parsed.key)) || parsed.modifiers.includes(releasedKey); } /** * Resets the progress of every in-progress sequence. */ resetSequenceProgress() { for (const registration of this.registrations.state.values()) if (registration.kind === "sequence") { registration.currentIndex = 0; registration.lastKeyTime = 0; } for (const timer of this.#sequenceResetTimers.values()) clearTimeout(timer); this.#sequenceResetTimers.clear(); this.#notify(); } /** * Gets the number of registered hotkeys, chords and sequences. */ getRegistrationCount() { return this.registrations.state.size; } /** * Checks if a specific hotkey is registered. * * @param hotkey - The chord or sequence to check * @param target - Optional target element to match (if provided, both hotkey and target must match) * @returns True if a matching registration exists */ isRegistered(hotkey, target) { for (const registration of this.registrations.state.values()) if (areHotkeysEqual(registration.hotkey, hotkey, registration.options.platform) && (target === void 0 || registration.target === target)) return true; return false; } /** * Checks whether a hotkey can fire now: at least one registration is * enabled, in an active scope, and listening where key presses go. A * registration on `document` or `window` always is; one on an element is * only while focus is inside that element. An app hotkey matches * registrations by id, so custom hotkeys apply. * * @param hotkey - A chord, sequence, or app hotkey. No hotkey * (`undefined`, `null`, or `''`) returns false. * @returns True if a registration that can fire exists */ hasActiveRegistration(hotkey) { if (!hotkey) return false; const id = typeof hotkey === "object" && "~appHotkey" in hotkey ? hotkey.id : void 0; for (const registration of this.registrations.state.values()) if (this.#isLive(registration) && targetHasFocus(registration.target) && (id === void 0 ? areHotkeysEqual(registration.hotkey, hotkey, registration.options.platform) : registration.options.appHotkeyId === id)) return true; return false; } /** * Destroys the manager and removes all listeners. */ destroy() { for (const timer of this.#sequenceResetTimers.values()) clearTimeout(timer); this.#sequenceResetTimers.clear(); this.#listeners.destroy(); this.#listenerTargets.clear(); this.#pendingReleases.clear(); this.registrations.setState(() => /* @__PURE__ */ new Map()); this.appHotkeys.setState(() => null); } }; /** * Gets the singleton HotkeyManager instance. * Convenience function for accessing the manager. */ function getHotkeyManager() { return HotkeyManager.getInstance(); } export { HotkeyManager, getHotkeyManager, toHotkeyRegistrationView };