Skip to content

Commit 6b4ecb5

Browse files
perf(core): the scroll hooks, TabList and SegmentedControl read no layout as they mount (#13387)
* perf(core): the scroll hooks, TabList and SegmentedControl read no layout as they mount useScrollableArea measured in its mount layout effect and read document.fonts.ready, which updates style and layout in Chromium. useScrollOverflow measured from the shared resize observer's registration call, once for the strip and once for each child. TabList revealed its selected tab from its mount effects. SegmentedControl attached its lens animators as it mounted, and the ::after animator then held its resting opacity with a new animation, which resolves style. Each read forced a style and layout pass on the new page before the browser's own. Both hooks now take their first measurement at the first resize notification, which comes after the browser's layout (observeResizeAfterLayout). Until then no other signal reads layout in useScrollableArea, and the fonts.ready read goes; the loadingdone listener still catches a late font. TabList reveals its selected tab at that notification, before the frame paints. SegmentedControl attaches its animators at the first selection change or press. Where no ResizeObserver exists, each one measures at once, as before. So a Table without plugins, a TabList and a SegmentedControl read no layout in the commit that mounts them. The column-resize and sticky-columns plugins and the windowed table's geometry subscription still read as they mount. useScrollOverflow takes that first measurement in a microtask after the notification's delivery and commits it at once. The microtask runs before the frame paints and after every callback of the delivery, so it reads the offset that TabList's reveal leaves. TabList registers its wrapper for that reveal in a layout effect, in the commit that attaches the strip. The two first notifications then come in one delivery, also when the frame comes before the mount's passive effects. TabList's and Carousel's edge fades and arrows show from the first frame. Carousel's scroll buttons take that first state without their opacity transition. The frame's style already holds them hidden when the measurement lands, so a fade would paint the first frames without them. Later edge changes fade as before. The first result of useScrollableArea can switch the viewport to overflow auto, and a classic scrollbar then resizes the observed viewport inside the delivery. So that result renders on React's own schedule: the scroll state, tab stop and edge fade of an area that overflows as it mounts arrive one frame later. Lab's Schedule time grid opened from that state. It now keeps its viewport a scroll container from the first frame and opens from one read in its mount layout effect, with no observer of its own. That offset reads the wall clock, because the clock store's first snapshot can be older than the mount. Fixes #12251 * Merge main into perf/12251-mount-reads-no-layout Co-authored-by: Sufiyan-MSA <Sufiyan-MSA@users.noreply.github.com> Co-authored-by: Cindy Zhang <cindyxz@meta.com>
1 parent 947e7b7 commit 6b4ecb5

15 files changed

Lines changed: 1095 additions & 106 deletions
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[perf] `useScrollableArea` and `useScrollOverflow` take their first measurement at the browser's first resize notification after layout, so a `Table` without plugins, a `TabList` and a `SegmentedControl` read no layout or computed style in the commit that mounts them. A `Table` with column resizing, sticky columns or windowing still measures as it mounts. `useScrollableArea` (Table, ScrollableArea, CodeBlock, Tokenizer and BottomSheet) also no longer reads `document.fonts.ready`, which updates style and layout in Chromium. TabList reveals its selected tab at that notification, before the frame paints. SegmentedControl attaches its selection animators at the first selection change or press. `useScrollOverflow` (TabList and Carousel) commits that first measurement before the frame paints, so the edge fades and scroll arrows show from the first frame, at the offset TabList's reveal leaves. Carousel's scroll buttons take that first state without their fade. With `useScrollableArea`, the scroll state, tab stop and edge fade of an area that overflows as it mounts arrive one frame later. A test that stubs `ResizeObserver` delivers that notification, and awaits a microtask for `useScrollOverflow`, before it checks them; where no `ResizeObserver` exists, the first measurement happens at once, as before.
6+
7+
@Sufiyan-MSA

‎packages/core/src/Carousel/Carousel.test.tsx‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,69 @@ describe('Carousel', () => {
349349
expect(right.closest('[inert]')).not.toBeNull();
350350
});
351351

352+
it('shows a scroll button from the first measurement without its fade, and fades the later changes', async () => {
353+
render(
354+
<Carousel aria-label="Photos">
355+
<div>Item 1</div>
356+
<div>Item 2</div>
357+
</Carousel>,
358+
);
359+
const scroller = screen.getByRole('group', {name: 'Photos'});
360+
// A 200 px scroll area over 500 px of slides.
361+
let scrollLeft = 0;
362+
Object.defineProperty(scroller, 'scrollWidth', {
363+
value: 500,
364+
configurable: true,
365+
});
366+
Object.defineProperty(scroller, 'clientWidth', {
367+
value: 200,
368+
configurable: true,
369+
});
370+
Object.defineProperty(scroller, 'scrollLeft', {
371+
get: () => scrollLeft,
372+
configurable: true,
373+
});
374+
const pillOf = (label: string) => {
375+
const pill = screen.getByLabelText(label).closest('[inert]');
376+
if (!(pill instanceof HTMLElement)) {
377+
throw new Error(`no hidden pill around "${label}"`);
378+
}
379+
return pill;
380+
};
381+
const start = pillOf('Scroll left');
382+
const end = pillOf('Scroll right');
383+
// The mount renders both pills hidden, and the first frame styles that.
384+
expect(getComputedStyle(end).opacity).toBe('0');
385+
386+
// The browser's first notification after layout. Its result commits in
387+
// a microtask, before the frame paints.
388+
const observer = MockResizeObserver.last;
389+
await act(async () => {
390+
observer?.callback(
391+
[{target: scroller} as unknown as ResizeObserverEntry],
392+
observer,
393+
);
394+
});
395+
expect(getComputedStyle(end).opacity).toBe('1');
396+
expect(getComputedStyle(end).transitionProperty).toBe('none');
397+
// Its button leaves the disabled state at once too, and keeps the rest.
398+
const endButton = screen.getByLabelText('Scroll right');
399+
expect(getComputedStyle(endButton).transitionProperty).not.toContain(
400+
'opacity',
401+
);
402+
expect(getComputedStyle(endButton).transitionProperty).toContain(
403+
'transform',
404+
);
405+
406+
// A scroll changes the edges that a frame has shown: the pills fade.
407+
scrollLeft = 150;
408+
fireEvent.scroll(scroller);
409+
expect(getComputedStyle(start).opacity).toBe('1');
410+
expect(getComputedStyle(start).transitionProperty).toBe('opacity');
411+
expect(getComputedStyle(end).transitionProperty).toBe('opacity');
412+
expect(getComputedStyle(endButton).transitionProperty).toContain('opacity');
413+
});
414+
352415
describe('Shift + wheel horizontal scroll', () => {
353416
// jsdom doesn't lay out elements, so we fake an overflowing scroll
354417
// container and capture scrollBy calls.

‎packages/core/src/Carousel/Carousel.tsx‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,16 @@ const styles = stylex.create({
262262
opacity: 0,
263263
pointerEvents: 'none' as const,
264264
},
265+
// The first measurement's edges replace none that a frame showed. A pill
266+
// takes them at once: a fade would paint the first frame without it.
267+
buttonPillUnfaded: {
268+
transitionProperty: 'none',
269+
},
270+
// Its button leaves the disabled state at once too. A hover and a press
271+
// keep their transitions.
272+
buttonUnfaded: {
273+
transitionProperty: 'background-image, background-color, color, transform',
274+
},
265275
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion, @typescript-eslint/consistent-type-assertions -- CSS custom property requires type widening for StyleX
266276
buttonRadiusOverride: {
267277
'--_button-radius': radiusVars['--radius-full'],
@@ -421,8 +431,14 @@ export function Carousel({
421431
// transition it is allowed to act on.
422432
const focusedNavRef = useRef<'start' | 'end' | null>(null);
423433
const prevCanScrollRef = useRef<{start: boolean; end: boolean} | null>(null);
424-
const {scrollRef, followShown, overflowStart, overflowEnd, hasOverflow} =
425-
useShownScrollOverflow();
434+
const {
435+
scrollRef,
436+
followShown,
437+
overflowStart,
438+
overflowEnd,
439+
hasOverflow,
440+
isFirstMeasurement,
441+
} = useShownScrollOverflow();
426442

427443
// Children.toArray drops null/undefined/boolean children and assigns
428444
// stable keys, so slide numbering ("Slide N of M") matches what actually
@@ -801,6 +817,7 @@ export function Carousel({
801817
{...stylex.props(
802818
styles.buttonPill,
803819
styles.buttonPillStart,
820+
isFirstMeasurement && styles.buttonPillUnfaded,
804821
!canScrollStart && styles.buttonHidden,
805822
)}>
806823
<Button
@@ -833,7 +850,10 @@ export function Carousel({
833850
}
834851
}}
835852
onClick={() => scrollBy(-1)}
836-
xstyle={styles.buttonRadiusOverride}
853+
xstyle={[
854+
styles.buttonRadiusOverride,
855+
isFirstMeasurement && styles.buttonUnfaded,
856+
]}
837857
/>
838858
</div>
839859
<div
@@ -843,6 +863,7 @@ export function Carousel({
843863
{...stylex.props(
844864
styles.buttonPill,
845865
styles.buttonPillEnd,
866+
isFirstMeasurement && styles.buttonPillUnfaded,
846867
!canScrollEnd && styles.buttonHidden,
847868
)}>
848869
<Button
@@ -873,7 +894,10 @@ export function Carousel({
873894
}
874895
}}
875896
onClick={() => scrollBy(1)}
876-
xstyle={styles.buttonRadiusOverride}
897+
xstyle={[
898+
styles.buttonRadiusOverride,
899+
isFirstMeasurement && styles.buttonUnfaded,
900+
]}
877901
/>
878902
</div>
879903
</>,

‎packages/core/src/ScrollableArea/ScrollableArea.test.tsx‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,13 @@ function setGeometry(
5858

5959
describe('ScrollableArea', () => {
6060
let frames: FrameRequestCallback[];
61+
// Sends the first resize notification of each element observed since the
62+
// last one. A browser sends it after it lays those elements out.
63+
let notifyFirstLayout: () => void;
6164

6265
beforeEach(() => {
6366
frames = [];
67+
notifyFirstLayout = () => {};
6468
vi.stubGlobal(
6569
'requestAnimationFrame',
6670
vi.fn((callback: FrameRequestCallback) => {
@@ -71,18 +75,34 @@ describe('ScrollableArea', () => {
7175
vi.stubGlobal('cancelAnimationFrame', vi.fn());
7276
vi.stubGlobal(
7377
'ResizeObserver',
74-
vi.fn(function () {
75-
return {observe: vi.fn(), unobserve: vi.fn(), disconnect: vi.fn()};
78+
vi.fn(function (callback: ResizeObserverCallback) {
79+
const unreported = new Set<Element>();
80+
notifyFirstLayout = () => {
81+
const entries = [...unreported].map(
82+
target => ({target}) as ResizeObserverEntry,
83+
);
84+
unreported.clear();
85+
if (entries.length > 0) {
86+
callback(entries, {} as ResizeObserver);
87+
}
88+
};
89+
return {
90+
observe: vi.fn((element: Element) => unreported.add(element)),
91+
unobserve: vi.fn((element: Element) => unreported.delete(element)),
92+
disconnect: vi.fn(),
93+
};
7694
}),
7795
);
7896
});
7997

8098
afterEach(() => vi.unstubAllGlobals());
8199

100+
/** A frame runs its callbacks, then lays out and notifies. */
82101
function flushFrame() {
83102
void act(() => {
84103
const pending = frames.splice(0);
85104
pending.forEach(callback => callback(performance.now()));
105+
notifyFirstLayout();
86106
});
87107
}
88108

‎packages/core/src/SegmentedControl/SegmentedControl.test.tsx‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1381,6 +1381,49 @@ describe('selection motion', () => {
13811381
spy.mockRestore();
13821382
}
13831383
});
1384+
1385+
it('starts no animation in the commit that mounts it; the first change holds the leaving surface', () => {
1386+
// jsdom has no Web Animations. This records each animation that starts.
1387+
const started: {element: HTMLElement; pseudoElement?: string | null}[] = [];
1388+
HTMLElement.prototype.animate = function (
1389+
this: HTMLElement,
1390+
_keyframes: Keyframe[] | PropertyIndexedKeyframes | null,
1391+
options?: number | KeyframeAnimationOptions,
1392+
) {
1393+
started.push({
1394+
element: this,
1395+
pseudoElement:
1396+
typeof options === 'object' ? options.pseudoElement : undefined,
1397+
});
1398+
return {
1399+
finished: new Promise<void>(() => {}),
1400+
cancel: () => {},
1401+
startTime: null,
1402+
} as unknown as Animation;
1403+
};
1404+
try {
1405+
const ui = (value: string) => (
1406+
<SegmentedControl value={value} onChange={() => {}} label="View">
1407+
<SegmentedControlItem value="grid" label="Grid" />
1408+
<SegmentedControlItem value="list" label="List" />
1409+
</SegmentedControl>
1410+
);
1411+
const {rerender} = render(ui('grid'));
1412+
// A new animation resolves style, which the mount commit must not do.
1413+
expect(started).toEqual([]);
1414+
1415+
rerender(ui('list'));
1416+
const group = screen.getByRole('radiogroup');
1417+
expect(
1418+
started.filter(
1419+
({element, pseudoElement}) =>
1420+
element === group && pseudoElement === '::after',
1421+
),
1422+
).toHaveLength(1);
1423+
} finally {
1424+
Reflect.deleteProperty(HTMLElement.prototype, 'animate');
1425+
}
1426+
});
13841427
});
13851428

13861429
describe("SegmentedControl keeps a caller's aria-describedby", () => {

‎packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts‎

Lines changed: 94 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@
44
* @file useSegmentedSelectionMotion.test.ts
55
* @input vitest, jsdom, SegmentedSelectionMotion with an animator on a
66
* scripted clock, stubbed segment geometry and a recording `animate`
7-
* @output The touch layer's selection motion as a state machine: the slide,
8-
* the hand-back, a change mid-flight, resize, Reduced Motion, the press, the
9-
* chase, the commit at the lift and the face that follows a drag
7+
* @output The touch layer's selection motion as a state machine: when its
8+
* animators attach, the slide, the hand-back, a change mid-flight, resize,
9+
* Reduced Motion, the press, the chase, the commit at the lift and the face
10+
* that follows a drag
1011
* @position Unit tests for useSegmentedSelectionMotion.ts; the browser proofs
1112
* are __tests__/SegmentedControl.interaction.browser.spec.ts
1213
*/
@@ -252,6 +253,96 @@ describe('the motion roles (spec:AST-094 FR4)', () => {
252253
});
253254
});
254255

256+
describe('when the animators attach', () => {
257+
interface Started {
258+
element: HTMLElement;
259+
keyframes: Keyframe[];
260+
options: KeyframeAnimationOptions;
261+
}
262+
let started: Started[] = [];
263+
const realAnimate = HTMLElement.prototype.animate;
264+
265+
// jsdom has no Web Animations. This records each animation that starts.
266+
beforeEach(() => {
267+
started = [];
268+
HTMLElement.prototype.animate = function (
269+
this: HTMLElement,
270+
keyframes: Keyframe[] | PropertyIndexedKeyframes | null,
271+
options?: number | KeyframeAnimationOptions,
272+
) {
273+
started.push({
274+
element: this,
275+
keyframes: keyframes as Keyframe[],
276+
options: options as KeyframeAnimationOptions,
277+
});
278+
return {
279+
finished: new Promise<void>(() => {}),
280+
cancel: vi.fn(),
281+
startTime: null,
282+
} as unknown as Animation;
283+
};
284+
});
285+
286+
afterEach(() => {
287+
HTMLElement.prototype.animate = realAnimate;
288+
});
289+
290+
/** The static animation that holds the ::after's resting opacity. */
291+
const leavingHolds = (track: HTMLElement) =>
292+
started.filter(
293+
({element, keyframes, options}) =>
294+
element === track &&
295+
options.pseudoElement === '::after' &&
296+
keyframes.every(keyframe => keyframe.opacity === '0'),
297+
);
298+
299+
it('starts no animation when the track attaches, as in the commit that mounts the control', () => {
300+
const ctx = setup('grid');
301+
expect(started).toEqual([]);
302+
expect(ctx.animator.element).toBeNull();
303+
expect(ctx.leavingAnimator.element).toBeNull();
304+
});
305+
306+
it('attaches the animators at the first selection change', () => {
307+
const ctx = setup('grid');
308+
select(ctx, 'grid', 'table');
309+
expect(ctx.animator.element).toBe(ctx.track);
310+
expect(ctx.leavingAnimator.element).toBe(ctx.track);
311+
expect(leavingHolds(ctx.track)).toHaveLength(1);
312+
expect(ctx.motion.isSliding).toBe(true);
313+
});
314+
315+
it('attaches the animators at the first press', () => {
316+
const ctx = setup('grid');
317+
begin(ctx, 60);
318+
expect(ctx.animator.element).toBe(ctx.track);
319+
expect(ctx.leavingAnimator.element).toBe(ctx.track);
320+
expect(leavingHolds(ctx.track)).toHaveLength(1);
321+
});
322+
323+
it('attaches them once: a later change or press starts no second hold', () => {
324+
const ctx = setup('grid');
325+
select(ctx, 'grid', 'table');
326+
select(ctx, 'table', 'list');
327+
begin(ctx, 60);
328+
expect(leavingHolds(ctx.track)).toHaveLength(1);
329+
});
330+
331+
it('detaches the animators with the track, and attaches them again at the next change', () => {
332+
const ctx = setup('grid');
333+
select(ctx, 'grid', 'table');
334+
ctx.motion.attachTrack(null);
335+
expect(ctx.animator.element).toBeNull();
336+
expect(ctx.leavingAnimator.element).toBeNull();
337+
338+
ctx.motion.attachTrack(ctx.track);
339+
expect(ctx.animator.element).toBeNull();
340+
select(ctx, 'table', 'list');
341+
expect(ctx.animator.element).toBe(ctx.track);
342+
expect(ctx.leavingAnimator.element).toBe(ctx.track);
343+
});
344+
});
345+
255346
describe('the selection slide', () => {
256347
it('paints the lens (the radiogroup’s ::before) with the selected surface and hides it on the segment: no element is added', () => {
257348
const ctx = setup('grid');

0 commit comments

Comments
 (0)