An open source design system that's fully customizable and agent ready
TypeScript
fix(core): a control in an opening layer keeps its settled touch insets (#9957)
Christopher Chedeau0f059280407a
diff --git a/.changeset/hit-area-layout-box-insets.md b/.changeset/hit-area-layout-box-insets.mdnew file mode 100644index 0000000000..f8878c075e--- /dev/null+++ b/.changeset/hit-area-layout-box-insets.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Under a finger, a Switch or InfoTip measured while an ancestor is scaled keeps the touch insets of its unscaled layout. Before, that measurement kept the scaled frame's insets until the next resize.++@vjeuxdiff --git a/packages/core/src/utils/__tests__/hitArea.interaction.browser.spec.ts b/packages/core/src/utils/__tests__/hitArea.interaction.browser.spec.tsnew file mode 100644index 0000000000..3dd4cf3ca1--- /dev/null+++ b/packages/core/src/utils/__tests__/hitArea.interaction.browser.spec.ts@@ -0,0 +1,105 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file hitArea.interaction.browser.spec.ts+ * @input The built Switch story, a phone-sized touch context and a mouse+ * context, and a layer held at half size while the switch's first+ * measurement runs+ * @output Proves that a control measured while its layer opens from a smaller+ * scale keeps the insets of the size the layer settles at, under a finger,+ * and that a mouse page writes no insets+ * @position The browser layer of utils/hitArea.ts; the pure model is+ * hitArea.test.ts+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {openStory, withStorybook} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++/** The switch's written insets, in the order top, right, bottom, left. */+async function insets(page: Page): Promise<string[]> {+ return page.evaluate(() => {+ const surface = document.querySelector<HTMLElement>(+ '#storybook-root [role="switch"]',+ )?.parentElement;+ return ['top', 'right', 'bottom', 'left'].map(+ side =>+ surface?.style.getPropertyValue(`--astryx-hit-inset-${side}`) ?? '',+ );+ });+}++/** Waits for two frames, the time a pending measurement takes. */+async function frames(page: Page): Promise<void> {+ await page.evaluate(async () => {+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );+ });+}++/**+ * Holds the story's root at half size from the first frame, as a layer that+ * opens from a smaller scale is during its first measurement.+ */+async function holdHalfSize(page: Page): Promise<void> {+ await page.addInitScript(() => {+ document.addEventListener('DOMContentLoaded', () => {+ const style = document.createElement('style');+ style.id = 'opening-layer';+ style.textContent =+ '#storybook-root { transform: scale(0.5); transform-origin: 0 0; }';+ document.head.append(style);+ });+ });+}++test('a switch measured while its layer opens from half size keeps the insets of the settled layout', async ({+ page,+}) => {+ await holdHalfSize(page);+ await openStory(page, storybook(), 'core-switch--default');+ await page.waitForFunction(+ () =>+ (document+ .querySelector<HTMLElement>('#storybook-root [role="switch"]')+ ?.parentElement?.style.getPropertyValue('--astryx-hit-inset-top') ??+ '') !== '',+ );+ // The layer settles at full size. Nothing about the switch's own box+ // changes, so nothing measures it again.+ await page.evaluate(() => document.getElementById('opening-layer')?.remove());+ await frames(page);+ const settled = await insets(page);+ // A measurement of the settled page: a window resize measures every control.+ await page.evaluate(() => window.dispatchEvent(new Event('resize')));+ await frames(page);+ expect(settled).toEqual(await insets(page));+});++test('a mouse page writes no insets, at half size or settled', async ({+ browser,+}) => {+ const context = await browser.newContext({+ hasTouch: false,+ isMobile: false,+ deviceScaleFactor: 1,+ viewport: {width: 480, height: 320},+ });+ try {+ const page = await context.newPage();+ await holdHalfSize(page);+ await openStory(page, storybook(), 'core-switch--default');+ await frames(page);+ expect(await insets(page)).toEqual(['', '', '', '']);+ await page.evaluate(() =>+ document.getElementById('opening-layer')?.remove(),+ );+ await page.evaluate(() => window.dispatchEvent(new Event('resize')));+ await frames(page);+ expect(await insets(page)).toEqual(['', '', '', '']);+ } finally {+ await context.close();+ }+});diff --git a/packages/core/src/utils/hitArea.test.ts b/packages/core/src/utils/hitArea.test.tsindex d07d3691ee..dde0fea6ef 100644--- a/packages/core/src/utils/hitArea.test.ts+++ b/packages/core/src/utils/hitArea.test.ts@@ -264,6 +264,33 @@ describe('watchHitArea', () => {stop();});+ it('measures a control in an opening layer by its layout box, so its insets hold once the layer settles', () => {+ // The layer opens from half size about the page origin, so every rect on+ // screen is half its layout box during the first pass.+ const half = ({left, top, right, bottom}: HitRect) => ({+ left: left / 2,+ top: top / 2,+ right: right / 2,+ bottom: bottom / 2,+ });+ const control = byId('switch');+ Object.assign(control.style, {+ width: '24px',+ height: '24px',+ boxSizing: 'border-box',+ });+ place(control, half(rect(100, 100, 24, 24)));+ place(byId('link'), half(rect(132, 100, 60, 24)));+ place(byId('other'), half(rect(400, 400, 24, 24)));+ const heard: HitInsets[] = [];+ const stop = watchHitArea(control, insets => heard.push(insets));+ show(control);+ flush();+ // The same insets as the page at full size gives.+ expect(heard).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));diff --git a/packages/core/src/utils/hitArea.ts b/packages/core/src/utils/hitArea.tsindex 42d157a615..ad47dd7091 100644--- a/packages/core/src/utils/hitArea.ts+++ b/packages/core/src/utils/hitArea.ts@@ -24,6 +24,9 @@// live control measures: only under a coarse primary pointer (AST-094), only on// screen, and in one read pass per frame within a 4 ms budget. Until the first// pass the insets are 0, so first paint never overlaps anything.+// The insets are lengths in the control's own box, so a pass measures in its+// layout px. A layer that opens from a smaller scale then keeps the insets of+// the size it settles at.import {observeContent} from './sharedMutationObserver';@@ -330,6 +333,77 @@ function plainRect(element: Element): HitRect {return {left, top, right, bottom};}+/** A box that the transforms around it leave at its layout size. */+const UNSCALED = {x: 1, y: 1} as const;++/** One axis of a box's scale on screen: its client size over its layout size. */+function axisScale(onScreen: number, layout: number): number {+ if (!(layout > 0) || !(onScreen > 0)) {+ return 1;+ }+ const scale = onScreen / layout;+ // Within rounding of 1 the box is at its layout size: no change to the rects.+ return Math.abs(scale - 1) < 1e-3 ? 1 : scale;+}++/**+ * How far the transforms around `element` scale its box on screen, per axis.+ * A layer that opens from a smaller scale scales every rect inside it, while+ * the layout box keeps the size the layer settles at. Only a scale is+ * expected: a rotated or skewed box would read as a larger scale.+ */+function screenScale(+ element: Element,+ onScreen: HitRect,+): {x: number; y: number} {+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);+ if (style == null || !style.width.endsWith('px')) {+ return UNSCALED;+ }+ const px = (value: string) => Number.parseFloat(value) || 0;+ const isContentBox = style.boxSizing !== 'border-box';+ const width =+ px(style.width) ++ (isContentBox+ ? px(style.paddingLeft) ++ px(style.paddingRight) ++ px(style.borderLeftWidth) ++ px(style.borderRightWidth)+ : 0);+ const height =+ px(style.height) ++ (isContentBox+ ? px(style.paddingTop) ++ px(style.paddingBottom) ++ px(style.borderTopWidth) ++ px(style.borderBottomWidth)+ : 0);+ return {+ x: axisScale(onScreen.right - onScreen.left, width),+ y: axisScale(onScreen.bottom - onScreen.top, height),+ };+}++/**+ * `rect` in the layout px of the box at `origin`: its offset from `origin`,+ * divided by that box's scale on screen.+ */+function inLayout(+ rect: HitRect,+ origin: HitRect,+ scale: {x: number; y: number},+): HitRect {+ if (scale.x === 1 && scale.y === 1) {+ return rect;+ }+ return {+ left: origin.left + (rect.left - origin.left) / scale.x,+ top: origin.top + (rect.top - origin.top) / scale.y,+ right: origin.left + (rect.right - origin.left) / scale.x,+ bottom: origin.top + (rect.bottom - origin.top) / scale.y,+ };+}+interface Candidate {readonly element: Element;readonly rect: HitRect;@@ -373,14 +447,15 @@ function measureOne(candidates: ReadonlyArray<Candidate>,): {target: HitRect; insets: HitInsets; neighbours: HitRect[]} {const target = plainRect(watch.element);+ const scale = screenScale(watch.element, target);// Two targets each growing up to half the minimum reach each other from a// minimum apart.const reach = Math.max(0, watch.minSize);const band = grown(target, {- top: reach,- right: reach,- bottom: reach,- left: reach,+ top: reach * scale.y,+ right: reach * scale.x,+ bottom: reach * scale.y,+ left: reach * scale.x,});const neighbours = candidates.filter(@@ -393,7 +468,16 @@ function measureOne(.map(({rect}) => rect);return {target,- insets: clampedHitInsets(target, neighbours, watch.minSize),+ // The insets are in the control's layout px. The returned rects stay in+ // screen px for a touch's distance checks. A neighbour maps by the+ // control's scale, as if it is in the same layer. A neighbour outside that+ // layer then reads farther away. A touch compares screen distances, so it+ // still counts that neighbour.+ insets: clampedHitInsets(+ inLayout(target, target, scale),+ neighbours.map(rect => inLayout(rect, target, scale)),+ watch.minSize,+ ),neighbours,};}