An open source design system that's fully customizable and agent ready
TypeScript
fix(useScrollOverflow): measure only while the container is rendered (#7518)
Christopher Chedeaufdb53f363b08
diff --git a/.changeset/scroll-overflow-hidden-subtree.md b/.changeset/scroll-overflow-hidden-subtree.mdnew file mode 100644index 0000000000..7513a97223--- /dev/null+++ b/.changeset/scroll-overflow-hidden-subtree.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `useScrollOverflow` (the strip of `TabList`, the scroller of `Carousel`) measures a resize, and its container at registration, only while the container is rendered. Inside a `display: none` ancestor or a `content-visibility: hidden` subtree the hook keeps its last state instead of reading layout, since a layout read there made the browser render the whole hidden subtree for the answer; the resize observation that comes with the reveal measures again, one frame after the reveal paints. A scroll is measured hidden or not, so a container script scrolled while hidden (a selected tab's reveal) is right at a reveal that brings no resize. Before, a hidden container reported no overflow.++@vjeuxdiff --git a/packages/core/src/hooks/useScrollOverflow.test.tsx b/packages/core/src/hooks/useScrollOverflow.test.tsxnew file mode 100644index 0000000000..d6e3667f2b--- /dev/null+++ b/packages/core/src/hooks/useScrollOverflow.test.tsx@@ -0,0 +1,222 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useScrollOverflow.test.tsx+ * @input Uses vitest, @testing-library/react, useScrollOverflow+ * @output Unit tests for the hook's measurement and its rendered-only gate+ * @position Testing; jsdom lays nothing out, so the scroll box is faked and+ * `checkVisibility` is stubbed per element.+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {act, renderHook} from '@testing-library/react';+import {useScrollOverflow} from './useScrollOverflow';++// jsdom has no ResizeObserver. This one hands the test the shared observer's+// callback so a resize can be delivered on demand; the registration-time+// measurement comes from `observeResize` itself.+let deliverResize: ((entries: ResizeObserverEntry[]) => void) | null = null;++class FakeResizeObserver implements ResizeObserver {+ constructor(callback: ResizeObserverCallback) {+ deliverResize = entries => callback(entries, this);+ }+ observe = vi.fn();+ unobserve = vi.fn();+ disconnect = vi.fn();+}++// The shared observer reads only `target` off an entry.+function resizeEntry(target: Element): ResizeObserverEntry {+ return {target} as unknown as ResizeObserverEntry;+}++type Reads = {scrollWidth: number; clientWidth: number; scrollLeft: number};++// Fakes an overflowing scroll box and counts every layout read on it.+function fakeScrollBox(+ el: HTMLElement,+ box: {scrollWidth: number; clientWidth: number; scrollLeft?: number},+): Reads {+ const reads: Reads = {scrollWidth: 0, clientWidth: 0, scrollLeft: 0};+ const values: Reads = {scrollLeft: 0, ...box};+ for (const name of Object.keys(reads) as (keyof Reads)[]) {+ Object.defineProperty(el, name, {+ configurable: true,+ get() {+ reads[name] += 1;+ return values[name];+ },+ });+ }+ return reads;+}++function totalReads(reads: Reads): number {+ return reads.scrollWidth + reads.clientWidth + reads.scrollLeft;+}++function stubRendered(el: HTMLElement, rendered: boolean | undefined) {+ Object.defineProperty(el, 'checkVisibility', {+ configurable: true,+ value: rendered === undefined ? undefined : () => rendered,+ });+}++beforeEach(() => {+ vi.stubGlobal('ResizeObserver', FakeResizeObserver);+});++afterEach(() => {+ vi.unstubAllGlobals();+ deliverResize = null;+});++describe('useScrollOverflow', () => {+ it('measures a rendered container when the ref attaches', () => {+ const el = document.createElement('div');+ const reads = fakeScrollBox(el, {scrollWidth: 600, clientWidth: 300});+ stubRendered(el, true);+ const {result, unmount} = renderHook(() => useScrollOverflow());++ act(() => {+ result.current.scrollRef(el);+ });++ expect(result.current.hasOverflow).toBe(true);+ expect(result.current.overflowStart).toBe(false);+ expect(result.current.overflowEnd).toBe(true);+ expect(totalReads(reads)).toBeGreaterThan(0);+ unmount();+ });++ it('reads no layout while the container is not rendered', () => {+ const el = document.createElement('div');+ const reads = fakeScrollBox(el, {scrollWidth: 600, clientWidth: 300});+ stubRendered(el, false);+ const {result, unmount} = renderHook(() => useScrollOverflow());++ act(() => {+ result.current.scrollRef(el);+ });+ // A resize delivered for the hidden box (a `display: none` or a+ // `content-visibility: hidden` ancestor reports a zero box) is skipped+ // too; a scroll is not (the next case).+ act(() => {+ deliverResize?.([resizeEntry(el)]);+ });++ expect(totalReads(reads)).toBe(0);+ expect(result.current.hasOverflow).toBe(false);+ expect(result.current.overflowEnd).toBe(false);+ unmount();+ });++ it('keeps the last state while hidden and measures again on the reveal', () => {+ const el = document.createElement('div');+ const reads = fakeScrollBox(el, {+ scrollWidth: 600,+ clientWidth: 300,+ scrollLeft: 150,+ });+ stubRendered(el, true);+ const {result, unmount} = renderHook(() => useScrollOverflow());++ act(() => {+ result.current.scrollRef(el);+ });+ expect(result.current.overflowStart).toBe(true);+ expect(result.current.overflowEnd).toBe(true);++ stubRendered(el, false);+ const readsBeforeHide = totalReads(reads);+ act(() => {+ deliverResize?.([resizeEntry(el)]);+ });+ expect(totalReads(reads)).toBe(readsBeforeHide);+ expect(result.current.overflowStart).toBe(true);+ expect(result.current.overflowEnd).toBe(true);++ // Revealed at the end edge with a new size: the resize that follows the+ // reveal measures (a reveal at the same size has no resize, and relies on+ // the scroll having been measured: the next case).+ stubRendered(el, true);+ fakeScrollBox(el, {scrollWidth: 600, clientWidth: 300, scrollLeft: 300});+ act(() => {+ deliverResize?.([resizeEntry(el)]);+ });+ expect(result.current.overflowStart).toBe(true);+ expect(result.current.overflowEnd).toBe(false);+ unmount();+ });++ it('measures a scroll while hidden, so a reveal at the same size is already right', () => {+ const el = document.createElement('div');+ fakeScrollBox(el, {scrollWidth: 600, clientWidth: 300});+ stubRendered(el, true);+ const {result, unmount} = renderHook(() => useScrollOverflow());++ act(() => {+ result.current.scrollRef(el);+ });+ expect(result.current.overflowStart).toBe(false);+ expect(result.current.overflowEnd).toBe(true);++ // Hidden, then scrolled by script to the end edge (a selected tab's+ // reveal under a hidden panel): the scroll is measured.+ stubRendered(el, false);+ const scrolled = fakeScrollBox(el, {+ scrollWidth: 600,+ clientWidth: 300,+ scrollLeft: 300,+ });+ act(() => {+ el.dispatchEvent(new Event('scroll'));+ });+ expect(totalReads(scrolled)).toBeGreaterThan(0);+ expect(result.current.overflowStart).toBe(true);+ expect(result.current.overflowEnd).toBe(false);++ // Revealed at the same size: no resize observation comes, and none is+ // needed.+ stubRendered(el, true);+ expect(result.current.overflowStart).toBe(true);+ expect(result.current.overflowEnd).toBe(false);+ unmount();+ });++ it('measures in a browser without checkVisibility', () => {+ const el = document.createElement('div');+ const reads = fakeScrollBox(el, {scrollWidth: 600, clientWidth: 300});+ stubRendered(el, undefined);+ const {result, unmount} = renderHook(() => useScrollOverflow());++ act(() => {+ result.current.scrollRef(el);+ });++ expect(result.current.hasOverflow).toBe(true);+ expect(totalReads(reads)).toBeGreaterThan(0);+ unmount();+ });++ it('follows a scroll on a rendered container', () => {+ const el = document.createElement('div');+ fakeScrollBox(el, {scrollWidth: 600, clientWidth: 300});+ stubRendered(el, true);+ const {result, unmount} = renderHook(() => useScrollOverflow());++ act(() => {+ result.current.scrollRef(el);+ });+ expect(result.current.overflowStart).toBe(false);++ fakeScrollBox(el, {scrollWidth: 600, clientWidth: 300, scrollLeft: 300});+ act(() => {+ el.dispatchEvent(new Event('scroll'));+ });+ expect(result.current.overflowStart).toBe(true);+ expect(result.current.overflowEnd).toBe(false);+ unmount();+ });+});diff --git a/packages/core/src/hooks/useScrollOverflow.ts b/packages/core/src/hooks/useScrollOverflow.tsindex 0f79e82407..e4e2d1867c 100644--- a/packages/core/src/hooks/useScrollOverflow.ts+++ b/packages/core/src/hooks/useScrollOverflow.ts@@ -6,10 +6,22 @@* @file useScrollOverflow.ts* @input Uses React useRef, useState, useCallback, useEffect* @output Exports useScrollOverflow hook for tracking scroll position edges- * @position Core hook; used by Carousel for fade-edge and button state+ * @position Core hook; used by Carousel and TabList for fade-edge and button+ * state** Observes a scroll container and reports whether content overflows at the- * start, end, or both edges. Updates on scroll and resize.+ * start, end, or both edges. Updates on every scroll, and on a resize while+ * the container is rendered: a layout read on an element the browser is not+ * rendering (an ancestor with `display: none`, or a `content-visibility:+ * hidden` subtree) either answers zeros or makes the browser lay out that+ * whole hidden subtree for the answer, so a resize observation delivered for+ * a hidden container, and the measurement at registration inside one, are+ * skipped; the hook keeps its last state until the resize observation that+ * follows the reveal (one frame after it paints). A scroll is measured+ * whether or not the container is rendered: a scroll of a hidden container+ * is script's (a selected tab revealed under a hidden panel), its layout is+ * already the scroll's, and a reveal at the same size brings no resize to+ * measure it with.** SYNC: When modified, update:* - /packages/core/src/hooks/index.ts@@ -27,6 +39,19 @@ export interface ScrollOverflowState {hasOverflow: boolean;}+/**+ * Whether the browser is rendering `el`, so a layout read on it answers for a+ * real box. `checkVisibility()` is false under a `display: none` ancestor and+ * inside a `content-visibility: hidden` subtree, and it answers without+ * rendering that subtree. Not `contentVisibilityAuto`: a freshly inserted,+ * on-screen `content-visibility: auto` section counts as skipped until the+ * next rendering update, and a strip mounted into one would paint its first+ * frame unmeasured. A browser without `checkVisibility` measures as before.+ */+function isRendered(el: HTMLElement): boolean {+ return typeof el.checkVisibility !== 'function' || el.checkVisibility();+}+/*** Tracks scroll overflow state for a horizontally scrollable container.*@@ -49,12 +74,7 @@ export function useScrollOverflow() {hasOverflow: false,});- const measure = useCallback(() => {- const el = elRef.current;- if (!el) {- return;- }-+ const measureNow = useCallback((el: HTMLElement) => {const tolerance = 1;const {scrollLeft, scrollWidth, clientWidth} = el;const maxScroll = scrollWidth - clientWidth;@@ -75,22 +95,44 @@ export function useScrollOverflow() {});}, []);+ // Registration and resize: only a rendered container. A hidden one has no+ // edges to report, and reading its layout would make the browser render+ // the hidden subtree it sits in; the resize observation that follows the+ // reveal measures again.+ const measure = useCallback(() => {+ const el = elRef.current;+ if (el && isRendered(el)) {+ measureNow(el);+ }+ }, [measureNow]);++ // A scroll: measured hidden or not. Script scrolled the hidden container+ // (its layout is already the scroll's), and a reveal at the same size+ // brings no resize observation, so this is the read that keeps the edges+ // right for it.+ const measureOnScroll = useCallback(() => {+ const el = elRef.current;+ if (el) {+ measureNow(el);+ }+ }, [measureNow]);+const scrollRef = useCallback((el: HTMLElement | null) => {if (elRef.current) {unobserveRef.current?.();unobserveRef.current = null;- elRef.current.removeEventListener('scroll', measure);+ elRef.current.removeEventListener('scroll', measureOnScroll);}elRef.current = el;if (el) {- el.addEventListener('scroll', measure, {passive: true});+ el.addEventListener('scroll', measureOnScroll, {passive: true});unobserveRef.current = observeResize(el, measure);}},- [measure],+ [measure, measureOnScroll],);useEffect(() => {@@ -98,10 +140,10 @@ export function useScrollOverflow() {if (elRef.current) {unobserveRef.current?.();unobserveRef.current = null;- elRef.current.removeEventListener('scroll', measure);+ elRef.current.removeEventListener('scroll', measureOnScroll);}};- }, [measure]);+ }, [measureOnScroll]);return {scrollRef,