An open source design system that's fully customizable and agent ready
TypeScript
perf(Layer): read an entering layer's box without writing styles (#10240)
Cindy Zhang55acf21babb4
diff --git a/.changeset/layer-settled-box-read-only.md b/.changeset/layer-settled-box-read-only.mdnew file mode 100644index 0000000000..873a9bd8b7--- /dev/null+++ b/.changeset/layer-settled-box-read-only.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] While a Tooltip or another anchored layer plays its entrance, most reads of the layer's box write no styles. Before, each read during the entrance overrode the layer's transform, read the box and put the transform back, so the browser recomputed style and layout twice in that frame (measured in Chromium: 8 style writes, 2 style recalculations and 2 layouts per read). Now a read on the middle frames of an entrance takes the entrance transform out of one box read by calculation, and gets the same box. The read that shows the layer and any read while its entrance is pending, a read whose box does not yet carry the entrance (in Chromium, a layer at a fallback position), the last frames of an entrance, a layer under a CSS `zoom` other than 1, and a `translate` given as a percentage still use the override, as before. Placement, the entrance animation and the keyboard cap do not change.++@cixzhangdiff --git a/packages/core/src/Layer/layerExitCopy.test.ts b/packages/core/src/Layer/layerExitCopy.test.tsindex 8a4cc08b13..29a3aa294c 100644--- a/packages/core/src/Layer/layerExitCopy.test.ts+++ b/packages/core/src/Layer/layerExitCopy.test.ts@@ -284,9 +284,15 @@ describe('placeLayerExitCopy', () => {popoverApi(true);const element = layer();// Mid-entrance: drawn at half size about its top-left corner, at a- // fractional position its whole-pixel offsets round away.- const laidOut = {left: 40.391, top: 120.594, width: 320.4, height: 253};- const drawn = {...laidOut, width: 160.2, height: 126.5};+ // fractional position its whole-pixel offsets round away. Like a real+ // engine, the box is laid out on the 1/64 px grid.+ const laidOut = {+ left: 40.390625,+ top: 120.59375,+ width: 320.40625,+ height: 253,+ };+ const drawn = {...laidOut, width: 160.203125, height: 126.5};// jsdom keeps no `!important`: the read's override shows as `none`.const settled = () => element.style.getPropertyValue('scale') === 'none';element.getBoundingClientRect = () => {@@ -315,7 +321,7 @@ describe('placeLayerExitCopy', () => {const presented: Record<string, string> = {scale: '0.5','transform-origin': '0px 0px',- width: '320.4px',+ width: '320.40625px',height: '253px','box-sizing': 'border-box',};@@ -334,9 +340,9 @@ describe('placeLayerExitCopy', () => {);const copy = place(element);// Laid out where the layer is, at its used size, fractions kept...- expect(copy.style.getPropertyValue('left')).toBe('40.391px');- expect(copy.style.getPropertyValue('top')).toBe('120.594px');- expect(copy.style.getPropertyValue('width')).toBe('320.4px');+ expect(copy.style.getPropertyValue('left')).toBe('40.390625px');+ expect(copy.style.getPropertyValue('top')).toBe('120.59375px');+ expect(copy.style.getPropertyValue('width')).toBe('320.40625px');expect(copy.style.getPropertyValue('height')).toBe('253px');// ...and drawn as it was drawn.expect(copy.style.getPropertyValue('scale')).toBe('0.5');diff --git a/packages/core/src/Layer/settledBox.test.ts b/packages/core/src/Layer/settledBox.test.tsnew file mode 100644index 0000000000..c5a80541d5--- /dev/null+++ b/packages/core/src/Layer/settledBox.test.ts@@ -0,0 +1,316 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file settledBox.test.ts+ * @input Uses vitest, settledBox, a stand-in engine for one layer's box+ * @output Unit tests for the layer box read without its transform+ * @position Testing; validates settledBox.ts+ *+ * SYNC: When settledBox.ts changes, update tests to match new behavior+ */++import {afterEach, describe, expect, it, vi} from 'vitest';+import {settledBox} from './settledBox';++type Matrix = readonly [number, number, number, number, number, number];++interface Engine {+ /** The layout box, where the position option put the layer. */+ layout: {left: number; top: number; width: number; height: number};+ /** The exact transform the engine applies. */+ matrix: Matrix;+ /** `transform-origin`, px from the box's top-left corner. */+ origin: readonly [number, number];+ transition?: {property: string; duration: string};+ /** The computed `translate`, beside the matrix the engine paints. */+ translate?: string;+ /**+ * The box read is still laid out without the transform that the computed+ * style already reports, as right after a show in Chromium.+ */+ stale?: boolean;+ /** The engine paints `matrix` from `translate` alone: `transform` is none. */+ translateOnly?: boolean;+}++/** A number as an engine serializes a computed transform: six digits. */+function serialized(value: number): string {+ return String(Number(value.toPrecision(6)));+}++/**+ * A layer whose engine paints `engine.matrix` over its layout box, unless an+ * inline `transform: none !important` overrides it, as Chromium does.+ */+function layerIn(engine: Engine): HTMLElement {+ const layer = document.createElement('div');+ document.body.append(layer);+ const isOverridden = () =>+ layer.style.getPropertyValue('transform') === 'none';+ const applied = (): Matrix =>+ isOverridden() ? [1, 0, 0, 1, 0, 0] : engine.matrix;+ const laidOut = (): Matrix => (engine.stale ? [1, 0, 0, 1, 0, 0] : applied());+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element => {+ if (element !== layer) {+ throw new Error('read of another element');+ }+ const m = applied();+ const values: Record<string, string> = {+ transform:+ m.join() === '1,0,0,1,0,0' || engine.translateOnly+ ? 'none'+ : `matrix(${m.map(serialized).join(', ')})`,+ translate: isOverridden() ? 'none' : (engine.translate ?? 'none'),+ rotate: 'none',+ scale: 'none',+ 'transform-origin': `${engine.origin[0]}px ${engine.origin[1]}px`,+ 'transition-property': engine.transition?.property ?? 'all',+ 'transition-duration': engine.transition?.duration ?? '0s',+ width: `${engine.layout.width}px`,+ height: `${engine.layout.height}px`,+ 'box-sizing': 'border-box',+ };+ return {+ getPropertyValue: (name: string) => values[name] ?? '',+ transform: values.transform,+ translate: values.translate,+ rotate: values.rotate,+ scale: values.scale,+ transformOrigin: values['transform-origin'],+ transitionProperty: values['transition-property'],+ transitionDuration: values['transition-duration'],+ } as unknown as CSSStyleDeclaration;+ });+ layer.getBoundingClientRect = () => {+ const {left, top, width, height} = engine.layout;+ const [a, b, c, d, e, f] = laidOut();+ const [ox, oy] = engine.origin;+ const corners = [+ [0, 0],+ [width, 0],+ [0, height],+ [width, height],+ ].map(([x, y]) => [+ left + ox + a * (x - ox) + c * (y - oy) + e,+ top + oy + b * (x - ox) + d * (y - oy) + f,+ ]);+ const xs = corners.map(([x]) => x);+ const ys = corners.map(([, y]) => y);+ return new DOMRect(+ Math.min(...xs),+ Math.min(...ys),+ Math.max(...xs) - Math.min(...xs),+ Math.max(...ys) - Math.min(...ys),+ );+ };+ Object.defineProperty(layer, 'offsetWidth', {+ get: () => Math.round(engine.layout.width),+ });+ Object.defineProperty(layer, 'offsetHeight', {+ get: () => Math.round(engine.layout.height),+ });+ return layer;+}++function edges(rect: DOMRect): number[] {+ return [rect.left, rect.top, rect.right, rect.bottom];+}++/** A Tooltip's box, on the layout grid of 1/64 px. */+const LAYOUT = {+ left: 122.421875,+ top: 367.53125,+ width: 189.828125,+ height: 28.375,+};+/** Its origin at the centre of its bottom edge: it enters from below. */+const ORIGIN = [LAYOUT.width / 2, LAYOUT.height] as const;++afterEach(() => {+ vi.restoreAllMocks();+ document.body.replaceChildren();+});++describe('settledBox', () => {+ it('reads a layer with no transform as its box', () => {+ const layer = layerIn({+ layout: LAYOUT,+ matrix: [1, 0, 0, 1, 0, 0],+ origin: ORIGIN,+ });+ expect(edges(settledBox(layer))).toEqual(+ edges(new DOMRect(LAYOUT.left, LAYOUT.top, LAYOUT.width, LAYOUT.height)),+ );+ });++ it('reads an entering layer at its layout box, exactly, and writes no style', () => {+ const expected = edges(+ new DOMRect(LAYOUT.left, LAYOUT.top, LAYOUT.width, LAYOUT.height),+ );+ // Frames of the entrance: from 8 px below at 95% to rest.+ // Frames whose scale the box size tells apart from 1.+ for (const progress of [0, 0.0159, 0.1, 0.37, 0.5, 0.75]) {+ const scale = 0.95 + 0.05 * progress;+ const layer = layerIn({+ layout: LAYOUT,+ matrix: [scale, 0, 0, scale, 0, 8 * (1 - progress)],+ origin: ORIGIN,+ });+ const write = vi.spyOn(layer.style, 'setProperty');+ expect(edges(settledBox(layer)), `progress ${progress}`).toEqual(+ expected,+ );+ expect(write).not.toHaveBeenCalled();+ vi.restoreAllMocks();+ }+ });++ it('reads a layer that scales unevenly, or mirrors, at its layout box', () => {+ const layer = layerIn({+ layout: LAYOUT,+ matrix: [-0.9, 0, 0, 0.75, -3.25, 12.5],+ origin: [10, 4],+ });+ const write = vi.spyOn(layer.style, 'setProperty');+ expect(edges(settledBox(layer))).toEqual(+ edges(new DOMRect(LAYOUT.left, LAYOUT.top, LAYOUT.width, LAYOUT.height)),+ );+ expect(write).not.toHaveBeenCalled();+ });++ it('reads a rotated layer under a one-read override, and restores it', () => {+ const angle = (10 * Math.PI) / 180;+ const layer = layerIn({+ layout: LAYOUT,+ matrix: [+ Math.cos(angle),+ Math.sin(angle),+ -Math.sin(angle),+ Math.cos(angle),+ 0,+ 0,+ ],+ origin: ORIGIN,+ });+ expect(edges(settledBox(layer))).toEqual(+ edges(new DOMRect(LAYOUT.left, LAYOUT.top, LAYOUT.width, LAYOUT.height)),+ );+ expect(layer.style.getPropertyValue('transform')).toBe('');+ });++ it('reads a rotated layer that transitions its transform without a write, at its whole-pixel size', () => {+ const angle = (10 * Math.PI) / 180;+ const layer = layerIn({+ layout: LAYOUT,+ matrix: [+ Math.cos(angle),+ Math.sin(angle),+ -Math.sin(angle),+ Math.cos(angle),+ 0,+ 0,+ ],+ origin: ORIGIN,+ transition: {property: 'transform', duration: '0.2s'},+ });+ const write = vi.spyOn(layer.style, 'setProperty');+ const box = settledBox(layer);+ expect(write).not.toHaveBeenCalled();+ expect(box.width).toBe(Math.round(LAYOUT.width));+ expect(box.height).toBe(Math.round(LAYOUT.height));+ const centreX = LAYOUT.left + LAYOUT.width / 2;+ const centreY = LAYOUT.top + LAYOUT.height / 2;+ expect(box.left + box.width / 2).toBeCloseTo(centreX, 0);+ expect(box.top + box.height / 2).toBeCloseTo(centreY, 0);+ });++ describe('reads under the one-read override where calculation cannot undo the transform', () => {+ const entering = (): Engine => ({+ layout: LAYOUT,+ matrix: [0.95, 0, 0, 0.95, 0, 8],+ origin: ORIGIN,+ });+ const layoutEdges = () =>+ edges(new DOMRect(LAYOUT.left, LAYOUT.top, LAYOUT.width, LAYOUT.height));++ it('while its entrance is still pending', () => {+ const layer = layerIn(entering());+ layer.getAnimations = () => [{pending: true} as Animation];+ const write = vi.spyOn(layer.style, 'setProperty');+ expect(edges(settledBox(layer))).toEqual(layoutEdges());+ expect(write).toHaveBeenCalled();+ expect(layer.style.getPropertyValue('transform')).toBe('');+ });++ it('under a CSS zoom other than 1', () => {+ const layer = layerIn(entering());+ Object.defineProperty(layer, 'currentCSSZoom', {value: 2});+ const write = vi.spyOn(layer.style, 'setProperty');+ expect(edges(settledBox(layer))).toEqual(layoutEdges());+ expect(write).toHaveBeenCalled();+ });++ it('for a translate given as a percentage', () => {+ const layer = layerIn({...entering(), translate: '10% 0px'});+ const write = vi.spyOn(layer.style, 'setProperty');+ expect(edges(settledBox(layer))).toEqual(layoutEdges());+ expect(write).toHaveBeenCalled();+ });++ it('but not for a running entrance at a zoom of 1 with a translate in px', () => {+ const layer = layerIn({...entering(), translate: '0px 0px'});+ layer.getAnimations = () => [{pending: false} as Animation];+ Object.defineProperty(layer, 'currentCSSZoom', {value: 1});+ const write = vi.spyOn(layer.style, 'setProperty');+ expect(edges(settledBox(layer))).toEqual(layoutEdges());+ expect(write).not.toHaveBeenCalled();+ });+ });++ describe('reads under the override where the box read may not carry the transform', () => {+ const layoutEdges = () =>+ edges(new DOMRect(LAYOUT.left, LAYOUT.top, LAYOUT.width, LAYOUT.height));++ it('a box still laid out without the transform its computed style reports', () => {+ const layer = layerIn({+ layout: LAYOUT,+ matrix: [0.970033, 0, 0, 0.970033, 0, 4.79467],+ origin: ORIGIN,+ stale: true,+ });+ layer.getAnimations = () => [{pending: false} as Animation];+ const write = vi.spyOn(layer.style, 'setProperty');+ expect(edges(settledBox(layer))).toEqual(layoutEdges());+ expect(write).toHaveBeenCalled();+ });++ it('a scale too near 1 for the box size to show', () => {+ const scale = 0.95 + 0.05 * 0.999;+ const layer = layerIn({+ layout: LAYOUT,+ matrix: [scale, 0, 0, scale, 0, 8 * 0.001],+ origin: ORIGIN,+ });+ const write = vi.spyOn(layer.style, 'setProperty');+ expect(edges(settledBox(layer))).toEqual(layoutEdges());+ expect(write).toHaveBeenCalled();+ });+ });++ it('reads a transitioned layer whose only transform is a one-value translate', () => {+ // Chromium reports `translate: 8px 0px` as `8px`.+ const layer = layerIn({+ layout: LAYOUT,+ matrix: [1, 0, 0, 1, 8, 0],+ origin: ORIGIN,+ translate: '8px',+ translateOnly: true,+ transition: {property: 'transform', duration: '200ms'},+ });+ const write = vi.spyOn(layer.style, 'setProperty');+ expect(edges(settledBox(layer))).toEqual(+ edges(new DOMRect(LAYOUT.left, LAYOUT.top, LAYOUT.width, LAYOUT.height)),+ );+ expect(write).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/Layer/settledBox.ts b/packages/core/src/Layer/settledBox.tsindex fe142a4428..ec0d239731 100644--- a/packages/core/src/Layer/settledBox.ts+++ b/packages/core/src/Layer/settledBox.ts@@ -17,6 +17,23 @@const TRANSFORM_PROPERTIES = ['transform', 'translate', 'scale', 'rotate'];+/** A 2D affine matrix in the order CSS `matrix()` lists it: a, b, c, d, e, f. */+type Matrix2D = readonly [number, number, number, number, number, number];++const IDENTITY: Matrix2D = [1, 0, 0, 1, 0, 0];++/**+ * Chromium and WebKit place layout boxes on a 1/64 px grid. The computed+ * transform keeps six digits, so a derived edge can miss that grid by+ * millionths of a px. An edge that close moves onto the grid. Firefox uses a+ * 1/60 px grid, so its edges stay as derived.+ */+const LAYOUT_UNITS_PER_PX = 64;+const GRID_TOLERANCE_PX = 1 / 2048;++/** How much nearer the scaled size must be, px, for the box to carry it. */+const SCALE_TOLERANCE_PX = 1 / 32;+function hasTransform(style: CSSStyleDeclaration): boolean {return TRANSFORM_PROPERTIES.some(name => {const value = style.getPropertyValue(name);@@ -24,63 +41,189 @@ function hasTransform(style: CSSStyleDeclaration): boolean {});}+function isSet(value: string): boolean {+ return value !== '' && value !== 'none';+}++function multiply(m: Matrix2D, n: Matrix2D): Matrix2D {+ return [+ m[0] * n[0] + m[2] * n[1],+ m[1] * n[0] + m[3] * n[1],+ m[0] * n[2] + m[2] * n[3],+ m[1] * n[2] + m[3] * n[3],+ m[0] * n[4] + m[2] * n[5] + m[4],+ m[1] * n[4] + m[3] * n[5] + m[5],+ ];+}+/**- * `rect`, the box of an element whose computed style still carries a 2D- * transform, with that transform undone. The transformed box's centre is the- * image of the element's centre. So undoing the transform about its origin on- * that centre gives the untransformed box, at the element's layout size. A- * transform this cannot undo (3D, or a rotation in another unit) leaves `rect`- * as it is.+ * The element's whole 2D transform, as one matrix, or null for a transform+ * this cannot read (3D, or a rotation in another unit). The individual+ * transform properties apply before `transform`, in this order (CSS+ * Transforms 2). An engine reports a computed `transform` as `matrix()`.*/-function untransform(- rect: DOMRect,- layer: HTMLElement,- style: CSSStyleDeclaration,-): DOMRect {- const set = (value: string) => value !== '' && value !== 'none';- if (typeof DOMMatrix === 'undefined' || layer.offsetWidth <= 0) {- return rect;- }- // The individual transform properties apply before `transform`, in this- // order (CSS Transforms 2).- let matrix = new DOMMatrix();- if (set(style.translate)) {- const [x = '0', y = '0', z] = style.translate.split(' ');- if (z != null) {- return rect;+function transformOf(style: CSSStyleDeclaration): Matrix2D | null {+ const translate = style.getPropertyValue('translate');+ const rotate = style.getPropertyValue('rotate');+ const scale = style.getPropertyValue('scale');+ const transform = style.getPropertyValue('transform');+ let matrix = IDENTITY;+ if (isSet(translate)) {+ const [x = '0', y = '0', z] = translate.split(' ');+ // The computed `translate` keeps a percentage, which is not a length.+ if (+ z != null ||+ !translate.split(' ').every(value => value.endsWith('px'))+ ) {+ return null;}- matrix = matrix.translate(parseFloat(x), parseFloat(y));+ matrix = multiply(matrix, [1, 0, 0, 1, parseFloat(x), parseFloat(y)]);}- if (set(style.rotate)) {- if (!/^-?[\d.]+deg$/.test(style.rotate)) {- return rect;+ if (isSet(rotate)) {+ if (!/^-?[\d.]+deg$/.test(rotate)) {+ return null;}- matrix = matrix.rotate(parseFloat(style.rotate));+ const angle = (parseFloat(rotate) * Math.PI) / 180;+ const cos = Math.cos(angle);+ const sin = Math.sin(angle);+ matrix = multiply(matrix, [cos, sin, -sin, cos, 0, 0]);}- if (set(style.scale)) {- const [x = '1', y = x, z] = style.scale.split(' ');+ if (isSet(scale)) {+ const [x = '1', y = x, z] = scale.split(' ');if (z != null) {- return rect;+ return null;}- matrix = matrix.scale(parseFloat(x), parseFloat(y));+ matrix = multiply(matrix, [parseFloat(x), 0, 0, parseFloat(y), 0, 0]);}- if (set(style.transform)) {- matrix = matrix.multiply(new DOMMatrix(style.transform));+ if (isSet(transform)) {+ const listed = /^matrix\(([^)]*)\)$/.exec(transform);+ const values = listed?.[1].split(',').map(value => parseFloat(value));+ if (values?.length !== 6 || values.some(value => Number.isNaN(value))) {+ return null;+ }+ matrix = multiply(matrix, values as unknown as Matrix2D);}- if (!matrix.is2D) {+ return matrix;+}++/**+ * Whether the matrix only translates and scales: the box keeps its edges+ * parallel to the axes, and its layout size is its transformed size over the+ * scale.+ */+function isAxisAligned([a, b, c, d]: Matrix2D): boolean {+ return b === 0 && c === 0 && a !== 0 && d !== 0;+}++/**+ * Whether the layer's transform can be taken out of its box by calculation.+ * Not while one of its animations is pending: Chromium can then report the+ * first keyframe before the box carries it. Not under a CSS zoom other than 1:+ * the computed translation and origin are then in the layer's own px, not in+ * the box's.+ */+function canUndoByCalculation(layer: HTMLElement): boolean {+ const zoom = (layer as {currentCSSZoom?: number}).currentCSSZoom ?? 1;+ if (zoom !== 1) {+ return false;+ }+ return !(layer.getAnimations?.() ?? []).some(animation => animation.pending);+}++/** The layer's border-box size in layout px, unrounded, from its used size. */+function layoutSize(style: CSSStyleDeclaration): {+ width: number;+ height: number;+} {+ const px = (name: string) => parseFloat(style.getPropertyValue(name)) || 0;+ const isContentBox = style.getPropertyValue('box-sizing') !== 'border-box';+ const extra = (sides: [string, string]) =>+ isContentBox+ ? sides.reduce(+ (sum, side) =>+ sum + px(`padding-${side}`) + px(`border-${side}-width`),+ 0,+ )+ : 0;+ return {+ width: px('width') + extra(['left', 'right']),+ height: px('height') + extra(['top', 'bottom']),+ };+}++/**+ * Whether the box read carries the scale of `matrix`. Right after a layer+ * shows, Chromium can report its entrance's first frame in the computed style+ * while the box read is still laid out without it. The box carries the scale+ * only when its size is clearly nearer the layout size times the scale than+ * the layout size itself. A scale too near 1 to tell them apart does not+ * count.+ */+function carriesScale(+ rect: DOMRect,+ style: CSSStyleDeclaration,+ [a, , , d]: Matrix2D,+): boolean {+ const {width, height} = layoutSize(style);+ if (!(width > 0) || !(height > 0)) {+ return false;+ }+ const scaledError =+ Math.abs(rect.width - width * Math.abs(a)) ++ Math.abs(rect.height - height * Math.abs(d));+ const unscaledError =+ Math.abs(rect.width - width) + Math.abs(rect.height - height);+ return scaledError + SCALE_TOLERANCE_PX < unscaledError;+}++function onLayoutGrid(value: number): number {+ const snapped = Math.round(value * LAYOUT_UNITS_PER_PX) / LAYOUT_UNITS_PER_PX;+ return Math.abs(snapped - value) < GRID_TOLERANCE_PX ? snapped : value;+}++/**+ * `rect`, the box of an element whose computed style carries the 2D transform+ * `matrix`, with that transform undone. The transformed box's centre is the+ * image of the element's centre. So undoing the transform about its origin on+ * that centre gives the untransformed box. A box that only translates and+ * scales gets its layout size from the transformed size, exactly, and needs+ * no other read. Any other box takes its layout size from `offsetWidth` and+ * `offsetHeight`, which round to whole pixels.+ */+function untransform(+ rect: DOMRect,+ layer: HTMLElement,+ style: CSSStyleDeclaration,+ matrix: Matrix2D,+): DOMRect {+ const [a, b, c, d, e, f] = matrix;+ const isExact = isAxisAligned(matrix);+ const width = isExact ? rect.width / Math.abs(a) : layer.offsetWidth;+ const height = isExact ? rect.height / Math.abs(d) : layer.offsetHeight;+ if (!isExact && width <= 0) {return rect;}- const [originX = 0, originY = 0] = style.transformOrigin+ const [originX = 0, originY = 0] = style+ .getPropertyValue('transform-origin').split(' ').map(value => parseFloat(value));- const width = layer.offsetWidth;- const height = layer.offsetHeight;- const centre = matrix.transformPoint(- new DOMPoint(width / 2 - originX, height / 2 - originY),+ const x = width / 2 - originX;+ const y = height / 2 - originY;+ const centreX = a * x + c * y + e;+ const centreY = b * x + d * y + f;+ const left = rect.left + rect.width / 2 - centreX - originX;+ const top = rect.top + rect.height / 2 - centreY - originY;+ if (!isExact) {+ return new DOMRect(left, top, width, height);+ }+ const snappedLeft = onLayoutGrid(left);+ const snappedTop = onLayoutGrid(top);+ return new DOMRect(+ snappedLeft,+ snappedTop,+ onLayoutGrid(left + width) - snappedLeft,+ onLayoutGrid(top + height) - snappedTop,);- const left = rect.left + rect.width / 2 - centre.x - originX;- const top = rect.top + rect.height / 2 - centre.y - originY;- return new DOMRect(left, top, width, height);}/**@@ -88,14 +231,15 @@ function untransform(* entry animation (or anything else) applies to it. A Tooltip enters from a* few pixels toward its trigger, scaled down. So the transformed box of a* tooltip that fits beside its trigger can read as covering it while it- * enters. For this one read, the layer's transforms are overridden with- * `none !important`, which outranks an animation. They are restored in the- * same task, so no frame paints in between and the animation keeps running.- * Where the engine still applies an animated transform under that override- * (WebKit), the read box has that transform undone instead (`untransform`). A- * layer that transitions a transform property is not overridden, since- * restoring the value would start that transition. Its box has its transform- * undone.+ * enters. When the transform only translates and scales, `untransform` takes+ * it out of one box read, if `canUndoByCalculation` and `carriesScale` allow+ * it. Nothing is written, so the read forces no extra style or layout work.+ * A layer that transitions a transform is also only read: restoring an+ * overridden value would start that transition. Otherwise one read overrides+ * the layer's transforms with `none !important`, which outranks an animation.+ * The same task restores them, so no frame paints in between and the+ * animation keeps running. WebKit still applies an animated transform under+ * that override, so there the read box has that transform undone instead.*/export function settledBox(layer: HTMLElement): DOMRect {const view = layer.ownerDocument.defaultView;@@ -103,15 +247,29 @@ export function settledBox(layer: HTMLElement): DOMRect {if (style == null || !hasTransform(style)) {return layer.getBoundingClientRect();}- const transitions = style.transitionProperty.split(',').map(p => p.trim());- const durations = style.transitionDuration.split(',').map(parseFloat);+ const matrix = transformOf(style);+ if (matrix != null && isAxisAligned(matrix) && canUndoByCalculation(layer)) {+ const rect = layer.getBoundingClientRect();+ if (carriesScale(rect, style, matrix)) {+ return untransform(rect, layer, style, matrix);+ }+ }+ const transitions = style+ .getPropertyValue('transition-property')+ .split(',')+ .map(p => p.trim());+ const durations = style+ .getPropertyValue('transition-duration')+ .split(',')+ .map(parseFloat);const transitioned = transitions.some((name, index) =>(name === 'all' || TRANSFORM_PROPERTIES.includes(name)) &&(durations[index % durations.length] ?? 0) > 0,);if (transitioned) {- return untransform(layer.getBoundingClientRect(), layer, style);+ const rect = layer.getBoundingClientRect();+ return matrix == null ? rect : untransform(rect, layer, style, matrix);}const saved = TRANSFORM_PROPERTIES.map(name =>@@ -126,8 +284,12 @@ export function settledBox(layer: HTMLElement): DOMRect {}const box = layer.getBoundingClientRect();const under = view?.getComputedStyle(layer);+ const underMatrix =+ under != null && hasTransform(under) ? transformOf(under) : null;const settled =- under != null && hasTransform(under) ? untransform(box, layer, under) : box;+ under != null && underMatrix != null+ ? untransform(box, layer, under, underMatrix)+ : box;for (const [name, value, priority] of saved) {if (value === '') {layer.style.removeProperty(name);diff --git a/packages/core/src/Tooltip/__tests__/TooltipTallContent.a11y.browser.spec.ts b/packages/core/src/Tooltip/__tests__/TooltipTallContent.a11y.browser.spec.tsindex a65371c7a9..3d6a110acd 100644--- a/packages/core/src/Tooltip/__tests__/TooltipTallContent.a11y.browser.spec.ts+++ b/packages/core/src/Tooltip/__tests__/TooltipTallContent.a11y.browser.spec.ts@@ -227,19 +227,22 @@ async function openReplacedTrigger(page: Page): Promise<number> {/*** Open the TallContent story at a viewport, scroll the trigger's centre to* `triggerY`, rest the pointer on the trigger and wait for the tooltip.- * Returns how many times the tooltip toggled.+ * Motion is held still unless `motion` is 'allowed'.*/async function hoverTallTrigger(page: Page,viewport: {width: number; height: number},triggerY: number,args = '',+ motion: 'still' | 'allowed' = 'still',) {await page.setViewportSize(viewport);await page.goto(`${storybook.origin}/iframe.html?id=core-tooltip--tall-content&viewMode=story${args ? `&args=${args}` : ''}`,);- await holdMotionStill(page);+ if (motion === 'still') {+ await holdMotionStill(page);+ }const trigger = page.getByRole('button', {name: 'Hover for details'});await expect(trigger).toBeVisible();await page.evaluate(@@ -341,6 +344,25 @@ test('desktop: a tall tooltip opens beside its trigger and stays open', async ({await expectScrollsInside(page);});+test('desktop, with motion allowed: a tall tooltip opens beside its trigger, and no frame of its entrance covers the trigger', async ({+ page,+}) => {+ // The reads while the tooltip enters take its entrance transform out. No+ // frame of the entrance paints it over its trigger.+ const viewport = {width: 1280, height: 720};+ const {trigger} = await hoverTallTrigger(page, viewport, 360, '', 'allowed');+ await page.waitForTimeout(500);+ const s = await expectStillAndClear(page, trigger, viewport);+ expect(s.left >= trigger.right || s.right <= trigger.left).toBe(true);+ expect(+ await page.evaluate(+ sel =>+ document.querySelector(sel)?.hasAttribute('data-astryx-clears-anchor'),+ TOOLTIP,+ ),+ ).toBe(true);+});+test('phone: with no room beside, it opens below when below has more room', async ({page,}) => {