diff --git a/.changeset/match-keys-first.md b/.changeset/match-keys-first.md new file mode 100644 index 000000000..523634ff3 --- /dev/null +++ b/.changeset/match-keys-first.md @@ -0,0 +1,5 @@ +--- +'@tanstack/hotkeys': patch +--- + +Key presses cost less when many hotkeys are registered. With 100 hotkeys on the document, a key press takes about a fifth of the time it did in Chromium, and about a seventh with 1,000. The manager now reads each key event once for all hotkeys, compares the key before it checks a hotkey's state, and no longer copies its list of hotkeys several times per event. Which hotkeys fire is unchanged. diff --git a/.intent/review-state.json b/.intent/review-state.json index 20de157b1..cb74bc9a8 100644 --- a/.intent/review-state.json +++ b/.intent/review-state.json @@ -95,7 +95,7 @@ ] }, "skill:packages/hotkeys/skills/hotkeys-core/SKILL.md": { - "fingerprint": "44f31755a95d2a7183ace483a9edbbe5af61f9e4ecbc4575f154e5e8cc62da84", + "fingerprint": "672f5476818c7f708e1460cdab16e72baec662026e25b798941b4f5b986004ed", "snapshot": { "docs/framework/react/guides/hotkeys-provider-and-scopes.md": "57039ef29571e18c058ea77d104140e33c9b7fbda7de561c4d77247a47a566ce", "docs/framework/react/guides/hotkeys.md": "14f8f41603cb30d71ae69a527b6f3d58c9ade5d9e1530818c56e4dd32bfcd7c0", @@ -104,7 +104,7 @@ "packages/hotkeys/skills/hotkeys-core/SKILL.md": "7b3987dbd1ff362ca2c243d7f091cfdfa76718ab004f0ca1940f37ebdde4def8", "packages/hotkeys/skills/hotkeys-core/references/scopes.md": "1139da465c06e76ee1d489cb14fc3ce952011666b67f64855846805c241c2108", "packages/hotkeys/skills/hotkeys-core/references/testing.md": "c2957eaac34ca431832069156504cf7434dcb96d5227bcb7cbb2129dc8e979bd", - "packages/hotkeys/src/hotkey-manager.ts": "11d5c43a649bc98992db7e838171fd1be79d45009f344766626285ea347fecc4", + "packages/hotkeys/src/hotkey-manager.ts": "004a43f4e82e78ece8aabecb61b43f45934c452c3f59f4a615c2622407fd933d", "packages/hotkeys/src/match.ts": "80c3c08023591cb2444aa2adbd5249ad7e2aeffd3dc4f8c529f142aab9141aaa", "packages/react-hotkeys/tests/skills/editor-shortcuts/editor-shortcuts.test.tsx": "73411ec7c25652244ed31ad4120880dfc08d6e10af959bef04d2df5360769fde", "packages/react-hotkeys/tests/skills/editor-shortcuts/fixture.tsx": "613a833bb6412b600925deb4009d16cfbfe7afa9a5dc0b82d1a39b8da8c0230b", @@ -116,11 +116,11 @@ "packages/react-hotkeys/tests/skills/editor-shortcuts/solution.tsx": "ec81379bf0e3a9950222cf8525f82f8abefeb6b46339550fd3a8622e61bf4f0d", "packages/react-hotkeys/tests/skills/editor-shortcuts/task.md": "9610d80e7add59f0433cbf210562ff8c481dc2c14371ce31c00a329d9ff1fedf" }, - "head": "243d225e0291f8b364274b43249cec722dad8b17", + "head": "59cceb805ee2c2e9ee86fc8280182f83f44f08f9", "outcome": "no-change", - "reason": "The skill describes matching and the Shift-with-a-symbol type rule, which still hold. The recorder now keeps Mac symbols reported only with Shift, and custom uncased keys go with Shift; neither changes what the skill tells agents to write.", + "reason": "Performance refactor of key event dispatch in hotkey-manager.ts, _match.ts and _target-listeners.ts: the event is read once per pass, keys are compared before a chord's state is checked, and per-event copies of the registration id sets are gone. No public API, option, default or firing rule changed, so the hotkeys-core guidance and the three planning documents stay accurate. Checked by 2,237 core unit tests, unit tests of all 19 packages, 333 browser tests in Chromium, Firefox and WebKit, and 248 keyboard layout tests in Docker.", "evidence": [ - "packages/hotkeys/skills/hotkeys-core/SKILL.md Modifiers match exactly bullet; packages/hotkeys/src/_recorder-chord.ts MAC_COMMAND_SHIFTED_SYMBOLS; key.types.ts ShiftableKey." + "Changed: packages/hotkeys/src/hotkey-manager.ts at 59cceb805ee2c2e9ee86fc8280182f83f44f08f9" ] }, "skill:packages/lit-hotkeys/skills/lit-hotkeys/SKILL.md": { @@ -273,7 +273,7 @@ ] }, "planning:_artifacts": { - "fingerprint": "e6aaa7ca53136bbae36814647651d0900fd7fa2851520da59f4527c24387b51c", + "fingerprint": "ff033d23c5e7da8f65d133075ce029d90e3c493c15fe6246d70558de47e952d7", "snapshot": { "_artifacts/domain_map.yaml": "81f47610362c2c3891c750e50a75b13b461f6304005af9bd7d51a801386bc098", "_artifacts/skill_spec.md": "d77ed3bb07efdd8a167ae1b5ab08a23e1deba52832ad1bf1ea72625deb25082c", @@ -336,7 +336,7 @@ "packages/hotkeys/skills/hotkeys-core/references/testing.md": "c2957eaac34ca431832069156504cf7434dcb96d5227bcb7cbb2129dc8e979bd", "packages/hotkeys/src/app-hotkeys.ts": "4620760d8409fb78a94319b6e52ca1a00c625121e29006fa1cef057fdeafa937", "packages/hotkeys/src/conflicts.ts": "3c8628500aee3e7ba14ec78411b5f5398fd66cbc00359ffdf227a81729a76fe5", - "packages/hotkeys/src/hotkey-manager.ts": "11d5c43a649bc98992db7e838171fd1be79d45009f344766626285ea347fecc4", + "packages/hotkeys/src/hotkey-manager.ts": "004a43f4e82e78ece8aabecb61b43f45934c452c3f59f4a615c2622407fd933d", "packages/hotkeys/src/hotkey-recorder.ts": "55c0e764812a4dd3907c915939904613fc3b7b66d967e09e5bedb754b143056a", "packages/hotkeys/src/match.ts": "80c3c08023591cb2444aa2adbd5249ad7e2aeffd3dc4f8c529f142aab9141aaa", "packages/lit-hotkeys/skills/lit-hotkeys/SKILL.md": "326b0a1ddd9579c65389e755d5a2e0a69512ef7f91aca21bda7db9c0ddb51521", @@ -404,11 +404,11 @@ "packages/vue-hotkeys/src/useHotkeyRecorder.ts": "f9090de677350d72ae3e1732eab11e5b89b5cf00021f2cc5e88d2fe3f2fb743d", "packages/vue-hotkeys/src/useHotkeys.ts": "219ded7bd27e250567817a9e74cb6c0032a58c1da6a6be81e820f4a67ab6c8c7" }, - "head": "243d225e0291f8b364274b43249cec722dad8b17", + "head": "59cceb805ee2c2e9ee86fc8280182f83f44f08f9", "outcome": "no-change", - "reason": "No new domain or reference is needed: both changes refine existing recorder and type rules.", + "reason": "Performance refactor of key event dispatch in hotkey-manager.ts, _match.ts and _target-listeners.ts: the event is read once per pass, keys are compared before a chord's state is checked, and per-event copies of the registration id sets are gone. No public API, option, default or firing rule changed, so the hotkeys-core guidance and the three planning documents stay accurate. Checked by 2,237 core unit tests, unit tests of all 19 packages, 333 browser tests in Chromium, Firefox and WebKit, and 248 keyboard layout tests in Docker.", "evidence": [ - "_artifacts/domain_map.yaml already covers recording and hotkey string types." + "Changed: packages/hotkeys/src/hotkey-manager.ts at 59cceb805ee2c2e9ee86fc8280182f83f44f08f9" ] }, "source:.changeset/intent-skills.md": { @@ -664,24 +664,28 @@ ] }, "source:docs/reference/classes/HotkeyManager.md": { - "fingerprint": "b736e804ca87593fb73865ff759cec35b0e882ae80173774d368f27d7b0076a5", + "fingerprint": "9fc36c41935243987969a8883a0d53ef2ee9da799b04ab1d57810dc521e321d1", "snapshot": { - "docs/reference/classes/HotkeyManager.md": "04225c4292b8d315af3aa7384b3024bdd0ac96c60de55615b847c919b273c579" + "docs/reference/classes/HotkeyManager.md": "26deec98a47b37b2e7c0e14cfff1424b6bd82ddda125b72ad4fc16415f94a556" }, - "head": "f026c8ab12658715ab51ace277262ea6e38eddc2", - "outcome": "out-of-scope", - "reason": "Generated reference docs, sidebar config, unit tests, or e2e specs for the Shift-with-symbol type rule, the SymbolKey rename, the recorder change, and formatForDisplay(\"Mod\"); no skill guidance depends on them.", - "evidence": ["No skill references this file"] + "head": "d9063cefbc8bf789116bc165c6ad91d9bf1f78e2", + "outcome": "no-change", + "reason": "The autofix job regenerated two reference pages. All 7 changed lines are 'Defined in' links whose hotkey-manager.ts line numbers moved by 13; no documented API, signature or description changed.", + "evidence": [ + "Changed: docs/reference/classes/HotkeyManager.md at d9063cefbc8bf789116bc165c6ad91d9bf1f78e2" + ] }, "source:docs/reference/functions/getHotkeyManager.md": { - "fingerprint": "068e8543b8a799f27f911aa3457a7cbb2eb19a0533a39be647e0e91a3bf7c3b5", + "fingerprint": "04d140f54bf584b22f14e1cbf4669e46d1c6c834ab7251fec17cd988b10863bf", "snapshot": { - "docs/reference/functions/getHotkeyManager.md": "071c823e94184cb47fc5f514df5540061ce62b1b7b57f513c7d59d2bad7957eb" + "docs/reference/functions/getHotkeyManager.md": "f8f7b70a932532b6f4b9295a8ee8cf54fd516657ee258f8ae2d8d43f8d04fc22" }, - "head": "f026c8ab12658715ab51ace277262ea6e38eddc2", - "outcome": "out-of-scope", - "reason": "Generated reference docs, sidebar config, unit tests, or e2e specs for the Shift-with-symbol type rule, the SymbolKey rename, the recorder change, and formatForDisplay(\"Mod\"); no skill guidance depends on them.", - "evidence": ["No skill references this file"] + "head": "d9063cefbc8bf789116bc165c6ad91d9bf1f78e2", + "outcome": "no-change", + "reason": "The autofix job regenerated two reference pages. All 7 changed lines are 'Defined in' links whose hotkey-manager.ts line numbers moved by 13; no documented API, signature or description changed.", + "evidence": [ + "Changed: docs/reference/functions/getHotkeyManager.md at d9063cefbc8bf789116bc165c6ad91d9bf1f78e2" + ] }, "source:examples/alpine/kitchen-sink/index.html": { "fingerprint": "e576c33ec891eff09138d3a05b3c29fffc60c984b7f4e88a1dca3848a899cdc5", @@ -4368,15 +4372,15 @@ ] }, "source:packages/hotkeys/tests/input-detection.test.ts": { - "fingerprint": "817e5c72fbdf2ba89dbf58003e7662466b06a716d35f042e6177092ba9e975ad", + "fingerprint": "391c24c5dfdac3431d64ccfefcaeef67527d84734537256f5bfd394b2598b893", "snapshot": { - "packages/hotkeys/tests/input-detection.test.ts": "ae2a0b301305485d9c2d0049ca7231e91da2a159e1c05231b44f9fd50d80ff73" + "packages/hotkeys/tests/input-detection.test.ts": "cffa83151964ec2c8b094caa96529f9ed987df88b098d4384d6e49ec2a771d0d" }, - "head": "ce272666d8aae7bebafc02b184b29fcd2e853125", + "head": "856f644ea45ad94419f9ec6205ebe2594aa41842", "outcome": "no-change", - "reason": "Combined test-coverage branch: tests, test setup, e2e suites, CI workflows and tooling config only. Regenerated reference pages only reorder a union type or change a node_modules path. No API or guidance change.", + "reason": "Test-only change in input-detection.test.ts: a second case pins that the bubble-phase hotkey is skipped when no earlier hotkey skips text fields. No source or guidance changed.", "evidence": [ - "Changed: packages/hotkeys/tests/input-detection.test.ts at ce272666d8aae7bebafc02b184b29fcd2e853125" + "Changed: packages/hotkeys/tests/input-detection.test.ts at 856f644ea45ad94419f9ec6205ebe2594aa41842" ] }, "source:packages/hotkeys/tests/registration-and-target.test.ts": { @@ -4410,14 +4414,16 @@ "evidence": ["e2e/support/x11.ts"] }, "source:packages/hotkeys/src/_match.ts": { - "fingerprint": "0995379b09a5bd847d3a736e1cba492f5c653b08dabc9cff7bcfabde880b4dab", + "fingerprint": "2aa643cbb50bb1096fda63734caf196e9e03adad4011165ddae9fdcaf3eb7c2a", "snapshot": { - "packages/hotkeys/src/_match.ts": "dc54a8a388f697eb9cf1c4d3fe281786a845cbd992c4a66330be98e494694be9" + "packages/hotkeys/src/_match.ts": "7e20de30e5a143aad3f2766182c17093d714e8285bb897419d155bb389f51e7f" }, - "head": "cd1c66aab538ccac294e72ee36ae4466fa9b2d2b", + "head": "59cceb805ee2c2e9ee86fc8280182f83f44f08f9", "outcome": "no-change", - "reason": "Internal change: the private constants move or the character-key classification behind suspendCharacterKeys. The core skill covers the public behavior.", - "evidence": ["packages/hotkeys/skills/hotkeys-core/SKILL.md"] + "reason": "Performance refactor of key event dispatch in hotkey-manager.ts, _match.ts and _target-listeners.ts: the event is read once per pass, keys are compared before a chord's state is checked, and per-event copies of the registration id sets are gone. No public API, option, default or firing rule changed, so the hotkeys-core guidance and the three planning documents stay accurate. Checked by 2,236 core unit tests, unit tests of all 19 packages, 333 browser tests in Chromium, Firefox and WebKit, and 248 keyboard layout tests in Docker.", + "evidence": [ + "Changed: packages/hotkeys/src/_match.ts at 59cceb805ee2c2e9ee86fc8280182f83f44f08f9" + ] }, "source:packages/hotkeys/tests/match.test.ts": { "fingerprint": "29930787adfc4098826fa994f10f2f118b0f65e77ca0e48a5f2cfaaf8be07946", @@ -7394,15 +7400,15 @@ "evidence": ["packages/vue-hotkeys/tests/unset-values.test.ts"] }, "source:packages/hotkeys/src/_target-listeners.ts": { - "fingerprint": "8a51e16771a1ce1f0315a0f1a5c897086284d5979bcffc72418e9c29eff236e7", + "fingerprint": "9c715beaa3aa22febb49eab64adf27d5e920f21d21e7cf7b948ece4c74118258", "snapshot": { - "packages/hotkeys/src/_target-listeners.ts": "39a0ca154b1dc5bfe6907108e1ca1603388b8a3153820eaa41bd033240aea5bc" + "packages/hotkeys/src/_target-listeners.ts": "d44c8263f113cba31d801e6c3e6fa50ed43ccded15394b6fb62191394272fc4f" }, - "head": "a3fc3ae3a058631dfe821a04edf4cf0cce49fb0a", + "head": "59cceb805ee2c2e9ee86fc8280182f83f44f08f9", "outcome": "no-change", - "reason": "Recorder target now cancels when its window closes; element hotkeys follow their element on focus. Skills don't cover the recorder target or listener placement, so no guidance changes", + "reason": "Performance refactor of key event dispatch in hotkey-manager.ts, _match.ts and _target-listeners.ts: the event is read once per pass, keys are compared before a chord's state is checked, and per-event copies of the registration id sets are gone. No public API, option, default or firing rule changed, so the hotkeys-core guidance and the three planning documents stay accurate. Checked by 2,237 core unit tests, unit tests of all 19 packages, 333 browser tests in Chromium, Firefox and WebKit, and 248 keyboard layout tests in Docker.", "evidence": [ - "Changed: packages/hotkeys/src/_target-listeners.ts at a3fc3ae3a058631dfe821a04edf4cf0cce49fb0a" + "Changed: packages/hotkeys/src/_target-listeners.ts at 59cceb805ee2c2e9ee86fc8280182f83f44f08f9" ] }, "source:packages/hotkeys/tests/capture.test.ts": { diff --git a/docs/reference/classes/HotkeyManager.md b/docs/reference/classes/HotkeyManager.md index 7f6bfb161..1a7fb7b9d 100644 --- a/docs/reference/classes/HotkeyManager.md +++ b/docs/reference/classes/HotkeyManager.md @@ -113,7 +113,7 @@ manager.activateScope('dialog', { exclusive: { allow: ['global'] } }) destroy(): void; ``` -Defined in: [hotkey-manager.ts:2274](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2274) +Defined in: [hotkey-manager.ts:2287](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2287) Destroys the manager and removes all listeners. @@ -129,7 +129,7 @@ Destroys the manager and removes all listeners. getRegistrationCount(): number; ``` -Defined in: [hotkey-manager.ts:2206](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2206) +Defined in: [hotkey-manager.ts:2219](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2219) Gets the number of registered hotkeys, chords and sequences. @@ -145,7 +145,7 @@ Gets the number of registered hotkeys, chords and sequences. hasActiveRegistration(hotkey): boolean; ``` -Defined in: [hotkey-manager.ts:2244](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2244) +Defined in: [hotkey-manager.ts:2257](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2257) Checks whether a hotkey can fire now: at least one registration is enabled, in an active scope, and listening where key presses go. A @@ -179,7 +179,7 @@ True if a registration that can fire exists isRegistered(hotkey, target?): boolean; ``` -Defined in: [hotkey-manager.ts:2217](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2217) +Defined in: [hotkey-manager.ts:2230](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2230) Checks if a specific hotkey is registered. @@ -305,7 +305,7 @@ handle.unregister() resetSequenceProgress(): void; ``` -Defined in: [hotkey-manager.ts:2191](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2191) +Defined in: [hotkey-manager.ts:2204](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2204) Resets the progress of every in-progress sequence. @@ -357,7 +357,7 @@ resume() trigger(id, event?): boolean; ``` -Defined in: [hotkey-manager.ts:2179](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2179) +Defined in: [hotkey-manager.ts:2192](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2192) Runs a registration's callback without a key press, as for a command palette entry or a devtools button. The callback gets the same context as diff --git a/docs/reference/functions/getHotkeyManager.md b/docs/reference/functions/getHotkeyManager.md index d6f5bb9e5..bda881c6f 100644 --- a/docs/reference/functions/getHotkeyManager.md +++ b/docs/reference/functions/getHotkeyManager.md @@ -9,7 +9,7 @@ title: getHotkeyManager function getHotkeyManager(): HotkeyManager; ``` -Defined in: [hotkey-manager.ts:2295](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2295) +Defined in: [hotkey-manager.ts:2308](https://github.com/TanStack/hotkeys/blob/main/packages/hotkeys/src/hotkey-manager.ts#L2308) Gets the singleton HotkeyManager instance. Convenience function for accessing the manager. diff --git a/package.json b/package.json index aa3ed7f5a..87b7c0994 100644 --- a/package.json +++ b/package.json @@ -63,7 +63,7 @@ "name": "HotkeyManager", "path": "packages/hotkeys/dist/index.js", "import": "{ getHotkeyManager }", - "limit": "9.25 KB" + "limit": "9.3 KB" }, { "name": "HotkeyRecorder", @@ -129,7 +129,7 @@ "react", "react-dom" ], - "limit": "12 KB" + "limit": "12.1 KB" }, { "name": "Preact useHotkey", @@ -197,7 +197,7 @@ "ignore": [ "alpinejs" ], - "limit": "13 KB" + "limit": "13.1 KB" }, { "name": "Alpine hotkeyDirective", diff --git a/packages/hotkeys/src/_match.ts b/packages/hotkeys/src/_match.ts index 88b5c75a6..8e3e0c99f 100644 --- a/packages/hotkeys/src/_match.ts +++ b/packages/hotkeys/src/_match.ts @@ -33,13 +33,26 @@ export interface KeyboardEventMatch { identity?: KeyIdentity } -/** Matches an event and reports the winning candidate and release identity. */ +/** The event as each platform reads it, kept while it is matched against many chords. */ +export type KeyboardEventReads = Partial< + Record +> + +/** + * Matches an event and reports the winning candidate and release identity. + * A caller that matches one event against many chords passes the same `reads` + * object each time, so the event is read once per platform. + */ export function matchKeyboardEvent( event: KeyboardEvent, parsed: ParsedHotkeyChord, platform: HotkeyPlatform = detectPlatform(), + reads: KeyboardEventReads = {}, ): KeyboardEventMatch { - const normalized = normalizeKeyboardEvent(event, platform) + const normalized = (reads[platform] ??= normalizeKeyboardEvent( + event, + platform, + )) const noMatch: KeyboardEventMatch = { matched: false, score: 0 } // Keys pressed while composing belong to the input method editor. @@ -63,7 +76,7 @@ export function matchKeyboardEvent( if (parsed.code !== undefined) { return !altGraph && shiftMatches && normalized.code === parsed.code - ? matched(3) + ? matched(3, normalized) : noMatch } @@ -90,7 +103,7 @@ export function matchKeyboardEvent( !'<>'.includes(parsed.key) && US_SHIFTED[US_UNSHIFTED.indexOf(normalized.key)] === parsed.key ) { - return matched(2) + return matched(2, normalized) } if (keysEqual(normalized.key, parsed.key)) { @@ -101,7 +114,7 @@ export function matchKeyboardEvent( !parsed.shift && !shiftTypedNothing if (shiftMatches || (implicitShift && normalized.shift)) { - return matched(implicitShift ? 2 : 3) + return matched(implicitShift ? 2 : 3, normalized) } } @@ -113,7 +126,7 @@ export function matchKeyboardEvent( // native Windows apps. An exact `ı` binding outranks it. With Alt, the // position decides instead: macOS Option+Shift+B types `ı` too. if (normalized.key === 'ı' && parsed.key === 'I' && !normalized.alt) { - return matched(2) + return matched(2, normalized) } // macOS Option changes what a key types: French Option+A types `æ` on the @@ -163,17 +176,19 @@ export function matchKeyboardEvent( codeToLogicalKey(normalized.code) ?? (normalized.key === 'Unidentified' ? normalized.code : undefined) return fallbackKey !== undefined && keysEqual(fallbackKey, parsed.key) - ? matched(1) + ? matched(1, normalized) : noMatch +} - // Preserve the triggering code so keyup can reset a shortcut even if its character changes. - function matched(score: 1 | 2 | 3): KeyboardEventMatch { - return { - matched: true, - score, - identity: { key: normalized.key, code: normalized.code }, - } - } +/** + * A match of the given score. It keeps the pressed key, so the key's release + * ends the press even if its character changed. + */ +function matched( + score: 1 | 2 | 3, + { key, code }: NormalizedKeyboardEvent, +): KeyboardEventMatch { + return { matched: true, score, identity: { key, code } } } /** diff --git a/packages/hotkeys/src/_target-listeners.ts b/packages/hotkeys/src/_target-listeners.ts index 5a9f37b32..4d95b459f 100644 --- a/packages/hotkeys/src/_target-listeners.ts +++ b/packages/hotkeys/src/_target-listeners.ts @@ -17,13 +17,8 @@ export class TargetListeners { #targets = new Map>() /** Listener groups per window, and its Escape listener while any exist. */ #windows = new Map() - #processed = new WeakMap< - KeyboardEvent, - { - ids: Set - groups: Set> - } - >() + /** Per event, the registrations each listener group it reached has processed. */ + #processed = new WeakMap, Set>>() constructor( private dispatch: ( @@ -64,24 +59,23 @@ export class TargetListeners { (eventType: HotkeyEventType): EventListener => (rawEvent) => { const event = rawEvent as KeyboardEvent - let processed = this.#processed.get(event) + const earlier = this.#processed.get(event) // The same event object can be dispatched again. Seeing the same // group twice starts a new dispatch rather than suppressing it. - const first = !processed || processed.groups.has(ids) - if (!processed || first) { - processed = { ids: new Set(), groups: new Set() } - this.#processed.set(event, processed) - } - processed.groups.add(ids) + const first = !earlier || earlier.has(ids) + const processed = first + ? new Map, Set>() + : earlier + this.#processed.set(event, processed) // Snapshot before callbacks can move registrations between phases. // A moved registration must not process this event a second time. - const pending = new Set() - for (const registrationId of ids) { - if (!processed.ids.has(registrationId)) { - processed.ids.add(registrationId) - pending.add(registrationId) + const pending = new Set(ids) + for (const seen of processed.values()) { + for (const registrationId of pending) { + if (seen.has(registrationId)) pending.delete(registrationId) } } + processed.set(ids, pending) this.dispatch(event, target, eventType, capture, pending, first) } group = { diff --git a/packages/hotkeys/src/hotkey-manager.ts b/packages/hotkeys/src/hotkey-manager.ts index ac10f5ffe..06da225fa 100644 --- a/packages/hotkeys/src/hotkey-manager.ts +++ b/packages/hotkeys/src/hotkey-manager.ts @@ -33,7 +33,7 @@ import { simplifyHotkey, } from './parse' import { detectPlatform } from './platform' -import type { KeyboardEventMatch } from './_match' +import type { KeyboardEventMatch, KeyboardEventReads } from './_match' import type { Store } from './_store' import type { ListenerTarget } from './_target-listeners' import type { AppHotkey, AppHotkeysStore } from './app-hotkeys' @@ -1468,22 +1468,19 @@ export class HotkeyManager { this.#sequenceResetTimers.delete(id) } - /** Registrations of one kind in the listener phase, in registration order. */ - #registrationsIn( - ids: Set, + /** The sequences among `ids` that listen in the phase, in registration order. */ + #sequencesIn( + ids: Iterable, capture: boolean, - kind: TKind, - ): Array> { - const result: Array> = [] + ): Array { + const result: Array = [] for (const id of ids) { const registration = this.registrations.state.get(id) if ( - registration?.kind === kind && + registration?.kind === 'sequence' && !!registration.options.capture === capture ) { - result.push( - registration as Extract, - ) + result.push(registration) } } return result @@ -1520,8 +1517,11 @@ export class HotkeyManager { this.#sequenceOwned.set(event, this.#isOwnedBySequence(event, eventType)) this.#endPresses(event, eventType) } - if (capture) { - // Capture listeners are always on the registrations' own target. + // One round is enough when every registration here listens on its own + // target: always in the capture phase, and in the bubble phase while no + // registration follows its element's root. An event that arrives stopped + // takes the rounds below, which leave some registrations out. + if (capture || (!this.#followers.size && !event.cancelBubble)) { this.#processRound(event, target as Target, eventType, capture, ids) return } @@ -1574,19 +1574,31 @@ export class HotkeyManager { capture: boolean, ids: Set, ): void { - this.#processChords( - event, - target, - eventType, - capture, - this.#registrationsIn(ids, capture, 'chord'), - ) + const { state } = this.registrations + const chords: Array = [] + // Every other id: the sequences, and registrations that a callback moved + // to the other phase and may move back. + const rest: Array = [] + for (const id of ids) { + const registration = state.get(id) + if ( + registration?.kind === 'chord' && + !!registration.options.capture === capture + ) { + chords.push(registration) + } else { + rest.push(id) + } + } + this.#processChords(event, target, eventType, capture, chords) + // Look up the sequences after the chords ran: a callback may have + // unregistered or moved one. this.#processSequences( event, target, eventType, capture, - this.#registrationsIn(ids, capture, 'sequence'), + this.#sequencesIn(rest, capture), ) } @@ -1616,66 +1628,76 @@ export class HotkeyManager { } if (isRecordingEvent(event) || this.#sequenceOwned.get(event)) return - const matches = new Map() + // The chords that matched, in registration order. + const matches: Array<[HotkeyChordRegistration, KeyboardEventMatch]> = [] // A chord that can't fire but has `preventDefault: 'always'` matched. let reserved = false + const reads: KeyboardEventReads = {} + const ended = this.#endedPresses.get(event) for (const registration of registrations) { - const live = this.#isLive(registration) - const { eventType: firesOn, preventDefault } = registration.options + const { parsedChord, id } = registration + const { + eventType: firesOn, + preventDefault, + platform, + } = registration.options // A keyup chord also sees its keydown, to prevent it and await the release. const press = eventType === 'keydown' && firesOn === 'keyup' - const skipped = this.#skips(registration, event) - const { parsedChord, id } = registration - const { platform } = registration.options - // The press this release ended, even while the hotkey can't fire. - const released = this.#endedPresses.get(event)?.get(id) + // The first chord to ask reads the focused element for the whole key + // press, so this stays ahead of the key comparison: a callback or + // another listener may move focus before a later chord asks. if ( (firesOn !== eventType && !press) || ignoredInInput(registration, event, target) ) { continue } - let result = matchKeyboardEvent(event, parsedChord, platform) + // The press this release ended, even while the hotkey can't fire. A + // keyup chord fires only for the release of a press it matched. + const released = ended?.get(id) + if (eventType === 'keyup' && !released) continue + let result = matchKeyboardEvent(event, parsedChord, platform, reads) + // Most chords are for another key, so compare keys before reading the + // registration's state. + if (!result.matched && !released) continue + const live = this.#isLive(registration) + const skipped = this.#skips(registration, event) if (press) { - if (result.matched) { - if (skipped) { - this.#pendingReleases.delete(id) - } else { - if (live && preventDefault) { - this.#prevent(event) - } else if (!live && preventDefault === 'always') { - // Like any reserved key, prevented only if no live hotkey handles it - reserved = true - } - // Recorded even while the hotkey can't fire, so a callback that - // enables it during this press, such as to end a mode, still - // gets the release. An auto-repeat continues a press and can't - // restart one that another key cancelled. - if (!event.repeat) this.#pendingReleases.set(id, result) + // Only a press that matched gets here: a keydown ends no press. + if (skipped) { + this.#pendingReleases.delete(id) + } else { + if (live && preventDefault) { + this.#prevent(event) + } else if (!live && preventDefault === 'always') { + // Like any reserved key, prevented only if no live hotkey handles it + reserved = true } + // Recorded even while the hotkey can't fire, so a callback that + // enables it during this press, such as to end a mode, still + // gets the release. An auto-repeat continues a press and can't + // restart one that another key cancelled. + if (!event.repeat) this.#pendingReleases.set(id, result) } continue } - if (!live && preventDefault !== 'always') continue - if (eventType === 'keyup') { - // A keyup chord fires only for the release of a press it matched. A - // release that another listener handled ends the press too. - if (!released || skipped) continue - if (!result.matched) result = released - } - if (skipped || !result.matched) continue + // A release that another listener handled ends the press too. + if ((!live && preventDefault !== 'always') || skipped) continue if (!live) { reserved = true continue } - matches.set(registration.id, result) + // A release can report another character than its press did, so the + // press it ended stands in for it. + if (released && !result.matched) result = released + matches.push([registration, result]) } // A hotkey that fires, on any listener, decides what happens to the event. if ( reserved && - matches.size === 0 && + !matches.length && !this.#handledByLiveHotkey(event, eventType) ) { this.#prevent(event) @@ -1684,33 +1706,25 @@ export class HotkeyManager { // The most recently activated scope with a match handles the key, on any // layout. Within it, exact matches outrank compatibility fallbacks. 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) + for (const [registration, { score }] of matches) { + const rank = this.#scopeRank(registration.options.scope) + if (rank > bestRank || (rank === bestRank && score > bestScore)) { + bestRank = rank + bestScore = score } } // Then a physical binding is the more specific one: Numpad Enter fires // `[NumpadEnter]` and not `Enter` too. - const best = registrations.filter( - (registration) => - matches.get(registration.id)?.score === bestScore && + const best = matches.filter( + ([registration, { score }]) => + score === bestScore && this.#scopeRank(registration.options.scope) === bestRank, ) - const physical = best.some(({ parsedChord }) => parsedChord.code) + const physical = best.some(([{ parsedChord }]) => parsedChord.code) - for (const snapshot of best) { - const match = matches.get(snapshot.id)! + for (const [snapshot, match] of best) { if (physical && !snapshot.parsedChord.code) continue // An earlier callback may have released this registration's scope. if (this.#scopeRank(snapshot.options.scope) !== bestRank) continue @@ -1831,6 +1845,7 @@ export class HotkeyManager { const now = Date.now() let changed = false + const reads: KeyboardEventReads = {} // Score eligible next steps (or restarts) before advancing any sequence. // Scores compete within a scope: the scope decides at completion. const candidates = new Map< @@ -1864,17 +1879,15 @@ export class HotkeyManager { continue } - let match = matchKeyboardEvent( - event, - expected, - registration.options.platform, - ) + const { platform } = registration.options + let match = matchKeyboardEvent(event, expected, platform, reads) let nextIndex = registration.currentIndex + 1 if (!match.matched && registration.currentIndex > 0) { match = matchKeyboardEvent( event, registration.parsedSequence[0]!, - registration.options.platform, + platform, + reads, ) nextIndex = 1 } diff --git a/packages/hotkeys/tests/input-detection.test.ts b/packages/hotkeys/tests/input-detection.test.ts index 83b12a615..610d2a6a8 100644 --- a/packages/hotkeys/tests/input-detection.test.ts +++ b/packages/hotkeys/tests/input-detection.test.ts @@ -390,6 +390,33 @@ describe('what does not block a hotkey', () => { }) }) +describe('focus that moves during a key press', () => { + // Presses K on the body while the page's own listener moves focus into a + // text field, between a capture-phase `J` hotkey and the bubble-phase `K`. + function pressWhileFocusMoves(earlier: HotkeyOptions) { + document.body.innerHTML = '' + const input = document.querySelector('input')! + register('J', { ...earlier, capture: true }) + const k = register('K') + const focusInput = () => input.focus() + document.body.addEventListener('keydown', focusInput) + keydown({ key: 'k', target: document.body }) + document.body.removeEventListener('keydown', focusInput) + expect(document.activeElement).toBe(input) + return k + } + + it('judges every hotkey by the focus read for the first one that skips text fields', () => { + // `J` is for another key, but it reads focus first, on the body. + expect(pressWhileFocusMoves({})).toHaveBeenCalledOnce() + }) + + it('reads focus later when no earlier hotkey skips text fields', () => { + // `J` never asks, so `K` is the first to read focus, now in the field. + expect(pressWhileFocusMoves({ ignoreInputs: false })).not.toHaveBeenCalled() + }) +}) + describe('keys dispatched by tests', () => { it('an unfocused custom element is not a hidden text field', () => { // Component tests often dispatch keys on a host element such as