From 48d67eecfad5ec38801811e2870a3f6d983fb2de Mon Sep 17 00:00:00 2001 From: Moksh Upadhyay Date: Tue, 1 Dec 2026 17:27:56 +0530 Subject: [PATCH] fix: cancel pending autoFocus raf when dropdown closes --- src/hooks/useAccessibility.ts | 6 +++++- tests/useAccessibility.test.tsx | 36 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/hooks/useAccessibility.ts b/src/hooks/useAccessibility.ts index e9571ee..6350d58 100644 --- a/src/hooks/useAccessibility.ts +++ b/src/hooks/useAccessibility.ts @@ -76,11 +76,15 @@ export default function useAccessibility({ React.useEffect(() => { if (open) { window.addEventListener('keydown', handleKeyDown); + let rafId: number | undefined; if (autoFocus) { // FIXME: hack with raf - raf(() => focusMenu({ preventScroll: true }), 3); + rafId = raf(() => focusMenu({ preventScroll: true }), 3); } return () => { + if (rafId !== undefined) { + raf.cancel(rafId); + } window.removeEventListener('keydown', handleKeyDown); focusMenuRef.current = false; }; diff --git a/tests/useAccessibility.test.tsx b/tests/useAccessibility.test.tsx index 931d508..02f6f95 100644 --- a/tests/useAccessibility.test.tsx +++ b/tests/useAccessibility.test.tsx @@ -28,3 +28,39 @@ it('closes without consuming Tab when the overlay ref is omitted', () => { trigger.remove(); } }); + +it('cancels pending autoFocus when closed before raf fires', () => { + jest.useFakeTimers(); + const trigger = document.createElement('button'); + const overlay = document.createElement('div'); + overlay.tabIndex = -1; + document.body.appendChild(trigger); + document.body.appendChild(overlay); + trigger.focus(); + + const { rerender, unmount } = renderHook( + ({ open }) => + useAccessibility({ + open, + autoFocus: true, + triggerRef: { current: trigger }, + overlayRef: { current: overlay }, + }), + { initialProps: { open: true } }, + ); + + try { + rerender({ open: false }); + + act(() => { + jest.runAllTimers(); + }); + + expect(document.activeElement).toBe(trigger); + } finally { + unmount(); + trigger.remove(); + overlay.remove(); + jest.useRealTimers(); + } +});