diff --git a/.changeset/react-ancestor-ref-before-act.md b/.changeset/react-ancestor-ref-before-act.md new file mode 100644 index 000000000..4b721b9e3 --- /dev/null +++ b/.changeset/react-ancestor-ref-before-act.md @@ -0,0 +1,5 @@ +--- +'@tanstack/react-hotkeys': patch +--- + +A hotkey whose `target` is a ref on an ancestor element now registers before Testing Library's `render()` returns. Since 0.27.4 it registered a microtask later, so a test that pressed a key right after `render()` saw nothing happen. diff --git a/.intent/review-state.json b/.intent/review-state.json index 24056c394..7f9a98a2b 100644 --- a/.intent/review-state.json +++ b/.intent/review-state.json @@ -178,7 +178,7 @@ "evidence": ["packages/preact-hotkeys/skills/preact-hotkeys/SKILL.md"] }, "skill:packages/react-hotkeys/skills/react-hotkeys/SKILL.md": { - "fingerprint": "40b526e2652320a0455b01990e3f33310e33a6ce389ceed9bbe81b1089296f44", + "fingerprint": "75accb532e8bb5e5acec19ae4121159b3862daea07ee124fd068c1d1e2d25cb8", "snapshot": { "docs/framework/react/guides/hotkeys-provider-and-scopes.md": "57039ef29571e18c058ea77d104140e33c9b7fbda7de561c4d77247a47a566ce", "docs/framework/react/quick-start.md": "f6024d88aae3520c0457cf3d8590a5cad61e9c5a9ff9278528cfebaedc523c49", @@ -188,7 +188,7 @@ "packages/react-hotkeys/src/HotkeysProvider.tsx": "fdd85693fa9b1d84341a0152601c606ca2be92d33e66019472d78029661dca78", "packages/react-hotkeys/src/useAppHotkeys.ts": "863185672c9c9aaa86c4a28f49707fa3332fba1826ab7a37a43405c667caae93", "packages/react-hotkeys/src/useHotkey.ts": "2222a3625e2a3b52f178681f6373be6a7dc278d2b5dff56ed833050f767b6e56", - "packages/react-hotkeys/src/useHotkeys.ts": "b9718ef67f2c773b7f474c0c556b480657faed6e798c486a978644bdb30ee2f7", + "packages/react-hotkeys/src/useHotkeys.ts": "2be13529121c560ffaedf7a74c3b62452d4110cbef7496cc085e62d9f2c5f949", "packages/react-hotkeys/tests/skills/editor-shortcuts/editor-shortcuts.test.tsx": "73411ec7c25652244ed31ad4120880dfc08d6e10af959bef04d2df5360769fde", "packages/react-hotkeys/tests/skills/editor-shortcuts/fixture.tsx": "613a833bb6412b600925deb4009d16cfbfe7afa9a5dc0b82d1a39b8da8c0230b", "packages/react-hotkeys/tests/skills/editor-shortcuts/grade.tsx": "abb8c54f80f8f64bc55dbf9082ac2275aea03d5626437c3366bd8393463cdb1c", @@ -207,10 +207,12 @@ "packages/react-hotkeys/tests/skills/shortcut-settings/solution.tsx": "3441296dea51490188d34991428fe2b8bf11ce6fafbdf6e2f7595ff7082f1400", "packages/react-hotkeys/tests/skills/shortcut-settings/task.md": "7163ed96e6694c745461f0edaf296b353906cfdb868f9c5df7d08ee01a4ba0ea" }, - "head": "f9fc17f0bbb537e70119ec81cec5d3d94294aa8e", - "outcome": "updated", - "reason": "Added the key lock state helper next to the held-key helpers, with its null-until-reported behavior", - "evidence": ["packages/react-hotkeys/skills/react-hotkeys/SKILL.md"] + "head": "ae620714c86f3a9d9ee96804c3b6ecf8b02693b8", + "outcome": "no-change", + "reason": "Review follow-up: the ancestor ref retry comment names both retries, and a test covers a conflict found by the microtask retry when Suspense shows hidden content again. No skill or planning record describes ref registration timing.", + "evidence": [ + "Changed: packages/react-hotkeys/src/useHotkeys.ts at ae620714c86f3a9d9ee96804c3b6ecf8b02693b8" + ] }, "skill:packages/solid-hotkeys/skills/solid-hotkeys/SKILL.md": { "fingerprint": "72ee2e030b8a054fa7241736950db31389fd1465d974e9bfdb2c74cf47bd4010", @@ -271,7 +273,7 @@ ] }, "planning:_artifacts": { - "fingerprint": "082ccbff3ea83cd6f4d6fc41dd5d62376f54e94dbfa23a4fbf002b0e182700a6", + "fingerprint": "ffc199d6dc762f75128bd5ed0aa40c6c4d42c2cf7d479fc999c1b2245f2118f7", "snapshot": { "_artifacts/domain_map.yaml": "fd7871cd1e1825435a188393cea39ee713f75265a07f7d2b05694881b01f1efe", "_artifacts/skill_spec.md": "d77ed3bb07efdd8a167ae1b5ab08a23e1deba52832ad1bf1ea72625deb25082c", @@ -361,7 +363,7 @@ "packages/react-hotkeys/src/HotkeysProvider.tsx": "fdd85693fa9b1d84341a0152601c606ca2be92d33e66019472d78029661dca78", "packages/react-hotkeys/src/useAppHotkeys.ts": "863185672c9c9aaa86c4a28f49707fa3332fba1826ab7a37a43405c667caae93", "packages/react-hotkeys/src/useHotkey.ts": "2222a3625e2a3b52f178681f6373be6a7dc278d2b5dff56ed833050f767b6e56", - "packages/react-hotkeys/src/useHotkeys.ts": "b9718ef67f2c773b7f474c0c556b480657faed6e798c486a978644bdb30ee2f7", + "packages/react-hotkeys/src/useHotkeys.ts": "2be13529121c560ffaedf7a74c3b62452d4110cbef7496cc085e62d9f2c5f949", "packages/react-hotkeys/tests/skills/editor-shortcuts/editor-shortcuts.test.tsx": "73411ec7c25652244ed31ad4120880dfc08d6e10af959bef04d2df5360769fde", "packages/react-hotkeys/tests/skills/editor-shortcuts/fixture.tsx": "613a833bb6412b600925deb4009d16cfbfe7afa9a5dc0b82d1a39b8da8c0230b", "packages/react-hotkeys/tests/skills/editor-shortcuts/grade.tsx": "abb8c54f80f8f64bc55dbf9082ac2275aea03d5626437c3366bd8393463cdb1c", @@ -402,11 +404,11 @@ "packages/vue-hotkeys/src/useHotkeyRecorder.ts": "f9090de677350d72ae3e1732eab11e5b89b5cf00021f2cc5e88d2fe3f2fb743d", "packages/vue-hotkeys/src/useHotkeys.ts": "219ded7bd27e250567817a9e74cb6c0032a58c1da6a6be81e820f4a67ab6c8c7" }, - "head": "33e0b46f70957660418f1c76e9180c5badccd1fc", + "head": "ae620714c86f3a9d9ee96804c3b6ecf8b02693b8", "outcome": "no-change", - "reason": "Comment wording fix in app-hotkeys.ts (T[K] instead of TInput) and regenerated line numbers; no guidance change.", + "reason": "Review follow-up: the ancestor ref retry comment names both retries, and a test covers a conflict found by the microtask retry when Suspense shows hidden content again. No skill or planning record describes ref registration timing.", "evidence": [ - "Changed: packages/hotkeys/src/app-hotkeys.ts at 33e0b46f70957660418f1c76e9180c5badccd1fc" + "Changed: packages/react-hotkeys/src/useHotkeys.ts at ae620714c86f3a9d9ee96804c3b6ecf8b02693b8" ] }, "source:.changeset/intent-skills.md": { @@ -23787,14 +23789,16 @@ "evidence": ["Core, adapter and e2e suites; battery 159/159"] }, "source:packages/react-hotkeys/tests/hidden-content.test.tsx": { - "fingerprint": "6b96a2f81ae6d8f89c08ad7853fa3fc87e2a5cc8c094584ab482b6febc30fcd4", + "fingerprint": "58a963574f4514cede93fba04583d52cf9c3c92ec3eccdc0a637df6c50fdb415", "snapshot": { - "packages/react-hotkeys/tests/hidden-content.test.tsx": "2e29e6d521d733b26582e64791c85d15e3c75817d156efb645a4d222eeda9d0c" + "packages/react-hotkeys/tests/hidden-content.test.tsx": "12cf27344aba2beaff00cc97598d7e9829c0e96fc574bf6d2914575a6d0c0fe2" }, - "head": "04caadd657dad4bab302200042915d298bd8d5d4", + "head": "ae620714c86f3a9d9ee96804c3b6ecf8b02693b8", "outcome": "no-change", - "reason": "React retry errors reach error boundaries; no skill guidance changes.", - "evidence": ["hidden-content.test.tsx"] + "reason": "Review follow-up: the ancestor ref retry comment names both retries, and a test covers a conflict found by the microtask retry when Suspense shows hidden content again. No skill or planning record describes ref registration timing.", + "evidence": [ + "Changed: packages/react-hotkeys/tests/hidden-content.test.tsx at ae620714c86f3a9d9ee96804c3b6ecf8b02693b8" + ] }, "source:packages/octane-hotkeys/tests/ref-targets.tsrx": { "fingerprint": "eb8e447f3b20db72f7bfb9425b9a5c6532aa0c103126afa046c7239f205db490", diff --git a/packages/react-hotkeys/src/useHotkeys.ts b/packages/react-hotkeys/src/useHotkeys.ts index e7765402f..8a75fe990 100644 --- a/packages/react-hotkeys/src/useHotkeys.ts +++ b/packages/react-hotkeys/src/useHotkeys.ts @@ -5,7 +5,7 @@ import { prepareHotkeyDefinitions, resolveRefTarget, } from '@tanstack/hotkeys/adapter' -import { useRef, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { useHotkeysContext } from './HotkeysProvider' import { useAppHotkeysStoreState } from './_appHotkeysStore' import { useIsomorphicLayoutEffect } from './_useIsomorphicLayoutEffect' @@ -77,9 +77,12 @@ export function useHotkeys( const bindingsRef = useRef | null>( null, ) - // An error from the ref retry, rethrown during render for error boundaries. + // An error from the microtask ref retry, rethrown during render for error + // boundaries. An error from the effect retry below reaches them directly. const [retryError, setRetryError] = useState<{ error: unknown }>() if (retryError) throw retryError.error + // Whether the last update found a ref target still unset. + const waitingRef = useRef(false) // Publish registrations, callbacks, and options in the commit, never during // render. Returns whether a ref target was still unset. @@ -105,12 +108,14 @@ export function useHotkeys( // React attaches a ref on an ancestor element after this component's // layout effects, on mount and when Suspense shows hidden content again. // Resolve again once the commit has attached every ref, unless these - // bindings were destroyed by then. - if (update()) { + // bindings were destroyed or the effect below resolved it first. Only the + // microtask runs when Suspense shows hidden content again. + waitingRef.current = update() + if (waitingRef.current) { queueMicrotask(() => { - if (bindingsRef.current !== bindings) return + if (bindingsRef.current !== bindings || !waitingRef.current) return try { - update() + waitingRef.current = update() } catch (error) { setRetryError({ error }) } @@ -118,6 +123,13 @@ export function useHotkeys( } }) + // Every ref is attached before effects run, and act() runs this before it + // returns, so a test can press a key as soon as render() returns. An error + // here reaches error boundaries directly. + useEffect(() => { + if (waitingRef.current) waitingRef.current = update() + }) + useIsomorphicLayoutEffect(() => { return () => { bindingsRef.current?.destroy() diff --git a/packages/react-hotkeys/tests/hidden-content.test.tsx b/packages/react-hotkeys/tests/hidden-content.test.tsx index 9d1e8fd84..67ffc8543 100644 --- a/packages/react-hotkeys/tests/hidden-content.test.tsx +++ b/packages/react-hotkeys/tests/hidden-content.test.tsx @@ -26,7 +26,6 @@ describe('hotkeys inside hidden content', () => { HotkeyManager.resetInstance() }) - // React attaches an ancestor's ref after its children's layout effects. // React attaches an ancestor's ref after its children's layout effects, // so the hotkey registers once the commit has attached it. function pressPanel(panel: HTMLElement) { @@ -67,50 +66,106 @@ describe('hotkeys inside hidden content', () => { expect(fired).toEqual(['save']) }) - it('reports a conflict found on the retry to the error boundary', async () => { - vi.spyOn(console, 'error').mockImplementation(() => {}) - class Boundary extends React.Component< - { children: React.ReactNode }, - { failed: boolean } - > { - state = { failed: false } - static getDerivedStateFromError() { - return { failed: true } - } - render() { - return this.state.failed ? ( -

