Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/scroll-region-first-measure-after-layout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astryxdesign/core': patch
---

[perf] A scrolling `LayoutContent`, `LayoutPanel` or `StackItem`, and `AppShell`'s main region under `height="fill"`, read no layout while they mount. Each one measures whether it overflows at the browser's first resize notification after layout. A region that mounts with a `Dialog`'s body no longer forces a style and layout pass before the dialog opens. The region's group role and name, and main's tab stop, arrive with that first notification.

@vjeux
42 changes: 38 additions & 4 deletions packages/core/src/AppShell/AppShell.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,37 @@ beforeAll(() => {
});

// Mock ResizeObserver
// Records what each observer watches, so a test can send the notification a
// browser sends after it lays those elements out.
const resizeObservers = new Set<MockResizeObserver>();
class MockResizeObserver {
callback: ResizeObserverCallback;
targets = new Set<Element>();
constructor(callback: ResizeObserverCallback) {
this.callback = callback;
resizeObservers.add(this);
}
observe(target: Element) {
this.targets.add(target);
}
unobserve(target: Element) {
this.targets.delete(target);
}
disconnect() {
this.targets.clear();
resizeObservers.delete(this);
}
}

function notifyResizeObservers() {
for (const resizeObserver of [...resizeObservers]) {
const entries = [...resizeObserver.targets].map(
target => ({target}) as ResizeObserverEntry,
);
if (entries.length > 0) {
resizeObserver.callback(entries, resizeObserver);
}
}
observe() {}
unobserve() {}
disconnect() {}
}

