Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

perf(useScrollableArea): a scroll updates the edges from geometry, without reading computed style (#8041)

Christopher Chedeau72cd1b182d98
diff --git a/.changeset/scroll-edges-without-style-reads.md b/.changeset/scroll-edges-without-style-reads.md
new file mode 100644
index 0000000000..be07c46378
--- /dev/null
+++ b/.changeset/scroll-edges-without-style-reads.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[perf] Scrolling a `ScrollableArea`, or any viewport that uses `useScrollableArea` (Table, CodeBlock, BottomSheet's body), no longer reads computed style on each frame. Before, every scroll event triggered a full measurement in the next animation frame: four computed-style reads plus geometry. When something else on the page had changed style earlier in that frame, this forced a style recalculation from script. Now the scroll event works out the logical edges from box geometry alone, with no computed style and no frame request. Size, style and writing-mode changes still trigger a full measurement, at most once per frame, and so does a scroll whose offset the measured writing direction rules out (a direction changed by a stylesheet alone).
+
+@vjeux
diff --git a/packages/core/src/hooks/scrollGeometry.ts b/packages/core/src/hooks/scrollGeometry.ts
index 724f73a6e0..8b24b6961b 100644
--- a/packages/core/src/hooks/scrollGeometry.ts
+++ b/packages/core/src/hooks/scrollGeometry.ts
@@ -141,15 +141,82 @@ export function measureLogicalScrollAxis(
return INACTIVE_AXIS_STATE;
}
- const isReversed = mapping[`${logicalAxis}Reversed`];
+ return {
+ isScrollable: true,
+ ...logicalEdges(
+ metrics.offset,
+ maxOffset,
+ mapping[`${logicalAxis}Reversed`],
+ ),
+ };
+}
+
+function logicalEdges(
+ offset: number,
+ maxOffset: number,
+ isReversed: boolean,
+): {atStart: boolean; atEnd: boolean} {
const logicalOffset = Math.min(
maxOffset,
- Math.max(0, isReversed ? Math.abs(metrics.offset) : metrics.offset),
+ Math.max(0, isReversed ? Math.abs(offset) : offset),
);
-
return {
- isScrollable: true,
atStart: logicalOffset <= SCROLL_OVERFLOW_TOLERANCE,
atEnd: logicalOffset >= maxOffset - SCROLL_OVERFLOW_TOLERANCE,
};
}
+
+/** Where a scroll left one logical axis, read from geometry alone. */
+export interface LogicalScrollPosition {
+ /** Content exceeds the viewport by more than the shared tolerance. */
+ overflows: boolean;
+ atStart: boolean;
+ atEnd: boolean;
+ /**
+ * The offset's sign contradicts the mapping: negative on an axis the
+ * mapping reads forward, or positive on one it reads reversed. The writing
+ * mode or direction changed without the last full measurement seeing it
+ * (a stylesheet alone, for one), so the mapping is stale.
+ */
+ contradictsMapping: boolean;
+}
+
+/**
+ * Reads one logical axis after a scroll without reading computed style.
+ *
+ * A scroll moves the offset and nothing else: the writing-mode mapping and
+ * whether the computed overflow can scroll are the ones the last full
+ * measurement read, so the caller passes that mapping in. Only box geometry
+ * is read here, which costs nothing while layout is clean, as it is during a
+ * scroll; a computed-style read would force a style recalculation on every
+ * frame of the scroll whenever anything else on the page has dirtied style.
+ *
+ * Returns null when the viewport is disconnected or has no box (the caller
+ * keeps its last valid state, as a full measurement does).
+ */
+export function measureLogicalScrollPosition(
+ element: HTMLElement,
+ logicalAxis: LogicalScrollAxis,
+ mapping: LogicalAxisMapping,
+): LogicalScrollPosition | null {
+ if (
+ !element.isConnected ||
+ element.clientWidth <= 0 ||
+ element.clientHeight <= 0
+ ) {
+ return null;
+ }
+ const isX = mapping[logicalAxis] === 'x';
+ const isReversed = mapping[`${logicalAxis}Reversed`];
+ const offset = isX ? element.scrollLeft : element.scrollTop;
+ const maxOffset = isX
+ ? element.scrollWidth - element.clientWidth
+ : element.scrollHeight - element.clientHeight;
+ return {
+ overflows: maxOffset > SCROLL_OVERFLOW_TOLERANCE,
+ ...logicalEdges(offset, maxOffset, isReversed),
+ contradictsMapping: isReversed
+ ? offset > SCROLL_OVERFLOW_TOLERANCE
+ : offset < -SCROLL_OVERFLOW_TOLERANCE,
+ };
+}
diff --git a/packages/core/src/hooks/useScrollableArea.test.tsx b/packages/core/src/hooks/useScrollableArea.test.tsx
index df29307d7f..48408dabaf 100644
--- a/packages/core/src/hooks/useScrollableArea.test.tsx
+++ b/packages/core/src/hooks/useScrollableArea.test.tsx
@@ -147,9 +147,12 @@ function mockOwnedComputedStyle(
describe('useScrollableArea', () => {
let frames: FrameRequestCallback[];
+ // A computed `direction` set by a stylesheet alone: no attribute changes.
+ let stylesheetDirection: string | null;
beforeEach(() => {
frames = [];
+ stylesheetDirection = null;
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((callback: FrameRequestCallback) => {
@@ -176,6 +179,9 @@ describe('useScrollableArea', () => {
if (element instanceof HTMLElement && property === 'overflowY') {
return element.style.overflowY || 'auto';
}
+ if (property === 'direction' && stylesheetDirection != null) {
+ return stylesheetDirection;
+ }
return Reflect.get(target, property, target);
},
});
@@ -411,7 +417,7 @@ describe('useScrollableArea', () => {
expect(viewport).toHaveAttribute('tabindex', '0');
});
- it('requires scroll-capable computed overflow and more than 1px excess geometry', () => {
+ it('requires scroll-capable computed overflow and more than 1px excess geometry', async () => {
render(<Fixture />);
const viewport = screen.getByTestId('viewport');
makeMeasurable(viewport);
@@ -427,8 +433,11 @@ describe('useScrollableArea', () => {
flushFrame();
expect(state().inline.isScrollable).toBe(false);
- viewport.style.overflowX = 'auto';
- void act(() => viewport.dispatchEvent(new Event('scroll')));
+ // A style change with no geometry change reaches the hook through its
+ // attribute observer; a scroll only ever moves the offset.
+ await act(async () => {
+ viewport.style.overflowX = 'auto';
+ });
flushFrame();
expect(state().inline).toEqual({
isScrollable: true,
@@ -471,6 +480,179 @@ describe('useScrollableArea', () => {
});
});
+ it('derives edges as a scroll is dispatched, without reading computed style or requesting a frame', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setGeometry(viewport, {scrollWidth: 300});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(state().inline.isScrollable).toBe(true);
+
+ const styleReads = vi.mocked(window.getComputedStyle).mock.calls.length;
+ const steps: [number, {atStart: boolean; atEnd: boolean}][] = [
+ [80, {atStart: false, atEnd: false}],
+ [200, {atStart: false, atEnd: true}],
+ [0, {atStart: true, atEnd: false}],
+ ];
+ for (const [scrollLeft, edges] of steps) {
+ setGeometry(viewport, {scrollLeft});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ expect(frames).toHaveLength(0);
+ expect(state().inline).toEqual({isScrollable: true, ...edges});
+ }
+ expect(vi.mocked(window.getComputedStyle).mock.calls).toHaveLength(
+ styleReads,
+ );
+ });
+
+ it('leaves a scroll to the full measurement already pending in its frame', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ const content = screen.getByTestId('content');
+ makeMeasurable(viewport);
+ setGeometry(viewport, {scrollWidth: 300});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+
+ void act(() => content.dispatchEvent(new Event('transitionend')));
+ expect(frames).toHaveLength(1);
+ setGeometry(viewport, {scrollLeft: 80});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ expect(frames).toHaveLength(1);
+ expect(state().inline.atStart).toBe(true);
+
+ flushFrame();
+ expect(state().inline).toEqual({
+ isScrollable: true,
+ atStart: false,
+ atEnd: false,
+ });
+ });
+
+ it('measures fully when a scroll finds the requested overflow gone', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setGeometry(viewport, {scrollWidth: 300, scrollLeft: 80});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(viewport).toHaveAttribute('tabindex', '0');
+
+ // Content shrinking clamps the offset, which the browser reports as a
+ // scroll: a change the offset cannot explain, measured in full.
+ setGeometry(viewport, {scrollWidth: 100, scrollLeft: 0});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ expect(frames).toHaveLength(1);
+ flushFrame();
+ expect(state().inline).toEqual({
+ isScrollable: false,
+ atStart: true,
+ atEnd: true,
+ });
+ expect(viewport).not.toHaveAttribute('tabindex');
+ });
+
+ it('keeps the last valid edges when a scroll arrives while the viewport has no box', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setGeometry(viewport, {scrollWidth: 300, scrollLeft: 80});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+
+ // At offset 0 a zero-size box would report the start edge, so this step
+ // fails if the zero-size guard is removed.
+ setGeometry(viewport, {clientWidth: 0, clientHeight: 0, scrollLeft: 0});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(state().inline).toEqual({
+ isScrollable: true,
+ atStart: false,
+ atEnd: false,
+ });
+ });
+
+ it('applies the measured writing direction on the scroll path', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ viewport.dir = 'rtl';
+ setGeometry(viewport, {scrollWidth: 300});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(state().inline).toEqual({
+ isScrollable: true,
+ atStart: true,
+ atEnd: false,
+ });
+
+ const styleReads = vi.mocked(window.getComputedStyle).mock.calls.length;
+ setGeometry(viewport, {scrollLeft: -200});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(state().inline).toEqual({
+ isScrollable: true,
+ atStart: false,
+ atEnd: true,
+ });
+ expect(vi.mocked(window.getComputedStyle).mock.calls).toHaveLength(
+ styleReads,
+ );
+ });
+
+ it('derives vertical-rl block edges on the scroll path without requesting a frame', () => {
+ render(<Fixture axis="block" />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ viewport.style.writingMode = 'vertical-rl';
+ setGeometry(viewport, {scrollWidth: 220});
+ void act(() => viewport.dispatchEvent(new Event('transitionend')));
+ flushFrame();
+ expect(state().block).toEqual({
+ isScrollable: true,
+ atStart: true,
+ atEnd: false,
+ });
+
+ // The block axis runs right to left along x: its end is scrollLeft -120.
+ setGeometry(viewport, {scrollLeft: -120});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ expect(frames).toHaveLength(0);
+ expect(state().block).toEqual({
+ isScrollable: true,
+ atStart: false,
+ atEnd: true,
+ });
+ });
+
+ it('measures fully when a scroll offset contradicts the measured direction', () => {
+ render(<Fixture />);
+ const viewport = screen.getByTestId('viewport');
+ makeMeasurable(viewport);
+ setGeometry(viewport, {scrollWidth: 300});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ flushFrame();
+ expect(state().inline).toEqual({
+ isScrollable: true,
+ atStart: true,
+ atEnd: false,
+ });
+
+ // A stylesheet alone turns the area RTL, so nothing re-measured; the
+ // next scroll reports a negative offset the stored mapping rules out.
+ stylesheetDirection = 'rtl';
+ setGeometry(viewport, {scrollLeft: -200});
+ void act(() => viewport.dispatchEvent(new Event('scroll')));
+ expect(frames).toHaveLength(1);
+ flushFrame();
+ expect(state().inline).toEqual({
+ isScrollable: true,
+ atStart: false,
+ atEnd: true,
+ });
+ });
+
it('normalizes RTL inline offsets to logical edges', () => {
render(<Fixture />);
const viewport = screen.getByTestId('viewport');
diff --git a/packages/core/src/hooks/useScrollableArea.ts b/packages/core/src/hooks/useScrollableArea.ts
index e3803e8fc9..8c0f9789d2 100644
--- a/packages/core/src/hooks/useScrollableArea.ts
+++ b/packages/core/src/hooks/useScrollableArea.ts
@@ -8,6 +8,11 @@
* @output Safe prop getters, native keyboard entry, and stable per-axis effective scroll state
* @position Canonical behavior core for ScrollableArea and structure-owning adopters
*
+ * Geometry and style signals coalesce into one full measurement per frame. A
+ * scroll only moves the offset, so its event re-derives the logical edges
+ * from box geometry: no computed-style read and no extra frame while the
+ * user scrolls.
+ *
* SYNC: When modified, update:
* - /packages/core/src/hooks/useScrollableArea.doc.mjs
* - /packages/core/src/hooks/useScrollableArea.test.tsx
@@ -35,6 +40,7 @@ import {
getLogicalAxisMapping,
measureLogicalOverflowGeometry,
measureLogicalScrollAxis,
+ measureLogicalScrollPosition,
type LogicalAxisMapping,
type LogicalOverflowGeometry,
} from './scrollGeometry';
@@ -106,6 +112,7 @@ const INITIAL_MAPPING: LogicalAxisMapping = {
inlineReversed: false,
blockReversed: false,
};
+const LOGICAL_AXES = ['inline', 'block'] as const;
const styles = stylex.create({
overflow: (
@@ -218,6 +225,18 @@ export function useScrollableArea({
let frame: number | null = null;
let isActive = true;
+ // What the last full measurement read from computed style and geometry.
+ // A scroll changes neither, so the scroll path reuses them.
+ let measuredMapping = INITIAL_MAPPING;
+ let measuredOverflow = INITIAL_OVERFLOW;
+
+ const publish = (nextState: ScrollableAreaState) => {
+ stateRef.current = nextState;
+ registerScrollOwner(viewport, nextState);
+ setMeasured(current =>
+ statesEqual(current, nextState) ? current : nextState,
+ );
+ };
// Measures now; `measure` is the frame callback that also clears the
// pending frame. The same-commit remeasure below calls this one, so a frame
@@ -257,17 +276,15 @@ export function useScrollableArea({
block: blockOverflow,
};
const nextState = {inline, block};
- stateRef.current = nextState;
- registerScrollOwner(viewport, nextState);
+ measuredMapping = nextMapping;
+ measuredOverflow = nextOverflow;
// Measured DOM geometry decides whether the viewport becomes a CSS
// scroll container.
setOverflow(current =>
overflowEqual(current, nextOverflow) ? current : nextOverflow,
);
// The measured DOM state is the hook's output.
- setMeasured(current =>
- statesEqual(current, nextState) ? current : nextState,
- );
+ publish(nextState);
// A writing-mode change remaps the behavior-owned physical CSS.
setMapping(current =>
mappingsEqual(current, nextMapping) ? current : nextMapping,
@@ -286,13 +303,70 @@ export function useScrollableArea({
frame = window.requestAnimationFrame(measure);
};
+ // A scroll moves the offset and nothing else, so it only re-derives the
+ // logical edges, from box geometry, as the scroll event is dispatched.
+ // Browsers fire it at most once per frame, before animation-frame
+ // callbacks, when style and layout are normally still clean from the last
+ // frame: no computed style is read, no frame is requested, and the edges
+ // are current in the frame that moved. Anything a scroll cannot explain
+ // (overflow appearing or going away on a requested axis, or an offset
+ // whose sign the measured writing direction rules out) schedules the
+ // full measurement, as every other invalidation does.
+ const onScroll = () => {
+ if (!isActive || frame != null) {
+ // A full measurement is already pending for this frame.
+ return;
+ }
+ const current = stateRef.current;
+ let next = current;
+ for (const logicalAxis of LOGICAL_AXES) {
+ if (!axisIsRequested(axis, logicalAxis)) {
+ continue;
+ }
+ const position = measureLogicalScrollPosition(
+ viewport,
+ logicalAxis,
+ measuredMapping,
+ );
+ if (position == null) {
+ return;
+ }
+ if (
+ position.overflows !== measuredOverflow[logicalAxis] ||
+ position.contradictsMapping
+ ) {
+ scheduleMeasure();
+ return;
+ }
+ const axisState = current[logicalAxis];
+ if (
+ !axisState.isScrollable ||
+ (axisState.atStart === position.atStart &&
+ axisState.atEnd === position.atEnd)
+ ) {
+ continue;
+ }
+ next = {
+ ...next,
+ [logicalAxis]: {
+ isScrollable: true,
+ atStart: position.atStart,
+ atEnd: position.atEnd,
+ },
+ };
+ }
+ if (next !== current) {
+ publish(next);
+ }
+ };
+
registerScrollOwner(viewport, stateRef.current);
measureRef.current = measureNow;
measure();
const stopObservingViewport = observeResize(viewport, scheduleMeasure);
const stopObservingContent = observeResize(content, scheduleMeasure);
- viewport.addEventListener('scroll', scheduleMeasure, {passive: true});
+ viewport.addEventListener('scroll', onScroll, {passive: true});
window.addEventListener('resize', scheduleMeasure);
window.visualViewport?.addEventListener('resize', scheduleMeasure);
content.addEventListener('load', scheduleMeasure, true);
@@ -338,7 +412,7 @@ export function useScrollableArea({
stopObservingViewport();
stopObservingContent();
mutationObserver?.disconnect();
- viewport.removeEventListener('scroll', scheduleMeasure);
+ viewport.removeEventListener('scroll', onScroll);
window.removeEventListener('resize', scheduleMeasure);
window.visualViewport?.removeEventListener('resize', scheduleMeasure);
content.removeEventListener('load', scheduleMeasure, true);