An open source design system that's fully customizable and agent ready
TypeScript
perf(core): a touch hit-area pass keeps the page's interactive elements until the DOM changes (#10242)
Cindy Zhangb4fc6840c09c
diff --git a/.changeset/hit-area-candidate-list.md b/.changeset/hit-area-candidate-list.mdnew file mode 100644index 0000000000..5086d617c3--- /dev/null+++ b/.changeset/hit-area-candidate-list.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] On a touch screen, a control that grows its touch target toward 44 px (CheckboxInput, RadioList, Switch, List rows, InfoTip, action groups) measures its neighbours in a shared pass. Each pass used to match every element on the page against the list of interactive selectors. The pass now keeps that list until an element is added, removed or moved, an attribute the list reads changes, or a control starts or stops its watch. It still reads every neighbour's box in each pass, so the touch targets are the same. Measured in Chromium at 4× CPU slowdown on a page with 240 interactive elements, a pass during a scroll took about 70% less time.++@cixzhangdiff --git a/packages/core/src/utils/hitArea.test.ts b/packages/core/src/utils/hitArea.test.tsindex f366893c6b..2fd6bef744 100644--- a/packages/core/src/utils/hitArea.test.ts+++ b/packages/core/src/utils/hitArea.test.ts@@ -399,6 +399,92 @@ describe('watchHitArea', () => {stop();});+ it('matches the page against its selector once, and again only after a mutation can change what it matches', () => {+ const control = byId('switch');+ place(control, rect(100, 100, 24, 24));+ place(byId('link'), rect(132, 100, 60, 24));+ place(byId('other'), rect(400, 400, 24, 24));+ const queries = vi.spyOn(document, 'querySelectorAll');+ const heard: HitInsets[] = [];+ const stop = watchHitArea(control, insets => heard.push(insets));+ show(control);+ flush();+ expect(queries).toHaveBeenCalledTimes(1);+ expect(heard).toEqual([{top: 10, right: 4, bottom: 10, left: 10}]);++ // A later pass reads every rect again, but finds the elements kept.+ place(byId('link'), rect(140, 100, 60, 24));+ log.length = 0;+ window.dispatchEvent(new Event('resize'));+ flush();+ expect(queries).toHaveBeenCalledTimes(1);+ expect(log).toContain('read link');+ expect(heard.at(-1)).toEqual({top: 10, right: 8, bottom: 10, left: 10});++ // A neighbour added in the same task as the pass counts in it.+ const above = document.createElement('button');+ above.id = 'above';+ document.body.append(above);+ place(above, rect(100, 80, 24, 12));+ window.dispatchEvent(new Event('resize'));+ flush();+ expect(queries).toHaveBeenCalledTimes(2);+ expect(heard.at(-1)).toEqual({top: 4, right: 8, bottom: 10, left: 10});++ // An attribute the selector reads makes an element a neighbour.+ const below = document.createElement('span');+ below.id = 'below';+ document.body.append(below);+ place(below, rect(100, 130, 24, 12));+ window.dispatchEvent(new Event('resize'));+ flush();+ expect(heard.at(-1)).toEqual({top: 4, right: 8, bottom: 10, left: 10});+ below.setAttribute('role', 'button');+ window.dispatchEvent(new Event('resize'));+ flush();+ expect(heard.at(-1)).toEqual({top: 4, right: 8, bottom: 3, left: 10});++ // A neighbour removed stops counting.+ above.remove();+ window.dispatchEvent(new Event('resize'));+ flush();+ expect(heard.at(-1)).toEqual({top: 10, right: 8, bottom: 3, left: 10});+ stop();+ });++ it('counts a control watched after the last pass by its own box, not by a part inside it', () => {+ // A group whose box reaches nearer the control than the input inside it.+ const group = document.createElement('div');+ const input = document.createElement('input');+ group.append(input);+ document.body.append(group);+ place(group, rect(100, 60, 24, 30));+ place(input, rect(100, 20, 24, 10));+ const control = byId('switch');+ place(control, rect(100, 100, 24, 24));+ place(byId('link'), rect(132, 100, 60, 24));+ place(byId('other'), rect(400, 400, 24, 24));+ const heard: HitInsets[] = [];+ const stop = watchHitArea(control, insets => heard.push(insets));+ show(control);+ flush();+ // The input is too far away to stop the control's growth.+ expect(heard.at(-1)).toEqual({top: 10, right: 4, bottom: 10, left: 10});+ // The group starts a watch. No element changes, but its box, not its+ // input, is now the neighbour.+ const stopGroup = watchHitArea(group, () => {});+ window.dispatchEvent(new Event('resize'));+ flush();+ expect(heard.at(-1)).toEqual({top: 5, right: 4, bottom: 10, left: 10});+ // The group stops its watch: its input, too far away, is the neighbour+ // again.+ stopGroup();+ window.dispatchEvent(new Event('resize'));+ flush();+ expect(heard.at(-1)).toEqual({top: 10, right: 4, bottom: 10, left: 10});+ stop();+ });+it('measures nothing off screen', () => {const control = byId('switch');place(control, rect(100, 100, 24, 24));@@ -797,6 +883,64 @@ describe('watchHitArea', () => {stops.forEach(stop => stop());});+ it('observes the page for its interactive elements only while the pointer is coarse and a watch is live (spec:AST-094 FR24)', () => {+ const Native = globalThis.MutationObserver;+ let pageObservers = 0;+ vi.stubGlobal(+ 'MutationObserver',+ class extends Native {+ private isOnPage = false;+ override observe(target: Node, options?: MutationObserverInit) {+ if (target === document && !this.isOnPage) {+ this.isOnPage = true;+ pageObservers += 1;+ }+ super.observe(target, options);+ }+ override disconnect() {+ if (this.isOnPage) {+ this.isOnPage = false;+ pageObservers -= 1;+ }+ super.disconnect();+ }+ },+ );+ const control = byId('switch');+ const other = byId('other');+ place(control, rect(100, 100, 24, 24));+ place(other, rect(400, 400, 24, 24));+ place(byId('link'), rect(132, 100, 60, 24));+ // Under a fine pointer: none.+ coarse = false;+ const stops = [control, other].map(element =>+ watchHitArea(element, () => {}),+ );+ show(control, other);+ flush();+ expect(pageObservers).toBe(0);+ // Coarse, with two watches: one.+ coarse = true;+ pointerListeners.forEach(listener => listener());+ show(control, other);+ flush();+ expect(pageObservers).toBe(1);+ // The pointer turns fine: released.+ coarse = false;+ pointerListeners.forEach(listener => listener());+ expect(pageObservers).toBe(0);+ // Coarse again, then the last watch stops: released.+ coarse = true;+ pointerListeners.forEach(listener => listener());+ show(control, other);+ flush();+ expect(pageObservers).toBe(1);+ stops[0]();+ expect(pageObservers).toBe(1);+ stops[1]();+ expect(pageObservers).toBe(0);+ });+it('removes its document listener when the last watch stops (spec:AST-094 FR24)', () => {const offDocument = vi.spyOn(document, 'removeEventListener');const stops = ['switch', 'other'].map(id =>diff --git a/packages/core/src/utils/hitArea.ts b/packages/core/src/utils/hitArea.tsindex 1fb8e1cd14..d00fff1b79 100644--- a/packages/core/src/utils/hitArea.ts+++ b/packages/core/src/utils/hitArea.ts@@ -30,7 +30,11 @@// layout px. A layer that opens from a smaller scale then keeps the insets of// the size it settles at.-import {observeContent} from './sharedMutationObserver';+import {+ flushMutations,+ observeContent,+ observeMutations,+} from './sharedMutationObserver';/** A rect in client pixels. */export interface HitRect {@@ -305,6 +309,24 @@ const CONTENT_SETTLE_MS = 100;const PASSIVE_CAPTURE = {capture: true, passive: true} as const;+/**+ * The mutations that can change which elements `INTERACTIVE_SELECTOR`+ * matches: elements added, removed or moved, and the attributes it reads.+ */+const CANDIDATE_MUTATIONS: MutationObserverInit = {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: [+ 'href',+ 'type',+ 'for',+ 'contenteditable',+ 'role',+ 'tabindex',+ ],+};+function now(): number {return typeof performance === 'undefined' ? Date.now() : performance.now();}@@ -344,6 +366,24 @@ let pointer: MediaQueryList | null = null;let visibility: IntersectionObserver | null = null;let resize: ResizeObserver | null = null;let isCoarse = false;+/**+ * The page's interactive elements, as the last pass found them. A pass keeps+ * them until a mutation or a watch change can change them.+ */+let interactive: Element[] | null = null;+let interactiveDocument: Document | null = null;+let stopInteractiveWatch: (() => void) | null = null;++function forgetInteractive(): void {+ interactive = null;+}++function stopWatchingInteractive(): void {+ stopInteractiveWatch?.();+ stopInteractiveWatch = null;+ interactiveDocument = null;+ interactive = null;+}function sameInsets(a: HitInsets, b: HitInsets): boolean {return (@@ -495,21 +535,48 @@ function watchedOwner(element: Element): Element | null {}/**- * The page's interactive elements and their rects: one read. A watched- * control counts by its own box, never by a part inside it (its invisible- * input is grown by its hit area, which must not shrink a neighbour's).+ * The page's interactive elements. A watched control counts by its own box,+ * never by a part inside it (its invisible input is grown by its hit area,+ * which must not shrink a neighbour's).*/-function readCandidates(doc: Document): Candidate[] {+function interactiveElements(doc: Document): Element[] {+ if (typeof MutationObserver === 'undefined') {+ // Nothing reports a change, so nothing is kept.+ interactive = null;+ } else if (interactiveDocument !== doc) {+ stopWatchingInteractive();+ interactiveDocument = doc;+ stopInteractiveWatch = observeMutations(+ doc,+ CANDIDATE_MUTATIONS,+ forgetInteractive,+ );+ } else {+ // A mutation earlier in this task is not delivered yet.+ flushMutations(CANDIDATE_MUTATIONS);+ }+ if (interactive != null) {+ return interactive;+ }const seen = new Set<Element>();- const candidates: Candidate[] = [];+ const elements: Element[] = [];for (const found of doc.querySelectorAll(INTERACTIVE_SELECTOR)) {const element = watchedOwner(found) ?? found;if (!seen.has(element)) {seen.add(element);- candidates.push({element, rect: plainRect(element)});+ elements.push(element);}}- return candidates;+ interactive = elements;+ return elements;+}++/** The page's interactive elements and their rects: one read. */+function readCandidates(doc: Document): Candidate[] {+ return interactiveElements(doc).map(element => ({+ element,+ rect: plainRect(element),+ }));}/** A control's rect and clamped insets, from candidates already read. */@@ -824,6 +891,7 @@ function stopObserving(): void {resize = null;scopeTimers.forEach(timer => clearTimeout(timer));scopeTimers.clear();+ stopWatchingInteractive();if (frame != null && typeof cancelAnimationFrame === 'function') {cancelAnimationFrame(frame);}@@ -943,6 +1011,7 @@ export function watchHitArea(if (entry == null) {entry = {watches: new Set(), release: null, disarm: null};watched.set(element, entry);+ forgetInteractive();entry.watches.add(watch);if (isCoarse) {observe(element, entry);@@ -964,6 +1033,7 @@ export function watchHitArea(if (own.watches.size === 0) {own.release?.();watched.delete(element);+ forgetInteractive();}if (watched.size === 0) {stopObserving();diff --git a/packages/core/src/utils/sharedMutationObserver.test.ts b/packages/core/src/utils/sharedMutationObserver.test.tsindex 9809db2ad2..4a070fd548 100644--- a/packages/core/src/utils/sharedMutationObserver.test.ts+++ b/packages/core/src/utils/sharedMutationObserver.test.ts@@ -1,7 +1,11 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, it, expect, vi} from 'vitest';-import {observeContent, observeMutations} from './sharedMutationObserver';+import {+ flushMutations,+ observeContent,+ observeMutations,+} from './sharedMutationObserver';const flush = async () => new Promise(resolve => setTimeout(resolve, 0));@@ -104,3 +108,25 @@ describe('observeMutations', () => {stops.forEach(stop => stop());});});++describe('flushMutations', () => {+ it('delivers a mutation of this task at once, and only once', async () => {+ const element = document.createElement('div');+ const options = {childList: true, subtree: true};+ const callback = vi.fn();+ const unsubscribe = observeMutations(element, options, callback);++ element.append(document.createElement('span'));+ expect(callback).not.toHaveBeenCalled();+ flushMutations(options);+ expect(callback).toHaveBeenCalledTimes(1);+ await flush();+ expect(callback).toHaveBeenCalledTimes(1);++ // Nothing pending, or no observer for the options: nothing is called.+ flushMutations(options);+ flushMutations({attributes: true});+ expect(callback).toHaveBeenCalledTimes(1);+ unsubscribe();+ });+});diff --git a/packages/core/src/utils/sharedMutationObserver.ts b/packages/core/src/utils/sharedMutationObserver.tsindex c9b9526b84..2ec6f51505 100644--- a/packages/core/src/utils/sharedMutationObserver.ts+++ b/packages/core/src/utils/sharedMutationObserver.ts@@ -5,8 +5,8 @@/*** @file sharedMutationObserver.ts* @input MutationObserver API- * @output Exports observeMutations (one shared observer per set of options)- * and observeContent, its text-and-children form+ * @output Exports observeMutations (one shared observer per set of options),+ * observeContent, its text-and-children form, and flushMutations* @position Internal utility; consumed by useTruncation, hitArea, AppShell's* main-overflow observer, ModalAnnounceProvider's presentation watch and* CheckboxList's required group. The mutation counterpart of sharedResizeObserver:@@ -25,6 +25,7 @@ const CONTENT_OPTIONS: MutationObserverInit = {interface SharedObserver {readonly observer: MutationObserver;readonly callbacks: Map<Node, Set<MutationCallback>>;+ readonly deliver: (records: MutationRecord[]) => void;}/**@@ -49,7 +50,7 @@ function optionsKey(options: MutationObserverInit): string {function createSharedObserver(options: MutationObserverInit): SharedObserver {const callbacks = new Map<Node, Set<MutationCallback>>();const isSubtree = options.subtree === true;- const observer = new MutationObserver(records => {+ const deliver = (records: MutationRecord[]) => {// One call per callback per batch, however many records it received.// With `subtree`, a record's target can be any descendant, so walk up to// the observed roots; without it, the target is the observed node.@@ -70,8 +71,8 @@ function createSharedObserver(options: MutationObserverInit): SharedObserver {}}pending.forEach(callback => callback());- });- return {observer, callbacks};+ };+ return {observer: new MutationObserver(deliver), callbacks, deliver};}/**@@ -135,3 +136,16 @@ export function observeContent(): () => void {return observeMutations(element, CONTENT_OPTIONS, callback);}++/**+ * Deliver at once the records that the shared observer for `options` holds+ * but has not yet delivered. The observer delivers a mutation in a microtask.+ * A read in the same task calls this first to see it.+ */+export function flushMutations(options: MutationObserverInit): void {+ const shared = observers.get(optionsKey(options));+ const records = shared?.observer.takeRecords() ?? [];+ if (shared != null && records.length > 0) {+ shared.deliver(records);+ }+}