diff --git a/.changeset/overflow-reset-on-disable.md b/.changeset/overflow-reset-on-disable.md new file mode 100644 index 00000000000..6875850d27d --- /dev/null +++ b/.changeset/overflow-reset-on-disable.md @@ -0,0 +1,5 @@ +--- +"@primer/react": patch +--- + +Discard stale overflow measurements when an item stops being observed. diff --git a/packages/react/src/internal/hooks/__tests__/useOverflowObserver.test.tsx b/packages/react/src/internal/hooks/__tests__/useOverflowObserver.test.tsx index 1ed4e349cf2..7e81b845664 100644 --- a/packages/react/src/internal/hooks/__tests__/useOverflowObserver.test.tsx +++ b/packages/react/src/internal/hooks/__tests__/useOverflowObserver.test.tsx @@ -75,6 +75,23 @@ describe('useIsClipped', () => { expect(MockIntersectionObserver.instances.every(o => !o.observed.has(item))).toBe(true) }) + it('waits for a fresh measurement after re-enabling a clipped item', () => { + vi.stubGlobal('IntersectionObserver', MockIntersectionObserver) + const {rerender} = render() + const item = page.getByTestId('item').element() + const observer = MockIntersectionObserver.instances.at(-1)! + observer.trigger([{target: item, isIntersecting: false, intersectionRatio: 0}]) + expect(item.getAttribute('data-overflowing')).toBe('true') + + rerender() + expect(item.getAttribute('data-overflowing')).toBe('false') + rerender() + expect(item.getAttribute('data-overflowing')).toBe('false') + + observer.trigger([{target: item, isIntersecting: false, intersectionRatio: 0}]) + expect(item.getAttribute('data-overflowing')).toBe('true') + }) + it('reflects overflow state from the shared root-scoped observer', () => { vi.stubGlobal('IntersectionObserver', MockIntersectionObserver) render() diff --git a/packages/react/src/internal/hooks/useOverflowObserver.ts b/packages/react/src/internal/hooks/useOverflowObserver.ts index 26cd32c3317..441e8a44ea2 100644 --- a/packages/react/src/internal/hooks/useOverflowObserver.ts +++ b/packages/react/src/internal/hooks/useOverflowObserver.ts @@ -37,7 +37,11 @@ export function useIsClipped(ref: RefObject, options?: {disa } } - return observe(element, updateOverflowState) + const unobserve = observe(element, updateOverflowState) + return () => { + unobserve() + isOverflowingRef.current = false + } }, [ref, observe, disabled], )