failed

- ) : ( - this.props.children - ) - } + // Testing Library's render() runs in act(), and tests often press a key as + // soon as it returns. + it('registers an ancestor ref target before render() returns', () => { + const fired: Array = [] + const { getByTestId } = render() + pressPanel(getByTestId('panel')) + expect(fired).toEqual(['save']) + }) + + class Boundary extends React.Component< + { children: React.ReactNode }, + { failed: boolean } + > { + state = { failed: false } + static getDerivedStateFromError() { + return { failed: true } + } + render() { + return this.state.failed ? ( +

failed

+ ) : ( + this.props.children + ) } - function Strict({ + } + function Strict({ + target, + }: { + target: React.RefObject + }) { + useHotkey('Mod+S', () => {}, { + platform: 'mac', target, - }: { - target: React.RefObject - }) { - useHotkey('Mod+S', () => {}, { - platform: 'mac', - target, - conflictBehavior: 'error', - }) + conflictBehavior: 'error', + }) + return null + } + function Conflicting() { + const ref = useRef(null) + return ( +
+ + +
+ ) + } + + it('reports a conflict found on the retry to the error boundary', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const view = render( + + + , + ) + expect(view.queryByTestId('failed')).not.toBeNull() + vi.restoreAllMocks() + }) + + // Showing hidden content again re-runs layout effects but not passive + // effects, so only the microtask retry finds this conflict. + it('reports a conflict found when Suspense shows hidden content again', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const never = new Promise(() => {}) + let suspend!: (on: boolean) => void + function Suspender() { + const [on, setOn] = useState(false) + suspend = setOn + if (on) throw never return null } - function Conflicting() { + let bindOther!: (element: HTMLElement) => void + function Other() { + const [element, setElement] = useState(null) + bindOther = setElement + useHotkey('Mod+S', () => {}, { platform: 'mac', target: element }) + return null + } + function StrictPanel() { const ref = useRef(null) return ( -
- +
) } const view = render( - - - , + <> + + + loading

}> + + +
+
+ , ) + const panel = view.getByTestId('panel') + act(() => suspend(true)) + act(() => bindOther(panel)) + act(() => suspend(false)) await act(async () => { await Promise.resolve() })