|
| 1 | +import { useLayoutEffect } from 'react'; |
| 2 | +import * as RadixSelect from '@radix-ui/react-select'; |
| 3 | + |
| 4 | +// Radix Select insists on locking scrolling when the dropdown is open. This is a workaround to unlock scrolling. |
| 5 | +const useScrollUnlock = () => { |
| 6 | + useLayoutEffect(() => { |
| 7 | + const TYPE_LIST = ['wheel', 'scroll', 'touchmove'] as const; |
| 8 | + const stopper = (e: Event) => e.stopImmediatePropagation(); |
| 9 | + |
| 10 | + const unlockScroll = () => { |
| 11 | + TYPE_LIST.forEach((type) => { |
| 12 | + window.addEventListener(type, stopper, { capture: true, passive: false }); |
| 13 | + }); |
| 14 | + document.body.removeAttribute('data-scroll-locked'); |
| 15 | + }; |
| 16 | + |
| 17 | + const cleanupListeners = () => { |
| 18 | + TYPE_LIST.forEach((type) => { |
| 19 | + window.removeEventListener(type, stopper, { capture: true }); |
| 20 | + }); |
| 21 | + }; |
| 22 | + |
| 23 | + const mo = new MutationObserver((mutations) => { |
| 24 | + // Only react if data-scroll-locked was added |
| 25 | + const wasLocked = mutations.some( |
| 26 | + (m) => m.type === 'attributes' && document.body.hasAttribute('data-scroll-locked'), |
| 27 | + ); |
| 28 | + if (wasLocked) { |
| 29 | + cleanupListeners(); |
| 30 | + unlockScroll(); |
| 31 | + } |
| 32 | + }); |
| 33 | + |
| 34 | + mo.observe(document.body, { attributes: true, attributeFilter: ['data-scroll-locked'] }); |
| 35 | + |
| 36 | + return () => { |
| 37 | + mo.disconnect(); |
| 38 | + cleanupListeners(); |
| 39 | + }; |
| 40 | + }, []); |
| 41 | +}; |
| 42 | + |
| 43 | +const Root = (props: RadixSelect.SelectProps) => { |
| 44 | + useScrollUnlock(); |
| 45 | + return <RadixSelect.Root {...props} />; |
| 46 | +}; |
| 47 | + |
| 48 | +// Re-export everything from Radix Select, then override Root |
| 49 | +export * from '@radix-ui/react-select'; |
| 50 | +export { Root }; |
0 commit comments