An open source design system that's fully customizable and agent ready
TypeScript
fix(useScrollableArea): an ancestor's transform no longer measures the scroll area again on every frame of a drag (#10034)
Xinzi Zhou74cb73c9fb64
diff --git a/.changeset/scrollable-area-ancestor-style.md b/.changeset/scrollable-area-ancestor-style.mdnew file mode 100644index 0000000000..0a83e4eb5e--- /dev/null+++ b/.changeset/scrollable-area-ancestor-style.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] useScrollableArea: an ancestor's inline `style` change measures the scroll area again only when it changes the axis mapping or the boxes' existence (`direction`, `writing-mode`, `display`, `visibility`, `content-visibility`); a size change still reaches it through the resize observers. A BottomSheet writes its transform, and its scrim's custom property, on every input sample of a drag, and each write forced a full measurement (its computed-style reads and the scroll geometry) in the next frame, a style recalculation and a layout on every frame of the drag.++@imdreamrunnerdiff --git a/packages/core/src/hooks/useScrollableArea.test.tsx b/packages/core/src/hooks/useScrollableArea.test.tsxindex 0edb34faed..e0b06a8e44 100644--- a/packages/core/src/hooks/useScrollableArea.test.tsx+++ b/packages/core/src/hooks/useScrollableArea.test.tsx@@ -150,10 +150,13 @@ describe('useScrollableArea', () => {let frames: FrameRequestCallback[];// A computed `direction` set by a stylesheet alone: no attribute changes.let stylesheetDirection: string | null;+ // The callbacks handed to ResizeObserver, to report a resize from a test.+ let resizeObservers: ResizeObserverCallback[];beforeEach(() => {frames = [];stylesheetDirection = null;+ resizeObservers = [];vi.stubGlobal('requestAnimationFrame',vi.fn((callback: FrameRequestCallback) => {@@ -164,7 +167,8 @@ describe('useScrollableArea', () => {vi.stubGlobal('cancelAnimationFrame', vi.fn());vi.stubGlobal('ResizeObserver',- vi.fn(function () {+ vi.fn(function (callback: ResizeObserverCallback) {+ resizeObservers.push(callback);return {observe: vi.fn(), unobserve: vi.fn(), disconnect: vi.fn()};}),);@@ -331,6 +335,57 @@ describe('useScrollableArea', () => {expect(pending.size).toBe(0);});+ it('leaves an ancestor that moves on the compositor alone, and measures on its direction and its size', async () => {+ mockOwnedComputedStyle();+ render(<Fixture axis="block" />);+ const viewport = screen.getByTestId('viewport');+ const ancestor = viewport.parentElement!;+ // Let the mount's own style writes reach the observer, and settle.+ await act(async () => {});+ flushFrame();+ await act(async () => {});+ flushFrame();+ const framesBefore = frames.length;+ const styleReads = vi.mocked(window.getComputedStyle).mock.calls.length;++ // A surface dragged under a finger writes its transform, and a custom+ // property for its scrim, on every input sample.+ for (const offset of [8, 16, 24]) {+ await act(async () => {+ ancestor.style.transform = `translateY(${offset}px)`;+ ancestor.style.setProperty('--_scrim-opacity', `${1 - offset / 100}`);+ });+ }+ expect(frames.length).toBe(framesBefore);+ expect(vi.mocked(window.getComputedStyle).mock.calls).toHaveLength(+ styleReads,+ );++ // The axis mapping is the ancestor's to change.+ await act(async () => {+ ancestor.style.direction = 'rtl';+ });+ expect(frames.length).toBe(framesBefore + 1);+ flushFrame();++ // A size change reaches the hook through its resize observer, whatever+ // ancestor style caused it.+ const framesBeforeResize = frames.length;+ act(() => {+ for (const callback of resizeObservers) {+ callback(+ [+ {+ target: viewport,+ } as Partial<ResizeObserverEntry> as ResizeObserverEntry,+ ],+ {} as ResizeObserver,+ );+ }+ });+ expect(frames.length).toBe(framesBeforeResize + 1);+ });+it('keeps the tab stop through a writing-mode change that moves the overflowing axis', async () => {let isVertical = false;mockOwnedComputedStyle(() =>diff --git a/packages/core/src/hooks/useScrollableArea.ts b/packages/core/src/hooks/useScrollableArea.tsindex 71b365a4a9..5f047fea2a 100644--- a/packages/core/src/hooks/useScrollableArea.ts+++ b/packages/core/src/hooks/useScrollableArea.ts@@ -120,6 +120,52 @@ const styles = stylex.create({) => ({overflowX, overflowY}),});+/**+ * The inline declarations of an ancestor that change what the hook measures+ * without changing a box: the axis mapping, and whether the boxes exist. A+ * size change reaches the hook through the resize observers whatever caused+ * it.+ */+const ANCESTOR_STYLE_PROPERTIES = [+ 'direction',+ 'writing-mode',+ 'display',+ 'visibility',+ 'content-visibility',+] as const;++function inlineDeclaration(+ cssText: string | null,+ property: string,+): string | null {+ if (cssText == null || !cssText.includes(property)) {+ return null;+ }+ const match = new RegExp(`(?:^|;)\\s*${property}\\s*:\\s*([^;]*)`, 'i').exec(+ cssText,+ );+ return match == null ? null : match[1].trim();+}++/**+ * Whether an ancestor's `style` attribute changed a declaration the+ * measurement depends on (ANCESTOR_STYLE_PROPERTIES), between its old and new+ * text.+ */+function inlineStyleChangesMapping(+ before: string | null,+ after: string | null,+): boolean {+ if (before === after) {+ return false;+ }+ return ANCESTOR_STYLE_PROPERTIES.some(+ property =>+ inlineDeclaration(before, property) !==+ inlineDeclaration(after, property),+ );+}+function axisIsRequested(requested: ScrollAxis, axis: 'inline' | 'block') {return requested === axis || requested === 'both';}@@ -376,12 +422,39 @@ export function useScrollableArea({hasLayoutInvalidation = true;scheduleContentMeasure();};+ // An ancestor's inline style reaches the measurement two ways: through the+ // viewport's or the content's box, which the resize observers report, or+ // through the axis mapping and the boxes' existence. So an ancestor's+ // `style` mutation counts only when one of those declarations changed.+ // A surface that moves under a finger writes its transform on every input+ // sample; measuring on each of those forced a style recalculation and a+ // layout every frame of the drag.+ const isUnmappedAncestorStyle = (record: MutationRecord) => {+ const target = record.target;+ return (+ record.type === 'attributes' &&+ record.attributeName === 'style' &&+ target instanceof Element &&+ !viewport.contains(target) &&+ !content.contains(target) &&+ !inlineStyleChangesMapping(+ record.oldValue,+ target.getAttribute('style'),+ )+ );+ };// A change below the content root, such as a mounted row, is content// only. A change to the content root, the viewport or an ancestor can// change how mounted content fits.const onMutations = (records: MutationRecord[]) => {+ const counted = records.filter(+ record => !isUnmappedAncestorStyle(record),+ );+ if (counted.length === 0) {+ return;+ }if (- records.some(+ counted.some(record =>record.target === content || !content.contains(record.target),)@@ -431,6 +504,7 @@ export function useScrollableArea({mutationObserver?.observe(ancestor, {attributes: true,attributeFilter: ['class', 'dir', 'hidden', 'style'],+ attributeOldValue: true,});ancestor = ancestor.parentElement;}