vi.stubGlobal('ResizeObserver', MockResizeObserver);
Expand Down Expand Up @@ -1549,6 +1572,9 @@ describe('AppShell main keyboard access', () => {

beforeEach(() => {
frames = [];
// Earlier suites leave their own observer in place; these tests send the
// browser's notification through the recording one.
vi.stubGlobal('ResizeObserver', MockResizeObserver);
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((callback: FrameRequestCallback) => {
Expand Down Expand Up @@ -1598,6 +1624,10 @@ describe('AppShell main keyboard access', () => {
}

function remeasure() {
// The browser lays main out and notifies before the window resizes.
act(() => {
notifyResizeObservers();
});
act(() => {
window.dispatchEvent(new Event('resize'));
});
Expand Down Expand Up @@ -1716,12 +1746,16 @@ describe('AppShell main keyboard access', () => {
remeasure();
expect(screen.getByRole('main')).toHaveAttribute('tabindex', '-1');

// Back in fill, main is measured as it attaches, with no other signal.
// Back in fill, main is measured at the first resize notification, with
// no other signal.
rerender(
<AppShell topNav={<div>Nav</div>}>
<p>Long content</p>
</AppShell>,
);
act(() => {
notifyResizeObservers();
});
expect(screen.getByRole('main')).toHaveAttribute('tabindex', '0');
});

Expand Down
124 changes: 115 additions & 9 deletions packages/core/src/AppShell/observeMainOverflow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
* @input observeMainOverflow on a main element with mocked geometry, a
* recorded resize observer, and frames run by hand
* @output Regression coverage for measuring a scroll container that holds its
* content as direct children: the children's sizes, the children coming and
* going, unknown geometry, and stopping
* content as direct children: no read before the first resize notification,
* font loads, the children's sizes, the children coming and going, unknown
* geometry, and stopping
* @position Unit contract of AppShell's internal overflow observer;
* AppShell.test.tsx covers main becoming a keyboard stop
*/
Expand All @@ -15,18 +16,46 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {observeMainOverflow} from './observeMainOverflow';

const observed = vi.hoisted(
() => new Map<Element, {callback: () => void; stopped: boolean}>(),
() =>
new Map<
Element,
{callback: (entry: ResizeObserverEntry | null) => void; stopped: boolean}
>(),
);
const resizeObserver = vi.hoisted(() => ({exists: true}));

vi.mock('../utils/sharedResizeObserver', () => ({
observeResize: (element: Element, callback: () => void) => {
vi.mock('../utils/sharedResizeObserver', () => {
const register = (
element: Element,
callback: (entry: ResizeObserverEntry | null) => void,
) => {
const entry = {callback, stopped: false};
observed.set(element, entry);
return () => {
entry.stopped = true;
};
},
}));
};
return {
// Like the real one, it calls back once as it registers.
observeResize: (
element: Element,
callback: (entry: ResizeObserverEntry) => void,
) => {
const stop = register(element, callback as never);
callback({target: element} as ResizeObserverEntry);
return stop;
},
observeResizeAfterLayout: (
element: Element,
callback: (entry: ResizeObserverEntry | null) => void,
) => (resizeObserver.exists ? register(element, callback) : null),
};
});

/** The notification a browser sends after it lays `element` out. */
function notify(element: Element) {
observed.get(element)?.callback({target: element} as ResizeObserverEntry);
}

function setGeometry(element: HTMLElement, client: number, scroll: number) {
for (const [key, value] of [
Expand All @@ -45,13 +74,34 @@ function setGeometry(element: HTMLElement, client: number, scroll: number) {
}
}

/**
* A font set that counts reads of `ready` and lets a test end a load.
* jsdom has no `document.fonts`.
*/
function stubFonts() {
const events = new EventTarget();
const fonts = {
readyReads: 0,
addEventListener: events.addEventListener.bind(events),
removeEventListener: events.removeEventListener.bind(events),
dispatchEvent: events.dispatchEvent.bind(events),
get ready() {
fonts.readyReads += 1;
return Promise.resolve(fonts);
},
};
Object.defineProperty(document, 'fonts', {configurable: true, value: fonts});
return fonts;
}

describe('observeMainOverflow', () => {
let frames: FrameRequestCallback[];
let main: HTMLElement;
let stop: (() => void) | null;

beforeEach(() => {
observed.clear();
resizeObserver.exists = true;
frames = [];
stop = null;
vi.stubGlobal(
Expand Down Expand Up @@ -85,6 +135,7 @@ describe('observeMainOverflow', () => {
afterEach(() => {
stop?.();
main.remove();
Reflect.deleteProperty(document, 'fonts');
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
Expand All @@ -94,9 +145,61 @@ describe('observeMainOverflow', () => {
pending.forEach(callback => callback(performance.now()));
}

it('reports the first measurement at once, then only changes', () => {
it('reads no layout as it starts, and measures at the first resize notification', () => {
const onChange = vi.fn();
// Starting runs where main attaches, in React's commit.
stop = observeMainOverflow(main, onChange);
expect(window.getComputedStyle).not.toHaveBeenCalled();
expect(frames).toEqual([]);
expect(onChange).not.toHaveBeenCalled();

// The browser lays main out, then notifies: the read happens there.
notify(main);
expect(window.getComputedStyle).toHaveBeenCalledWith(main);
expect(onChange.mock.calls).toEqual([[false]]);
});

it('lets no other signal read layout before the first resize notification', () => {
const onChange = vi.fn();
stop = observeMainOverflow(main, onChange);
window.dispatchEvent(new Event('resize'));
runFrames();
expect(window.getComputedStyle).not.toHaveBeenCalled();
expect(onChange).not.toHaveBeenCalled();
});

it('does not read fonts.ready, which updates style and layout in Chromium', () => {
const fonts = stubFonts();
stop = observeMainOverflow(main, vi.fn());
notify(main);
expect(fonts.readyReads).toBe(0);
});

it('measures again when a font finishes loading after layout', () => {
const fonts = stubFonts();
const onChange = vi.fn();
stop = observeMainOverflow(main, onChange);
notify(main);
expect(onChange.mock.calls).toEqual([[false]]);

// The loaded font makes the content taller than main.
setGeometry(main, 300, 1200);
fonts.dispatchEvent(new Event('loadingdone'));
runFrames();
expect(onChange.mock.calls).toEqual([[false], [true]]);
});

it('measures at once where no ResizeObserver exists', () => {
resizeObserver.exists = false;
const onChange = vi.fn();
stop = observeMainOverflow(main, onChange);
expect(onChange.mock.calls).toEqual([[false]]);
});

it('reports the first measurement, then only changes', () => {
const onChange = vi.fn();
stop = observeMainOverflow(main, onChange);
notify(main);
expect(onChange.mock.calls).toEqual([[false]]);

window.dispatchEvent(new Event('resize'));
Expand All @@ -112,14 +215,15 @@ describe('observeMainOverflow', () => {
it('watches each direct child, so content growing inside main is measured', () => {
const onChange = vi.fn();
stop = observeMainOverflow(main, onChange);
notify(main);
const second = main.querySelector('#second');
expect(observed.has(main)).toBe(true);
expect(observed.has(main.querySelector('#first') as Element)).toBe(true);
expect(second != null && observed.has(second)).toBe(true);

// The child grows; main keeps its own size.
setGeometry(main, 300, 1200);
observed.get(second as Element)?.callback();
notify(second as Element);
runFrames();

expect(onChange).toHaveBeenLastCalledWith(true);
Expand All @@ -142,6 +246,7 @@ describe('observeMainOverflow', () => {
const onChange = vi.fn();
setGeometry(main, 300, 1200);
stop = observeMainOverflow(main, onChange);
notify(main);
expect(onChange.mock.calls).toEqual([[true]]);

// A hidden or zero-size main is unknown, not fitting.
Expand All @@ -154,6 +259,7 @@ describe('observeMainOverflow', () => {
it('stops every observer and listener, and measures nothing after', () => {
const onChange = vi.fn();
stop = observeMainOverflow(main, onChange);
notify(main);
const children = Array.from(main.children);
window.dispatchEvent(new Event('resize'));
stop();
Expand Down
Loading