Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(core): a block-edge reveal slides its parts on the glide's frames (#10296)

Christopher Chedeau0ecd324bf656
diff --git a/.changeset/edge-reveal-slide.md b/.changeset/edge-reveal-slide.md
new file mode 100644
index 0000000000..97cbe7eaa6
--- /dev/null
+++ b/.changeset/edge-reveal-slide.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A block-edge reveal or conceal, as in Collapsible, TreeList and Table's row expansion with an `animatedLayout` handle, now slides the revealed element's children on the same frames as the content beside it, under a still clip on the element's box. An element that paints its own box, such as Table's `panelVariant="muted"` panel, keeps the moving clip. On iOS Safari a moving clip ran on its own clock and parted from that content for a few frames; now the two stay together. The glide's timing and curve are unchanged. Collapsible's region now wraps its children in one inner element; selectors like `region > *` or `:first-child` on the region's children need updating.
+
+@vjeux
diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.md
index b72b3f7d65..39838da9af 100644
--- a/docs/architecture/react-component-runtime.md
+++ b/docs/architecture/react-component-runtime.md
@@ -234,7 +234,11 @@ those contracts.
sibling outside the band the changes in a frame can bring into view (the
area's visible part plus one viewport, or the changed elements' summed size
if larger, above and below), so its cost grows with depth plus the
- siblings near the visible part, never with the length of a list. Where the
+ siblings near the visible part, never with the length of a list. A block
+ edge's reveal or conceal also moves the changed element's own child
+ elements that the band can show, each on the glide's frames under a fixed
+ clip on that element's box, so that cost grows with the changed size, never
+ with the length of a list. Where the
scroll container opts out of scroll anchoring, a change above the band
walks forward to the band; that cost grows with the distance. In a
container whose children run across the block direction (multi-column, a
@@ -529,7 +533,7 @@ component suite is not blanket conformance with every invariant.
| INV9 | Provider/external-store identity and render-count tests | Unchanged semantic payload changes identity, or snapshot identity creates a render loop |
| INV10 | Shared test over every adopter of the announcement module | An adopter holding its own Effect, observer, timer, or listener for its own-content announcement |
| INV11 | Source boundary check plus hook tests across StrictMode replay and unmount | A second keyboard listener or measurement in Core; a consumer reading a CSS custom property on the root or a shared ancestor for the height; an export of the hook; a component outside Core measuring by a rule other than AST-099 FR2, or riding the keyboard; a listener left after unmount; a translate left on an app element after the keyboard hides once focus has left the field, or after the field unmounts; any other write on an app element; a translate on a container whose layout box is not at the bottom edge, that fills the viewport, or whose own `translate` is not `none`; a translate on a container whose position the app is animating with CSS when the module measures; on a docked container too tall to fit above the keyboard once moved (a full-height side drawer, a pane below a fixed header), a translate when a scroller holds the field or one larger than the focused field needs to clear the keyboard; a translate measured before the page's own keyboard listeners run; a covered field deciding its keyboard behavior in an Effect that reacts to focus; a Core rider driven by JavaScript per frame or by its own transition; or more than one layout read per keyboard change beyond the docked bar's one read INV11 names |
-| INV12 | Source boundary check plus real-browser tests on a throttled phone profile over a 10-level by 50-sibling tree and two changes in one frame | A per-frame height or layout, a walk past the area or into a subtree other than `display: contents`, an element moved twice for one frame, an added element other than a swap's one transient copy, that copy left after the swap ends, or an exported reporting function fails |
+| INV12 | Source boundary check plus real-browser tests on a throttled phone profile over a 10-level by 50-sibling tree and two changes in one frame | A per-frame height or layout, a walk past the area or into a subtree other than `display: contents`, an element moved twice for one frame, an added element other than a swap's one transient copy, that copy left after the swap ends, an exported reporting function, a slide that moves a child outside the band, or a moving clip on an element whose parts slide fails |
| INV13 | Source boundary check plus bundle analysis of a page with several touch components, and real-browser tests on a throttled phone profile, under a fine pointer, and on a hybrid device | A second copy of a touch module on one page, a component bundling its own copy of a module's primitive, an `import()` of a module in a component other than `Item`'s released loader for its deprecated swipe props, a swipe module (the gesture core, the animator, the panels' rendering, the row's gesture code) imported by `Item` or `ListItem`, swipe code in `Item` other than its deprecated path (that loader, the released row style, the role gate, the `commit` warning, the bridge, the click guard, the event forwarders, and the coexistence diagnostic), or any of it outside the deprecated path, a public export or doc entry for the modules, an install call or installed check in the public API, a gesture listener in a component that uses no gesture, or an idle document listener outside a press other than the one shared press controller and the one stray-click swallower, an import of `@astryxdesign/core/internal/*` outside Core and Lab, a class outside the recognizer family, an `instanceof` check on a recognizer, an internal factory with a public factory's name, or a direct module import for a job the public layer covers fails |
| INV15 | Unit tests of the animator's value mode and real-browser proofs of its adopters | A value off its channels' timing (the theme's tokens for a program-started change, a spring only where `spec:AST-094` FR45 keeps one), a count past the component's swap size, a count or cross-fade under reduced motion with a coarse or a fine pointer, an intermediate value announced, or a public export fails |
| INV16 | Review of each Core component that handles a concern Core owns in a shared hook or utility | A Core component that keeps its own effect, listener, or tracker for that concern fails, whether or not it also calls the hook or utility |
diff --git a/docs/specs/AST-105-animated-layout/spec.md b/docs/specs/AST-105-animated-layout/spec.md
index beabc58659..b9330b3fa2 100644
--- a/docs/specs/AST-105-animated-layout/spec.md
+++ b/docs/specs/AST-105-animated-layout/spec.md
@@ -135,7 +135,12 @@ const animatedLayout = useAnimatedLayout({containerRef: scrollRef});
measures any change, and the element's moving edge and the content on that
edge's side move on FR4's one motion, whether that content comes after the
element or before it (an end panel's LayoutContent comes before the panel),
- so the content beside the edge glides with it and no gap opens. An optional
+ so the content beside the edge glides with it and no gap opens. In a
+ block-edge form, the element's own child elements slide on that motion under
+ a still clip at its content box on the side its parts enter from, so they
+ enter and leave at the moving edge; an element with text of its own, a child
+ that a translation cannot move, or a box or generated box of its own that it
+ paints, keeps a clip that moves with the edge. An optional
two-state form holds the element's old state as FR8's swap holds it, while
the element rides the glide of the content beside its moving edge; a reversal
from the shown state starts from where it is. Under Reduce Motion it follows
diff --git a/docs/specs/components/Collapsible/Collapsible.spec.md b/docs/specs/components/Collapsible/Collapsible.spec.md
index 3d76cbacaf..584e98f1f2 100644
--- a/docs/specs/components/Collapsible/Collapsible.spec.md
+++ b/docs/specs/components/Collapsible/Collapsible.spec.md
@@ -115,6 +115,10 @@ not parallel public names for this axis.
- **AV4 — Existing non-chevron behavior.** Open-state ownership, disabled behavior,
divider/density presentation, content layout, and reveal motion remain governed
by their existing authority and are not changed by this decision.
+- **AV5 — Internal region element.** The content region always wraps its
+ children in one inner element, so an edge reveal or conceal slides them
+ under the region's clip (`spec:AST-105` FR9). The element is internal: it is
+ not a styling target or a promised structure.
### Representative states
diff --git a/docs/specs/components/Table/Table.spec.md b/docs/specs/components/Table/Table.spec.md
index e6a731008d..7688f00cb2 100644
--- a/docs/specs/components/Table/Table.spec.md
+++ b/docs/specs/components/Table/Table.spec.md
@@ -253,6 +253,10 @@ Consumer data, columns, props, module signatures and usage remain documented in
positions of the gliding row, the two parts round to different pixels. The step
lasts only while the row glides; at rest the divider is level. This contract
records the gap and does not correct it.
+- An expanded panel row with `panelVariant="muted"` paints its own box and
+ keeps the moving clip, so on iOS WebKit it can drift from the rows below for a
+ few frames; AST-105 FR9's slide doesn't apply to an element that paints its
+ own box.
### Allowed variation
diff --git a/packages/core/src/Collapsible/Collapsible.tsx b/packages/core/src/Collapsible/Collapsible.tsx
index ce2300bb91..d38788c950 100644
--- a/packages/core/src/Collapsible/Collapsible.tsx
+++ b/packages/core/src/Collapsible/Collapsible.tsx
@@ -593,13 +593,17 @@ export function Collapsible({
!isOpen && !isExiting && styles.contentHidden,
),
)}>
- {presentation != null ? (
- <CollapsibleGroupPresentationContext value={null}>
- {children}
- </CollapsibleGroupPresentationContext>
- ) : (
- children
- )}
+ {/* One box holds the content, so an opening or closing slides it
+ under the region's clip: a translation cannot move bare text. */}
+ <div>
+ {presentation != null ? (
+ <CollapsibleGroupPresentationContext value={null}>
+ {children}
+ </CollapsibleGroupPresentationContext>
+ ) : (
+ children
+ )}
+ </div>
</div>
</div>
);
diff --git a/packages/core/src/Table/__tests__/TableRowGlide.a11y.browser.spec.ts b/packages/core/src/Table/__tests__/TableRowGlide.a11y.browser.spec.ts
index f387b95611..cc37b5e509 100644
--- a/packages/core/src/Table/__tests__/TableRowGlide.a11y.browser.spec.ts
+++ b/packages/core/src/Table/__tests__/TableRowGlide.a11y.browser.spec.ts
@@ -206,6 +206,25 @@ test('mid-glide each divider moves with its row, pinned cells included', async (
}
});
+test("mid-open the panel's divider rides its cell's bottom", async ({page}) => {
+ await mount(page, 'gliding-rows');
+ expect(await toggleAndHold(page, 0, 90)).toBeGreaterThan(0);
+ // The panel's one cell, where it shows now: the line under it moves with
+ // its bottom. A line left where the cell was measured mid-slide is cut off.
+ const cell = await page.evaluate(() => {
+ const box = document
+ .querySelector('tr[data-expansion-panel] > td')
+ ?.getBoundingClientRect();
+ return box == null
+ ? null
+ : {x: Math.round((box.left + box.right) / 2), y: Math.round(box.bottom)};
+ });
+ expect(cell, 'the panel cell').not.toBeNull();
+ expect((await darkestNear(page, cell?.x ?? 0, cell?.y ?? 0))[0]).toBeLessThan(
+ 248,
+ );
+});
+
test("a theme's divider and an app's override move with their rows, pinned cells included", async ({
page,
}) => {
diff --git a/packages/core/src/Table/glidingDivider.ts b/packages/core/src/Table/glidingDivider.ts
index 7bb8caa1ac..1c9070183a 100644
--- a/packages/core/src/Table/glidingDivider.ts
+++ b/packages/core/src/Table/glidingDivider.ts
@@ -6,8 +6,9 @@
* computed borders, StyleX
* @output Exports `glidingDividerStyles` (a row's stand-in divider while it
* glides), `markGlidingRows` (marks the moving rows for that glide and
- * carries each row's own border onto the stand-in), `rowEdge`, and the
- * row and pinned-cell attribute names plugins/stickyColumns reads
+ * carries each row's own border onto the stand-in), `rowEdge`,
+ * `dividerOffset`, and the row and pinned-cell attribute names
+ * plugins/stickyColumns reads
* @position Table internals. With collapsed borders the table paints every
* border at its cell's static place, so a row that moves leaves its divider
* behind. For the glide only, the moving row's cells are marked: their
@@ -179,6 +180,25 @@ export function rowEdge(row: Element): BottomEdge | null {
return collapsedBottom(row.lastElementChild as HTMLTableCellElement);
}
+/**
+ * How far `row`'s divider hangs from the bottom of the row's padding box. The
+ * line hangs from that padding box (its containing block), which a row's own
+ * border shortens. The collapsed edge starts at a cell's padding-box bottom,
+ * which a wide border puts below it. The table paints that edge from the
+ * whole pixel at or above it, so the line starts there too.
+ */
+export function dividerOffset(row: Element, edge: BottomEdge): number | null {
+ const cell = row.lastElementChild;
+ if (!(cell instanceof HTMLElement)) {
+ return null;
+ }
+ const cellEdge =
+ cell.getBoundingClientRect().top + cell.clientTop + cell.clientHeight;
+ const rowPaddingEdge =
+ row.getBoundingClientRect().top + row.clientTop + row.clientHeight;
+ return Math.floor(cellEdge) + edge.width - rowPaddingEdge;
+}
+
/**
* Marks the rows a glide is moving around `changed`, and `entering` (a row
* playing its entrance, with that entrance), so their cells draw a divider
@@ -187,13 +207,18 @@ export function rowEdge(row: Element): BottomEdge | null {
* visible part, so this walks out from the changed row each way and stops at
* still rows: it never visits the rest of a long table. It asks the motion
* module which rows glide and takes the borders read before the glide
- * started (`edges`), so it reads nothing from the layout: it only writes.
+ * started (`edges`). It reads each row's divider offset before it writes.
* Resolves when the motion has ended.
*/
export async function markGlidingRows(
changed: HTMLElement,
edges: ReadonlyMap<Element, BottomEdge>,
- entering: {row: HTMLElement; animation: Animation} | null,
+ entering: {
+ row: HTMLElement;
+ animation: Animation;
+ /** Its divider's offset, read before its entrance moved its cell. */
+ offset?: number | null;
+ } | null,
glideOf: (element: Element) => Animation | null,
): Promise<void> {
const rows = new Map<HTMLElement, Animation | null>();
@@ -226,23 +251,20 @@ export async function markGlidingRows(
return;
}
const batch = Symbol('glide');
- // Where each row's divider rests, read before any write. The line hangs
- // from the row's padding box (its containing block), which a row's own
- // border shortens; the collapsed edge starts at a cell's padding-box
- // bottom, which a wide border puts below it. The table paints that edge
- // from the whole pixel at or above it, so the line starts there too.
+ // Where each row's divider rests, read before any write.
const offsets = new Map<Element, number>();
for (const row of rows.keys()) {
const edge = edges.get(row);
- const cell = row.lastElementChild;
- if (edge == null || !(cell instanceof HTMLElement)) {
+ if (edge == null) {
continue;
}
- const cellEdge =
- cell.getBoundingClientRect().top + cell.clientTop + cell.clientHeight;
- const rowPaddingEdge =
- row.getBoundingClientRect().top + row.clientTop + row.clientHeight;
- offsets.set(row, Math.floor(cellEdge) + edge.width - rowPaddingEdge);
+ const offset =
+ row === entering?.row && entering.offset != null
+ ? entering.offset
+ : dividerOffset(row, edge);
+ if (offset != null) {
+ offsets.set(row, offset);
+ }
}
for (const row of rows.keys()) {
const edge = edges.get(row);
diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
index 949994e1d5..f5cdb9c4d7 100644
--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
@@ -68,6 +68,7 @@ import {
type LayoutChange,
} from '../../../motion/animatedLayout';
import {
+ dividerOffset,
GLIDING_ATTRIBUTE,
glidingDividerStyles,
markGlidingRows,
@@ -765,6 +766,7 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
row: HTMLElement;
panel: HTMLElement | null;
entrance: Animation | null;
+ panelOffset: number | null;
edges: Map<Element, BottomEdge>;
}[] = [];
for (const pending of pendings) {
@@ -784,6 +786,7 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
? next
: null,
entrance: null as Animation | null,
+ panelOffset: null as number | null,
edges: new Map<Element, BottomEdge>(),
};
// Read where the glide reads the layout, before anything moves: the
@@ -804,6 +807,8 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
const edge = rowEdge(record.panel);
if (edge != null) {
record.edges.set(record.panel, edge);
+ // Its entrance moves its cell: read where its line hangs first.
+ record.panelOffset = dividerOffset(record.panel, edge);
}
record.entrance = playLayoutChange(animatedLayout, record.panel);
}
@@ -831,12 +836,12 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
// one runs after it, before the frame paints, and only writes.
queueMicrotask(() => {
const stopped = Promise.all(
- moved.map(async ({row, panel, entrance, edges}) =>
+ moved.map(async ({row, panel, entrance, panelOffset, edges}) =>
markGlidingRows(
row,
edges,
panel != null && entrance != null
- ? {row: panel, animation: entrance}
+ ? {row: panel, animation: entrance, offset: panelOffset}
: null,
glideOf,
),
diff --git a/packages/core/src/motion/__tests__/animatedLayoutAdopters.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animatedLayoutAdopters.interaction.browser.spec.ts
index a591d4790e..7ef0900036 100644
--- a/packages/core/src/motion/__tests__/animatedLayoutAdopters.interaction.browser.spec.ts
+++ b/packages/core/src/motion/__tests__/animatedLayoutAdopters.interaction.browser.spec.ts
@@ -155,6 +155,24 @@ async function edgeRide(
? (parseFloat(b) / 100) * box.height
: parseFloat(b);
};
+ // A block edge's reveal slides the element's parts under a still clip:
+ // the first part's slide, on its own clock, says how much is hidden.
+ const slideOf = (element: HTMLElement) =>
+ element.firstElementChild
+ ?.getAnimations()
+ .filter(a =>
+ (a.effect as KeyframeEffect)
+ .getKeyframes()
+ .some(k => k.translate != null),
+ )
+ .at(-1) ?? null;
+ const slidHidden = (slide: Animation) => {
+ const frames = (slide.effect as KeyframeEffect).getKeyframes();
+ const {i, f} = bracket(frames, at(slide));
+ const y0 = y(frames[i].translate);
+ const y1 = y(frames[i + 1].translate);
+ return Math.max(0, -(y0 + (y1 - y0) * f));
+ };
const insetBottom = (element: HTMLElement) => {
const box = element.getBoundingClientRect();
const animation = element
@@ -166,7 +184,10 @@ async function edgeRide(
)
.at(-1);
if (animation == null) {
- return bottomOf(getComputedStyle(element).clipPath, box);
+ const slide = slideOf(element);
+ return slide == null
+ ? bottomOf(getComputedStyle(element).clipPath, box)
+ : slidHidden(slide);
}
const frames = (animation.effect as KeyframeEffect).getKeyframes();
const {i, f} = bracket(frames, at(animation));
@@ -260,15 +281,22 @@ async function edgeRide(
animation.currentTime = 120;
}
read('reversed');
- const clipOf = () =>
- content()
- ?.getAnimations()
- .filter(a =>
- (a.effect as KeyframeEffect)
- .getKeyframes()
- .some(k => k.clipPath != null),
- )
- .at(-1) ?? null;
+ const clipOf = () => {
+ const element = content();
+ if (element == null) {
+ return null;
+ }
+ return (
+ element
+ .getAnimations()
+ .filter(a =>
+ (a.effect as KeyframeEffect)
+ .getKeyframes()
+ .some(k => k.clipPath != null),
+ )
+ .at(-1) ?? slideOf(element)
+ );
+ };
const opening = clipOf();
button.click();
// Until the close commits (a component may commit its state in a later
@@ -285,7 +313,10 @@ async function edgeRide(
const concealStart =
start == null
? Number.NaN
- : startBox.height - bottomOf(start.clipPath, startBox);
+ : startBox.height -
+ (start.clipPath == null
+ ? Math.max(0, -y(start.translate))
+ : bottomOf(start.clipPath, startBox));
for (const animation of document.getAnimations()) {
if (animation.playState === 'paused') {
animation.play();
@@ -456,7 +487,18 @@ test.describe('component:Collapsible FR10 and component:TreeList FR9 (spec:AST-1
)
.at(-1);
if (animation == null) {
- return bottomOf(getComputedStyle(element).clipPath, height);
+ // A slide: the first part's translate on its own clock.
+ const slide = element.firstElementChild
+ ?.getAnimations()
+ .filter(a =>
+ (a.effect as KeyframeEffect)
+ .getKeyframes()
+ .some(k => k.translate != null),
+ )
+ .at(-1);
+ return slide == null
+ ? bottomOf(getComputedStyle(element).clipPath, height)
+ : Math.max(0, -glideY(element.firstElementChild as HTMLElement));
}
const effect = animation.effect as KeyframeEffect;
const frames = effect.getKeyframes();
diff --git a/packages/core/src/motion/__tests__/animatedLayoutRevealPaint.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animatedLayoutRevealPaint.interaction.browser.spec.ts
new file mode 100644
index 0000000000..ed644cb31f
--- /dev/null
+++ b/packages/core/src/motion/__tests__/animatedLayoutRevealPaint.interaction.browser.spec.ts
@@ -0,0 +1,462 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @input The Animated layout story's Collapsible and TreeList, opened and
+ * closed in a real browser.
+ * @output Real-browser tests of what an edge reveal paints on every frame:
+ * the revealed content's shown edge, as the engine evaluates it, against the
+ * content after it.
+ * @position Beside `animatedLayoutAdopters.interaction.browser.spec.ts`, which
+ * reads the same edge on the module's clock from keyframes. This one reads
+ * evaluated boxes and clips, where an engine that paints a clip on its own
+ * clock parts the two.
+ */
+
+import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer | undefined;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+const STORY = 'core-animated-layout--animated-layout';
+
+async function openStory(page: Page): Promise<void> {
+ await page.goto(
+ `${storybook?.origin ?? ''}/iframe.html?id=${STORY}&viewMode=story`,
+ );
+ await page
+ .locator('#storybook-root > *')
+ .first()
+ .waitFor({state: 'attached'});
+ await page.evaluate(async () => {
+ await document.fonts.ready;
+ await new Promise<void>(resolve => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ });
+ });
+}
+
+interface PaintedFrame {
+ phase: 'opening' | 'closing';
+ /** From the shown edge of the revealed content to the content after it. */
+ gap: number;
+ /** How much of the revealed content shows. */
+ shown: number;
+}
+
+interface PaintedRide {
+ frames: PaintedFrame[];
+ /** The gap the layout leaves between the open content and what follows. */
+ restGap: number;
+ /** How much farther than the content's height the content after it moves. */
+ beyond: number;
+}
+
+/**
+ * Opens and closes the content, and reads what the engine evaluates on every
+ * frame. That is the content's box less its clip, the lowest of its parts
+ * with their translation, and the box after it.
+ */
+async function paintedRide(
+ page: Page,
+ selectors: {trigger: string; content: string; after: string},
+): Promise<PaintedRide> {
+ return page.evaluate(async ({trigger, content: contentSelector, after}) => {
+ const button = document.querySelector(trigger) as HTMLElement;
+ const content = () => document.querySelector<HTMLElement>(contentSelector);
+ const next = document.querySelector(after) as HTMLElement;
+ const clipBottom = (element: HTMLElement, box: DOMRect) => {
+ const match = /^inset\(([^)]*)\)/.exec(
+ getComputedStyle(element).clipPath,
+ );
+ if (match == null) {
+ return 0;
+ }
+ const [t, , b = t] = match[1].trim().split(/\s+/);
+ return b.endsWith('%')
+ ? (Number.parseFloat(b) / 100) * box.height
+ : Number.parseFloat(b);
+ };
+ const frames: PaintedFrame[] = [];
+ const read = (phase: PaintedFrame['phase']) => {
+ const element = content();
+ if (element == null || getComputedStyle(element).display === 'none') {
+ return;
+ }
+ const box = element.getBoundingClientRect();
+ let edge = box.bottom - clipBottom(element, box);
+ let lowest = Number.NEGATIVE_INFINITY;
+ for (
+ let part = element.firstElementChild;
+ part != null;
+ part = part.nextElementSibling
+ ) {
+ lowest = Math.max(lowest, part.getBoundingClientRect().bottom);
+ }
+ if (Number.isFinite(lowest)) {
+ edge = Math.min(edge, lowest);
+ }
+ frames.push({
+ phase,
+ gap: next.getBoundingClientRect().top - edge,
+ shown: Math.max(0, edge - box.top),
+ });
+ };
+ const frame = async () =>
+ new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve());
+ });
+ const settle = async () => {
+ for (let i = 0; i < 90; i++) {
+ await frame();
+ }
+ };
+ const closedTop = next.getBoundingClientRect().top;
+ button.click();
+ await settle();
+ const box = (content() as HTMLElement).getBoundingClientRect();
+ const openTop = next.getBoundingClientRect().top;
+ const restGap = openTop - box.bottom;
+ const beyond = Math.max(0, openTop - closedTop - box.height);
+ button.click();
+ await settle();
+ button.click();
+ for (let i = 0; i < 40; i++) {
+ await frame();
+ read('opening');
+ }
+ await settle();
+ button.click();
+ for (let i = 0; i < 40; i++) {
+ await frame();
+ read('closing');
+ }
+ return {frames, restGap, beyond};
+ }, selectors);
+}
+
+/**
+ * On every painted frame where the content shows, its shown edge meets the
+ * content after it as at rest. No blank band opens and nothing overlaps,
+ * beyond the container gap that content travels.
+ */
+function expectPaintedRide(result: PaintedRide): void {
+ for (const phase of ['opening', 'closing'] as const) {
+ const shown = result.frames.filter(f => f.phase === phase && f.shown > 0.5);
+ expect(shown.length, `${phase} frames`).toBeGreaterThan(4);
+ for (const f of shown) {
+ const detail = JSON.stringify({...f, ...result, frames: undefined});
+ expect(f.gap, detail).toBeLessThan(result.restGap + 1.5);
+ expect(f.gap, detail).toBeGreaterThan(
+ result.restGap - result.beyond - 1.5,
+ );
+ }
+ }
+}
+
+/**
+ * Waits until no animation on the page still runs. It reads again after each
+ * wait, so a motion that starts late is waited for too.
+ */
+async function settleMotions(page: Page): Promise<void> {
+ await page.evaluate(async () => {
+ const running = () =>
+ document
+ .getAnimations()
+ .filter(animation => animation.playState !== 'finished');
+ for (let left = running(); left.length > 0; left = running()) {
+ await Promise.allSettled(left.map(async animation => animation.finished));
+ }
+ });
+}
+
+/** Opens the gliding rows story and marks the first row's toggle and the row after it. */
+async function openTable(page: Page): Promise<void> {
+ await page.goto(
+ `${storybook?.origin ?? ''}/iframe.html?id=core-tablerowexpansion--gliding-rows&viewMode=story`,
+ );
+ const trigger = page.locator('tbody button[aria-expanded="false"]').first();
+ await trigger.waitFor();
+ await trigger.evaluate(button => {
+ button.setAttribute('data-test-id', 'expand');
+ button
+ .closest('tr')
+ ?.nextElementSibling?.setAttribute('data-test-id', 'after-row');
+ });
+}
+
+/**
+ * Opens the marked row. On the next frame, reads whether the panel row's own
+ * motion moves a clip, and how many of its cells move.
+ */
+async function revealOnNextFrame(page: Page) {
+ return page.evaluate(async () => {
+ (document.querySelector('[data-test-id="expand"]') as HTMLElement).click();
+ const panel = () => document.querySelector('[data-expansion-panel]');
+ for (let i = 0; i < 30 && !panel()?.getAnimations().length; i++) {
+ await new Promise(requestAnimationFrame);
+ }
+ return {
+ clips: (panel()?.getAnimations() ?? []).some(animation =>
+ (animation.effect as KeyframeEffect)
+ .getKeyframes()
+ .some(frame => frame.clipPath != null),
+ ),
+ partMotions: [...(panel()?.children ?? [])].reduce(
+ (count, part) => count + part.getAnimations().length,
+ 0,
+ ),
+ };
+ });
+}
+
+test.describe('spec:AST-105 FR9: an edge reveal paints its edge on the content beside it', () => {
+ test("a Collapsible's revealed content meets the content after it on every painted frame, opening and closing", async ({
+ page,
+ }) => {
+ await openStory(page);
+ await page.evaluate(() => {
+ const element = [...document.querySelectorAll('div')].find(el =>
+ el.firstChild?.textContent?.trim().startsWith('A plain app div'),
+ );
+ element?.setAttribute('data-test-id', 'after');
+ });
+ const trigger = page.getByRole('button', {name: 'Shipping details'});
+ const contentId = await trigger.getAttribute('aria-controls');
+ expectPaintedRide(
+ await paintedRide(page, {
+ trigger: `button[aria-controls="${contentId ?? ''}"]`,
+ content: `[id="${contentId ?? ''}"]`,
+ after: '[data-test-id="after"]',
+ }),
+ );
+ });
+
+ test('a Collapsible closed and opened again rests with its content in place, with no slide left on it', async ({
+ page,
+ }) => {
+ await openStory(page);
+ const trigger = page.getByRole('button', {name: 'Shipping details'});
+ const contentId = (await trigger.getAttribute('aria-controls')) ?? '';
+ for (let i = 0; i < 3; i++) {
+ await trigger.click();
+ await settleMotions(page);
+ }
+ const parts = await page.evaluate(id => {
+ const region = document.getElementById(id);
+ return [...(region?.children ?? [])].map(part => ({
+ animations: part.getAnimations().length,
+ translate: getComputedStyle(part).translate,
+ }));
+ }, contentId);
+ expect(parts.length).toBeGreaterThan(0);
+ for (const part of parts) {
+ expect(part.animations).toBe(0);
+ expect(part.translate).toBe('none');
+ }
+ });
+
+ test("mid-open a Collapsible's content stays inside the region's content box, below the trigger's label", async ({
+ page,
+ }) => {
+ await openStory(page);
+ const trigger = page.getByRole('button', {name: 'Shipping details'});
+ const contentId = (await trigger.getAttribute('aria-controls')) ?? '';
+ await trigger.click();
+ const held = await page.evaluate(async id => {
+ const region = document.getElementById(id);
+ for (let i = 0; i < 30 && !region?.getAnimations().length; i++) {
+ await new Promise(requestAnimationFrame);
+ }
+ for (const animation of document.getAnimations()) {
+ animation.pause();
+ animation.currentTime = 105;
+ }
+ await new Promise(requestAnimationFrame);
+ if (region == null || region.firstElementChild == null) {
+ return null;
+ }
+ const style = getComputedStyle(region);
+ const box = region.getBoundingClientRect();
+ return {
+ clipTop: Number.parseFloat(
+ /^inset\(([^ )]+)/.exec(style.clipPath)?.[1] ?? 'NaN',
+ ),
+ paddingTop: Number.parseFloat(style.paddingTop),
+ partTop: region.firstElementChild.getBoundingClientRect().top - box.top,
+ };
+ }, contentId);
+ expect(held, 'the region and its content').not.toBeNull();
+ expect(held?.paddingTop ?? 0).toBeGreaterThan(0);
+ // The clip starts where the content box does: the label's descenders
+ // hang into the padding above it.
+ expect(held?.clipTop ?? 0).toBeCloseTo(held?.paddingTop ?? -1, 1);
+ // Mid-open the content still reaches above that edge, so the clip does work.
+ expect(held?.partTop ?? 0).toBeLessThan(held?.paddingTop ?? 0);
+ });
+
+ test('a Collapsible region with a generated box of its own keeps the moving clip, and its parts stay still', async ({
+ page,
+ }) => {
+ await openStory(page);
+ const trigger = page.getByRole('button', {name: 'Shipping details'});
+ const contentId = (await trigger.getAttribute('aria-controls')) ?? '';
+ await page.addStyleTag({
+ content: `[id="${contentId}"]::before { content: ""; display: block; height: 4px; }`,
+ });
+ await trigger.click();
+ const reveal = await page.evaluate(async id => {
+ const region = document.getElementById(id);
+ for (let i = 0; i < 30 && !region?.getAnimations().length; i++) {
+ await new Promise(requestAnimationFrame);
+ }
+ return {
+ clips: (region?.getAnimations() ?? []).some(animation =>
+ (animation.effect as KeyframeEffect)
+ .getKeyframes()
+ .some(frame => frame.clipPath != null),
+ ),
+ partMotions: [...(region?.children ?? [])].reduce(
+ (count, part) => count + part.getAnimations().length,
+ 0,
+ ),
+ };
+ }, contentId);
+ expect(reveal).toEqual({clips: true, partMotions: 0});
+ });
+
+ test("a Table row's expanded panel slides its cell on the glide's frames and meets the row after it on every painted frame as it opens", async ({
+ page,
+ }) => {
+ await openTable(page);
+ expect(await revealOnNextFrame(page)).toEqual({
+ clips: false,
+ partMotions: 1,
+ });
+ await settleMotions(page);
+ await page.locator('[data-test-id="expand"]').click();
+ await settleMotions(page);
+ const ride = await paintedRide(page, {
+ trigger: '[data-test-id="expand"]',
+ content: '[data-expansion-panel]',
+ after: '[data-test-id="after-row"]',
+ });
+ // A closing panel leaves at once and only the rows after it glide.
+ const opening = ride.frames.filter(
+ f => f.phase === 'opening' && f.shown > 0.5,
+ );
+ expect(opening.length, 'opening frames').toBeGreaterThan(4);
+ for (const f of opening) {
+ expect(f.gap, JSON.stringify(f)).toBeLessThan(ride.restGap + 1.5);
+ expect(f.gap, JSON.stringify(f)).toBeGreaterThan(
+ ride.restGap - ride.beyond - 1.5,
+ );
+ }
+ });
+
+ test('a Table panel row that paints its own box keeps the moving clip, and its cell stays still', async ({
+ page,
+ }) => {
+ await openTable(page);
+ await page.addStyleTag({
+ content:
+ '[data-expansion-panel] { background-color: rgb(240, 240, 240); }',
+ });
+ expect(await revealOnNextFrame(page)).toEqual({
+ clips: true,
+ partMotions: 0,
+ });
+ });
+
+ test("a nested row expanded while its parent's group still slides: the rows after it keep meeting it, and none jumps", async ({
+ page,
+ }) => {
+ await openStory(page);
+ const result = await page.evaluate(async () => {
+ const toggle = (id: string) =>
+ document.querySelector<HTMLElement>(
+ `[data-tree-id="${id}"] [data-tree-toggle]`,
+ );
+ const row = (id: string) =>
+ document.querySelector<HTMLElement>(`[data-tree-id="${id}"]`);
+ const group = () =>
+ document.querySelector<HTMLElement>(
+ '[data-tree-id="trips"] > [role="group"]',
+ );
+ const frame = async () =>
+ new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve());
+ });
+ // Where Trips' group shows its bottom: its box, or its lowest part.
+ const shownEdge = (element: HTMLElement) => {
+ let lowest = Number.NEGATIVE_INFINITY;
+ for (
+ let part = element.firstElementChild;
+ part != null;
+ part = part.nextElementSibling
+ ) {
+ lowest = Math.max(lowest, part.getBoundingClientRect().bottom);
+ }
+ return Math.min(element.getBoundingClientRect().bottom, lowest);
+ };
+ toggle('photos')?.click();
+ for (let i = 0; i < 7; i++) {
+ await frame();
+ }
+ toggle('trips')?.click();
+ const frames: {gap: number; overlap: number}[] = [];
+ for (let i = 0; i < 30; i++) {
+ await frame();
+ const trips = group();
+ const party = row('party')?.getBoundingClientRect();
+ const docs = row('docs')?.getBoundingClientRect();
+ if (trips == null || party == null || docs == null) {
+ continue;
+ }
+ frames.push({
+ gap: party.top - shownEdge(trips),
+ overlap: party.bottom - docs.top,
+ });
+ }
+ for (let i = 0; i < 60; i++) {
+ await frame();
+ }
+ const trips = group();
+ const party = row('party')?.getBoundingClientRect();
+ return {
+ frames,
+ restGap: (party?.top ?? 0) - (trips == null ? 0 : shownEdge(trips)),
+ };
+ });
+ expect(result.frames.length).toBeGreaterThan(4);
+ for (const [i, f] of result.frames.entries()) {
+ const at = `frame ${i}: ${JSON.stringify(f)}`;
+ expect(Math.abs(f.gap - result.restGap), at).toBeLessThan(1.5);
+ expect(f.overlap, at).toBeLessThan(0.5);
+ }
+ });
+
+ test("a TreeList row's revealed group meets the rows after it on every painted frame, expanding and collapsing", async ({
+ page,
+ }) => {
+ await openStory(page);
+ expectPaintedRide(
+ await paintedRide(page, {
+ trigger: '[data-tree-id="docs"] [data-tree-toggle]',
+ content: '[data-tree-id="docs"] > [role="group"]',
+ after: '[data-tree-id="notes"]',
+ }),
+ );
+ });
+});
diff --git a/packages/core/src/motion/animatedLayout.boundary.test.ts b/packages/core/src/motion/animatedLayout.boundary.test.ts
index aef8bdf66c..4c06e979f8 100644
--- a/packages/core/src/motion/animatedLayout.boundary.test.ts
+++ b/packages/core/src/motion/animatedLayout.boundary.test.ts
@@ -94,6 +94,13 @@ describe('architecture:react-component-runtime INV12 source boundary', () => {
expect(body).toMatch(
/sibling != null && take\(sibling, false\);\s*sibling = sibling\.previousElementSibling/,
);
+ // One more descent: a block edge's reveal reads the changed element's own
+ // children, and stops at the first one past the band.
+ expect(body.match(/\.firstChild\b/g) ?? []).toHaveLength(1);
+ expect(body).toMatch(
+ /for \(let node = element\.firstChild; node != null; node = node\.nextSibling\)/,
+ );
+ expect(body).toMatch(/if \(box\.top > band\.end\) \{\s*break;/);
});
it('keeps the reporting functions out of every public entry point', () => {
diff --git a/packages/core/src/motion/animatedLayout.slide.test.ts b/packages/core/src/motion/animatedLayout.slide.test.ts
new file mode 100644
index 0000000000..e2dc619ff1
--- /dev/null
+++ b/packages/core/src/motion/animatedLayout.slide.test.ts
@@ -0,0 +1,348 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @input `animatedLayout`'s block edge reveal and conceal, in jsdom with
+ * recorded animations and placed boxes.
+ * @output Unit tests for the slide under a still clip: which parts move, on
+ * which frames, and what the element keeps while they move.
+ * @position Beside `animatedLayout.test.ts`, which covers the clip reveal of an
+ * element with text of its own.
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {
+ createAnimatedLayout,
+ glideOf,
+ holdLayoutExit,
+ playLayoutChange,
+ releaseLayoutExit,
+ reportLayoutChange,
+} from './animatedLayout';
+
+interface Played {
+ element: Element;
+ keyframes: Keyframe[];
+ options: KeyframeAnimationOptions;
+ cancel: ReturnType<typeof vi.fn>;
+ /** Runs every finish listener, in the order they were added. */
+ finish: () => void;
+}
+
+let played: Played[] = [];
+const originalAnimate = Element.prototype.animate;
+const originalMatchMedia = window.matchMedia;
+
+beforeEach(() => {
+ played = [];
+ Element.prototype.animate = function (
+ this: Element,
+ keyframes: Keyframe[] | PropertyIndexedKeyframes | null,
+ options?: number | KeyframeAnimationOptions,
+ ) {
+ const cancel = vi.fn();
+ const listeners: (() => void)[] = [];
+ const entry: Played = {
+ element: this,
+ keyframes: keyframes as Keyframe[],
+ options: options as KeyframeAnimationOptions,
+ cancel,
+ finish: () => {
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ };
+ played.push(entry);
+ return {
+ cancel,
+ addEventListener(type: string, listener: () => void) {
+ if (type === 'finish') {
+ listeners.push(listener);
+ }
+ },
+ currentTime: 0,
+ } as unknown as Animation;
+ };
+ window.matchMedia = (query: string) =>
+ ({
+ matches: false,
+ media: query,
+ addEventListener() {},
+ removeEventListener() {},
+ }) as unknown as MediaQueryList;
+});
+
+afterEach(() => {
+ Element.prototype.animate = originalAnimate;
+ window.matchMedia = originalMatchMedia;
+ document.body.innerHTML = '';
+ vi.restoreAllMocks();
+});
+
+/** Places `element` at `y` with `height`, in a 400 px wide area. */
+function place(element: Element, y: number, height: number) {
+ vi.spyOn(element, 'getBoundingClientRect').mockReturnValue(
+ new DOMRect(0, y, 400, height),
+ );
+}
+
+/**
+ * An 80 px content of two rows, opened or closed in a 600 px area, with a row
+ * after it. With `far`, a third child sits far below the band.
+ */
+function setUp({isOpening, far = false}: {isOpening: boolean; far?: boolean}) {
+ document.body.innerHTML = `<div id="area"><div id="content"><p id="a">A</p>
+ <p id="b">B</p>${far ? '<p id="far">Far</p>' : ''}</div><p id="after">Next</p></div>`;
+ const area = document.getElementById('area') as HTMLElement;
+ const content = document.getElementById('content') as HTMLElement;
+ const after = document.getElementById('after') as HTMLElement;
+ place(area, 0, 600);
+ place(document.getElementById('a') as HTMLElement, 40, 40);
+ place(document.getElementById('b') as HTMLElement, 80, 40);
+ if (far) {
+ place(document.getElementById('far') as HTMLElement, 5000, 40);
+ }
+ Object.defineProperty(content, 'offsetHeight', {value: 80});
+ // A closing content stays in place while it exits, and gives up its space
+ // through its end margin. An opening one takes its 80 px with the commit.
+ let isShown = !isOpening;
+ vi.spyOn(content, 'getBoundingClientRect').mockImplementation(
+ () => new DOMRect(0, 40, 400, isShown || !isOpening ? 80 : 0),
+ );
+ vi.spyOn(after, 'getBoundingClientRect').mockImplementation(() => {
+ const margin =
+ Number.parseFloat(content.style.getPropertyValue('margin-block-end')) ||
+ 0;
+ return new DOMRect(
+ 0,
+ 40 + (isShown || !isOpening ? 80 : 0) + margin,
+ 400,
+ 20,
+ );
+ });
+ const layout = createAnimatedLayout(() => area);
+ const change = reportLayoutChange(layout, () => content);
+ change.measureBefore();
+ isShown = isOpening;
+ change.animate();
+ return {area, content, after, layout};
+}
+
+const motionsOn = (id: string) =>
+ played.filter(entry => (entry.element as HTMLElement).id === id);
+
+const translates = (entry: Played | undefined) =>
+ (entry?.keyframes ?? []).map(frame => String(frame.translate));
+
+describe('a block edge reveal slides its parts under a still clip (spec:AST-105 FR9)', () => {
+ it('slides the child elements in on the frames the content after them glides on, fading the element, which keeps a still clip on its box', () => {
+ const {content, layout} = setUp({isOpening: true});
+ playLayoutChange(layout, content);
+ const [entrance] = motionsOn('content');
+ // The element only fades: no clip moves.
+ expect(entrance.keyframes.every(frame => frame.clipPath == null)).toBe(
+ true,
+ );
+ expect(entrance.keyframes[0].opacity).toBe(0);
+ expect(content.style.getPropertyValue('clip-path')).toBe(
+ 'inset(0px 0px 0px 0px)',
+ );
+ // Both rows start a full content height up, and land in place.
+ for (const id of ['a', 'b']) {
+ const [slide] = motionsOn(id);
+ expect(translates(slide)[0]).toBe('0px -80px');
+ expect(translates(slide).at(-1)).toBe('0px 0px');
+ expect(slide.options.duration).toBe(entrance.options.duration);
+ expect(slide.keyframes.map(frame => frame.offset)).toEqual(
+ entrance.keyframes.map(frame => frame.offset),
+ );
+ }
+ // Once it ends, the element's own clip comes back.
+ entrance.finish();
+ expect(content.style.getPropertyValue('clip-path')).toBe('');
+ });
+
+ it("makes each part's slide its glide, so a later change carries it, and forgets it when the motion ends", () => {
+ const {content, layout} = setUp({isOpening: true});
+ playLayoutChange(layout, content);
+ const part = document.getElementById('a') as HTMLElement;
+ expect(glideOf(part)).not.toBeNull();
+ const [entrance] = motionsOn('content');
+ entrance.finish();
+ expect(glideOf(part)).toBeNull();
+ });
+
+ it('keeps the moving clip when a part still glides from an earlier change, so its glide plays on', async () => {
+ document.body.innerHTML = `<div id="area"><div id="content"><p id="a">A</p>
+ <p id="b">B</p></div><p id="after">Next</p></div>`;
+ const byId = (id: string) => document.getElementById(id) as HTMLElement;
+ const [area, content, a, b, after] = [
+ 'area',
+ 'content',
+ 'a',
+ 'b',
+ 'after',
+ ].map(byId);
+ place(area, 0, 600);
+ // The first row grows by 20 px, so the second row glides down.
+ let grown = 0;
+ vi.spyOn(a, 'getBoundingClientRect').mockImplementation(
+ () => new DOMRect(0, 40, 400, 40 + grown),
+ );
+ vi.spyOn(b, 'getBoundingClientRect').mockImplementation(
+ () => new DOMRect(0, 80 + grown, 400, 40),
+ );
+ vi.spyOn(content, 'getBoundingClientRect').mockImplementation(
+ () => new DOMRect(0, 40, 400, 80 + grown),
+ );
+ Object.defineProperty(content, 'offsetHeight', {get: () => 80 + grown});
+ vi.spyOn(after, 'getBoundingClientRect').mockImplementation(() => {
+ const margin =
+ Number.parseFloat(content.style.getPropertyValue('margin-block-end')) ||
+ 0;
+ return new DOMRect(0, 120 + grown + margin, 400, 20);
+ });
+ const layout = createAnimatedLayout(() => area);
+ const grow = reportLayoutChange(layout, () => a);
+ grow.measureBefore();
+ grown = 20;
+ grow.animate();
+ await Promise.resolve();
+ expect(glideOf(b)).not.toBeNull();
+ const glide = glideOf(b);
+ // The content then closes while that glide runs.
+ const close = reportLayoutChange(layout, () => content);
+ close.measureBefore();
+ close.animate();
+ expect(holdLayoutExit(layout, content, vi.fn())).toBe(true);
+ const exit = motionsOn('content').at(-1);
+ expect(exit?.keyframes.some(frame => frame.clipPath != null)).toBe(true);
+ expect(glideOf(b)).toBe(glide);
+ });
+
+ it('leaves a child the band cannot show where it is', () => {
+ const {content, layout} = setUp({isOpening: true, far: true});
+ playLayoutChange(layout, content);
+ expect(motionsOn('a')).toHaveLength(1);
+ expect(motionsOn('b')).toHaveLength(1);
+ expect(motionsOn('far')).toEqual([]);
+ });
+
+ it('keeps the clip reveal for an element with text of its own', () => {
+ const {content, layout} = setUp({isOpening: true});
+ content.prepend('Details');
+ playLayoutChange(layout, content);
+ const [entrance] = motionsOn('content');
+ expect(String(entrance.keyframes[0].clipPath)).toBe('inset(0 0 100% 0)');
+ expect(motionsOn('a')).toEqual([]);
+ expect(content.style.getPropertyValue('clip-path')).toBe('');
+ });
+
+ it('slides the parts out on an exit, holding them at their end until the release, which stops them and puts the clip back', () => {
+ const {content, layout} = setUp({isOpening: false});
+ const done = vi.fn();
+ expect(holdLayoutExit(layout, content, done)).toBe(true);
+ const [exit] = motionsOn('content');
+ expect(exit.keyframes.every(frame => frame.clipPath == null)).toBe(true);
+ expect(content.style.getPropertyValue('clip-path')).toBe(
+ 'inset(0px 0px 0px 0px)',
+ );
+ const [slide] = motionsOn('a');
+ expect(translates(slide)[0]).toBe('0px 0px');
+ expect(translates(slide).at(-1)).toBe('0px -80px');
+ expect(slide.options.fill).toBe('forwards');
+ releaseLayoutExit(content);
+ expect(slide.cancel).toHaveBeenCalledTimes(1);
+ expect(content.style.getPropertyValue('clip-path')).toBe('');
+ });
+
+ it("holds an exit's slides past its end, and stops them once at the release that follows, so a later reveal starts from rest", () => {
+ const {content, layout} = setUp({isOpening: false});
+ const done = vi.fn();
+ holdLayoutExit(layout, content, done);
+ const [exit] = motionsOn('content');
+ const [slide] = motionsOn('a');
+ exit.finish();
+ expect(done).toHaveBeenCalledTimes(1);
+ expect(slide.cancel).not.toHaveBeenCalled();
+ expect(content.style.getPropertyValue('clip-path')).toBe(
+ 'inset(0px 0px 0px 0px)',
+ );
+ releaseLayoutExit(content);
+ expect(slide.cancel).toHaveBeenCalledTimes(1);
+ expect(content.style.getPropertyValue('clip-path')).toBe('');
+ releaseLayoutExit(content);
+ expect(slide.cancel).toHaveBeenCalledTimes(1);
+ });
+
+ it("holds the parts inside the element's content box on the side they come from", () => {
+ const {content, layout} = setUp({isOpening: true});
+ content.style.paddingTop = '12px';
+ content.style.paddingBottom = '7px';
+ playLayoutChange(layout, content);
+ expect(content.style.getPropertyValue('clip-path')).toBe(
+ 'inset(12px 0px 0px 0px)',
+ );
+ });
+
+ it('keeps the moving clip for an element that paints its own box', () => {
+ const {content, layout} = setUp({isOpening: true});
+ content.style.backgroundColor = 'rgb(240, 240, 240)';
+ playLayoutChange(layout, content);
+ const [entrance] = motionsOn('content');
+ expect(String(entrance.keyframes[0].clipPath)).toBe('inset(0 0 100% 0)');
+ expect(motionsOn('a')).toEqual([]);
+ });
+
+ for (const [what, paint] of [
+ ['a border image', {borderImageSource: 'linear-gradient(red, blue)'}],
+ ['a filter', {filter: 'blur(1px)'}],
+ ['a border', {borderTop: '1px solid rgb(0, 0, 0)'}],
+ ['a shadow', {boxShadow: '0 1px 2px rgb(0, 0, 0)'}],
+ ] as const) {
+ it(`keeps the moving clip for an element whose own box carries ${what}`, () => {
+ const {content, layout} = setUp({isOpening: true});
+ Object.assign(content.style, paint);
+ playLayoutChange(layout, content);
+ const [entrance] = motionsOn('content');
+ expect(String(entrance.keyframes[0].clipPath)).toBe('inset(0 0 100% 0)');
+ expect(motionsOn('a')).toEqual([]);
+ });
+ }
+
+ it('keeps the moving clip when a part is an inline box, which no translation moves', () => {
+ const {content, layout} = setUp({isOpening: true});
+ (document.getElementById('b') as HTMLElement).style.display = 'inline';
+ playLayoutChange(layout, content);
+ const [entrance] = motionsOn('content');
+ expect(String(entrance.keyframes[0].clipPath)).toBe('inset(0 0 100% 0)');
+ expect(motionsOn('a')).toEqual([]);
+ });
+
+ it('keeps the moving clip when no part can play its slide', () => {
+ const {content, layout} = setUp({isOpening: true});
+ const animate = Element.prototype.animate;
+ Element.prototype.animate = function (
+ this: Element,
+ ...args: Parameters<Element['animate']>
+ ) {
+ if (this.tagName === 'P') {
+ throw new Error('no animation here');
+ }
+ return animate.apply(this, args);
+ };
+ playLayoutChange(layout, content);
+ const [entrance] = motionsOn('content');
+ expect(String(entrance.keyframes[0].clipPath)).toBe('inset(0 0 100% 0)');
+ expect(content.style.getPropertyValue('clip-path')).toBe('');
+ });
+
+ it('a reveal that reverses a running exit stops its slides first', () => {
+ const {content, layout} = setUp({isOpening: false});
+ holdLayoutExit(layout, content, vi.fn());
+ const [leaving] = motionsOn('a');
+ releaseLayoutExit(content);
+ playLayoutChange(layout, content);
+ expect(leaving.cancel).toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.ts
index 88b5a29854..03c4360ad3 100644
--- a/packages/core/src/motion/animatedLayout.ts
+++ b/packages/core/src/motion/animatedLayout.ts
@@ -1720,6 +1720,156 @@ function extentOf(element: Element, edge: LayoutEdge): number {
: rect.height / scale.y;
}
+/** The parts that slide, and the still clip that holds them while they do. */
+interface Sliding {
+ readonly parts: ReadonlyArray<Element>;
+ /** Each part's ancestors' scale: page px per px of its own offset. */
+ readonly scales: ReadonlyArray<{readonly x: number; readonly y: number}>;
+ readonly clip: string;
+}
+
+/**
+ * The parts that slide inside an element revealed or concealed from a block
+ * edge by `extent` px. They are its child elements that the band can show:
+ * the area's visible part plus one viewport, or `extent` if larger, above and
+ * below. A part past the band cannot come into view while it moves, so it
+ * stays. The walk stops at the first child below the band, so its cost grows
+ * with the changed size, never with the length of a list. A translation
+ * cannot move text on its own, so an element with text of its own keeps the
+ * clip (null).
+ */
+function slidingParts(
+ element: Element,
+ edge: LayoutEdge,
+ area: Element,
+ extent: number,
+): Sliding | null {
+ if (!edge.startsWith('block') || !(extent > 0)) {
+ return null;
+ }
+ const view = element.ownerDocument.defaultView;
+ const style = view?.getComputedStyle(element);
+ // A box the element paints itself would show whole from the first frame
+ // under a still clip, so such an element keeps the moving clip. So does one
+ // with a generated box, which stays still while its parts slide.
+ if (
+ view == null ||
+ style == null ||
+ paintsOwnBox(style) ||
+ ['::before', '::after'].some(pseudo => {
+ const {content} = view.getComputedStyle(element, pseudo);
+ return content !== '' && content !== 'none' && content !== 'normal';
+ })
+ ) {
+ return null;
+ }
+ const visible = visibleRect(area);
+ const band = bandFor(visible, Math.max(view.innerHeight, extent));
+ const parts: Element[] = [];
+ const scales: {x: number; y: number}[] = [];
+ for (let node = element.firstChild; node != null; node = node.nextSibling) {
+ if (node.nodeType === Node.TEXT_NODE) {
+ if ((node.textContent ?? '').trim() !== '') {
+ return null;
+ }
+ continue;
+ }
+ if (node.nodeType !== Node.ELEMENT_NODE) {
+ continue;
+ }
+ // A translation moves neither an inline box nor a boxless one.
+ const {display} = view.getComputedStyle(node as Element);
+ if (display === 'inline' || display === 'contents') {
+ return null;
+ }
+ // Each part's place, read once per reveal, before anything moves.
+ const box = (node as Element).getBoundingClientRect();
+ if (box.top > band.end) {
+ break;
+ }
+ if (box.bottom >= band.start) {
+ // A part an earlier change still glides keeps that glide, which a slide
+ // would hide and then show again. The element keeps the moving clip.
+ if (glides.has(node as Element)) {
+ return null;
+ }
+ parts.push(node as Element);
+ scales.push(scaleOf(node as Element, box, ownScaleOf(node as Element)));
+ }
+ }
+ if (parts.length === 0) {
+ return null;
+ }
+ // The parts come in from one side. The clip holds them inside the content
+ // box there, off what the content before the element draws into its padding.
+ const inner = (side: 'top' | 'bottom') =>
+ (Number.parseFloat(style.getPropertyValue(`border-${side}-width`)) || 0) +
+ (Number.parseFloat(style.getPropertyValue(`padding-${side}`)) || 0);
+ return {
+ parts,
+ scales,
+ clip:
+ edge === 'block-end'
+ ? `inset(${inner('top')}px 0px 0px 0px)`
+ : `inset(0px 0px ${inner('bottom')}px 0px)`,
+ };
+}
+
+/**
+ * Whether a style paints a box of its own: a fill, a border, a shadow, an
+ * outline or a filter.
+ */
+function paintsOwnBox(style: CSSStyleDeclaration): boolean {
+ const isClear = (color: string) =>
+ color === '' || color === 'transparent' || /^rgba\(.*,\s*0\)$/.test(color);
+ return (
+ !isClear(style.backgroundColor) ||
+ (style.backgroundImage !== '' && style.backgroundImage !== 'none') ||
+ ['Top', 'Right', 'Bottom', 'Left'].some(
+ side =>
+ style.getPropertyValue(`border-${side.toLowerCase()}-style`) !==
+ 'none' &&
+ Number.parseFloat(
+ style.getPropertyValue(`border-${side.toLowerCase()}-width`),
+ ) > 0,
+ ) ||
+ (style.boxShadow !== '' && style.boxShadow !== 'none') ||
+ (style.borderImageSource !== '' && style.borderImageSource !== 'none') ||
+ (style.filter !== '' && style.filter !== 'none') ||
+ (style.outlineStyle !== '' &&
+ style.outlineStyle !== 'none' &&
+ Number.parseFloat(style.outlineWidth) > 0)
+ );
+}
+
+/**
+ * Where the parts sit when the element hides `hidden` px from `edge`. They
+ * move that far towards it, so their far edge meets the content that rides
+ * the same edge.
+ */
+function slideFrame(edge: LayoutEdge, hidden: number): Keyframe {
+ return {translate: `0px ${edge === 'block-end' ? -hidden : hidden}px`};
+}
+
+/**
+ * Clips `element` with `clip` while its parts slide, and returns what puts
+ * its own `clip-path` back. The clip does not move, so it stays in step with
+ * the parts and the content beside them on every engine.
+ */
+function holdSlideClip(element: Element, clip: string): () => void {
+ const {style} = element as HTMLElement;
+ const value = style.getPropertyValue('clip-path');
+ const priority = style.getPropertyPriority('clip-path');
+ style.setProperty('clip-path', clip);
+ return () => {
+ if (value === '') {
+ style.removeProperty('clip-path');
+ } else {
+ style.setProperty('clip-path', value, priority);
+ }
+ };
+}
+
/**
* The last element before `element` in the area that takes part in layout:
* its previous sibling, or its nearest ancestor's below the area (the mirror
@@ -1792,6 +1942,10 @@ interface EdgeMotion {
readonly animation: Animation;
/** The fraction of the element it shows `t` ms in (1: all of it). */
shownAt: (t: number) => number;
+ /** The parts that slide under the element's clip, and their motions. */
+ readonly slides: ReadonlyArray<Animation>;
+ /** Puts back what the motion set on the element, once. */
+ readonly release: () => void;
}
/** Each element's running one-state reveal or conceal. */
@@ -1828,6 +1982,7 @@ function shownAtStart(element: Element, atRest: number): number {
edgeMotions.delete(element);
const fraction = shownNow(running);
running.animation.cancel();
+ stopSlides(running);
return fraction;
}
const stopped = stoppedShown.get(element);
@@ -1838,22 +1993,55 @@ function shownAtStart(element: Element, atRest: number): number {
return atRest;
}
+/** Stops `motion`'s sliding parts and puts back the element's clip, once. */
+function stopSlides(motion: EdgeMotion): void {
+ motion.release();
+}
+
/** Records `animation` as `element`'s running one-state motion. */
function trackEdgeMotion(
element: Element,
animation: Animation,
shownAt: (t: number) => number,
+ slides: ReadonlyArray<Animation> = [],
+ release: () => void = () => {},
+ isHeldToRelease = false,
): EdgeMotion {
- const motion: EdgeMotion = {animation, shownAt};
+ let isReleased = false;
+ const motion: EdgeMotion = {
+ animation,
+ shownAt,
+ slides,
+ release: () => {
+ if (!isReleased) {
+ isReleased = true;
+ for (const slide of slides) {
+ stopGlideOf(slide);
+ }
+ release();
+ }
+ },
+ };
edgeMotions.set(element, motion);
+ if (isHeldToRelease) {
+ heldSlides.set(element, motion);
+ }
+ // A reveal's parts have landed at its end. An exit's parts hold where they
+ // end until `releaseLayoutExit`.
animation.addEventListener?.('finish', () => {
if (edgeMotions.get(element) === motion) {
edgeMotions.delete(element);
+ if (!isHeldToRelease) {
+ motion.release();
+ }
}
});
return motion;
}
+/** Each exit's motion, whose parts hold their slides until its release. */
+const heldSlides = new WeakMap<Element, EdgeMotion>();
+
/**
* After this commit's glides start (the batch flushes in a microtask queued
* before this one), before the frame paints: once the content on `edge`'s
@@ -1874,7 +2062,7 @@ function rideNeighbour(
isCurrent: () => boolean,
hiddenAt: (towards: number) => number,
frame: (hidden: number) => Keyframe,
- onRide: (hidden: (t: number) => number) => void,
+ onRide: (hidden: (t: number) => number, durationMs: number) => void,
): void {
const effect = animation.effect as KeyframeEffect | null;
if (effect == null || typeof effect.setKeyframes !== 'function') {
@@ -1897,13 +2085,20 @@ function rideNeighbour(
// it shares with the neighbour (an item above them closing): the edge
// rides the neighbour's offset from the element, not from the page.
const own = glideMoving(element, neighbour, area);
- const durationMs = Math.max(glide.durationMs, own?.durationMs ?? 0);
+ // Each glide is read on its own clock. A glide an earlier change started,
+ // such as a part's slide, is already some way in.
+ const glideAt = startedBefore(glide, animation);
+ const ownAt = own == null ? 0 : startedBefore(own, animation);
+ const durationMs = Math.max(
+ glide.durationMs - glideAt,
+ own == null ? 0 : own.durationMs - ownAt,
+ );
// The neighbour's offset from its place relative to the element's,
// towards the edge's side.
const sign = isEnd ? 1 : -1;
const hidden = (t: number): number => {
- const offset = glide.offsetAt(t);
- const moved = own?.offsetAt(t) ?? {x: 0, y: 0};
+ const offset = glide.offsetAt(glideAt + t);
+ const moved = own?.offsetAt(ownAt + t) ?? {x: 0, y: 0};
return hiddenAt(
sign *
(edge.startsWith('inline')
@@ -1913,7 +2108,7 @@ function rideNeighbour(
};
effect.setKeyframes(sampleOver(durationMs, t => frame(hidden(t))));
effect.updateTiming?.({duration: durationMs});
- onRide(hidden);
+ onRide(hidden, durationMs);
});
}
@@ -1945,12 +2140,21 @@ function rideEdge(
() => edgeMotions.get(element) === motion,
towards =>
Math.min(extent, Math.max(0, isConceal ? extent - towards : -towards)),
- hidden => ({
- opacity: 1 - hidden / extent,
- clipPath: pxClip(edge, hidden, rtl),
- }),
- hiddenAt => {
+ hidden =>
+ motion.slides.length > 0
+ ? {opacity: 1 - hidden / extent}
+ : {opacity: 1 - hidden / extent, clipPath: pxClip(edge, hidden, rtl)},
+ (hiddenAt, durationMs) => {
motion.shownAt = t => 1 - hiddenAt(t) / extent;
+ // The parts ride the same frames, so their edge and the content's move
+ // on one clock.
+ for (const slide of motion.slides) {
+ const effect = slide.effect as KeyframeEffect | null;
+ effect?.setKeyframes?.(
+ sampleOver(durationMs, t => slideFrame(edge, hiddenAt(t))),
+ );
+ effect?.updateTiming?.({duration: durationMs});
+ }
},
);
}
@@ -2004,26 +2208,154 @@ export function playLayoutChange(
}
const {progress} = motion;
const rtl = edge.startsWith('inline') && isRtl(element);
+ // A block edge's parts slide in under the element's clip, on the frames the
+ // content after them glides on. A clip that moved would be painted on its
+ // own clock in WebKit, and the edge would part from that content.
+ const extent = edge.startsWith('block') ? extentOf(element, edge) : 0;
+ const sliding = slidingParts(element, edge, area, extent);
+ const partMotions = slideParts(sliding, progress, change, remaining =>
+ slideFrame(edge, (1 - from) * remaining * extent),
+ );
const animation = safeAnimate(
element,
sampleKeyframes(progress, remaining => {
const hidden = (1 - from) * remaining;
- return {opacity: 1 - hidden, clipPath: fractionClip(edge, hidden, rtl)};
+ return partMotions.length > 0
+ ? {opacity: 1 - hidden}
+ : {opacity: 1 - hidden, clipPath: fractionClip(edge, hidden, rtl)};
}),
{duration: progress.durationMs, easing: 'linear'},
change,
);
- if (animation != null) {
+ if (animation == null) {
+ for (const part of partMotions) {
+ part.cancel();
+ }
+ } else {
const tracked = trackEdgeMotion(
element,
animation,
t => 1 - (1 - from) * progress.remaining(t),
+ partMotions,
+ partMotions.length > 0 && sliding != null
+ ? holdSlideClip(element, sliding.clip)
+ : undefined,
);
rideEdge(element, area, edge, rtl, tracked, false);
}
return animation;
}
+/**
+ * Plays each part's slide on the change's start, sampled like the glide.
+ * `frame` turns the share of the motion still to come into a keyframe.
+ */
+function slideParts(
+ sliding: Sliding | null,
+ progress: GlideProgress,
+ change: ChangeStart | undefined,
+ frame: (remaining: number) => Keyframe,
+ fill?: FillMode,
+): Animation[] {
+ const motions: Animation[] = [];
+ for (const [index, part] of (sliding?.parts ?? []).entries()) {
+ const motion = safeAnimate(
+ part,
+ sampleKeyframes(progress, frame),
+ {duration: progress.durationMs, easing: 'linear', fill},
+ change,
+ );
+ if (motion != null) {
+ motions.push(motion);
+ // A slide is the part's glide. A later change in the area then carries
+ // its rest into the part's next glide, as it carries any glide.
+ const glide: Glide = {
+ animation: motion,
+ offsetAt: t => drawnOffset(motion, t),
+ // A ride retimes the slide, so its length is read off the slide.
+ get durationMs() {
+ return liveDuration(motion, progress.durationMs);
+ },
+ // The part showed at its place when the parts were read.
+ shownBefore: {x: 0, y: 0},
+ scale: sliding?.scales[index] ?? {x: 1, y: 1},
+ };
+ glides.set(part, glide);
+ slideTargets.set(motion, part);
+ // An exit's slide then holds its end until the release. The element is
+ // inert and has given up its space by then.
+ motion.addEventListener?.('finish', () => {
+ if (glides.get(part) === glide) {
+ glides.delete(part);
+ }
+ });
+ }
+ }
+ return motions;
+}
+
+/**
+ * The offset `animation` draws `t` ms in, read off its keyframes, a straight
+ * line between each two. A slide that rides another glide reads that glide's
+ * frames, so this follows it.
+ */
+function drawnOffset(
+ animation: Animation,
+ t: number,
+): {readonly x: number; readonly y: number} {
+ const effect = animation.effect as KeyframeEffect | null;
+ if (effect == null || typeof effect.getKeyframes !== 'function') {
+ return {x: 0, y: 0};
+ }
+ const frames = effect.getKeyframes();
+ const duration = Number(effect.getTiming().duration);
+ const at = duration > 0 ? Math.min(1, Math.max(0, t / duration)) : 1;
+ const offsetOf = (frame: ComputedKeyframe | undefined) => {
+ const [x = 0, y = 0] = numbersIn(String(frame?.translate ?? ''));
+ return {x, y, offset: frame?.computedOffset ?? 0};
+ };
+ let from = offsetOf(frames[0]);
+ let to = offsetOf(frames[frames.length - 1]);
+ for (const frame of frames) {
+ const point = offsetOf(frame);
+ if (point.offset <= at) {
+ from = point;
+ }
+ if (point.offset >= at) {
+ to = point;
+ break;
+ }
+ }
+ const span = to.offset - from.offset;
+ const k = span > 0 ? (at - from.offset) / span : 0;
+ return {x: from.x + (to.x - from.x) * k, y: from.y + (to.y - from.y) * k};
+}
+
+/** How many ms before `animation` started `glide` started: 0 in one change. */
+function startedBefore(glide: Glide, animation: Animation): number {
+ const shift = Number(animation.startTime) - Number(glide.animation.startTime);
+ return Number.isFinite(shift) ? Math.max(0, shift) : 0;
+}
+
+/** `animation`'s length now, in ms, or `fallback` if it has none. */
+function liveDuration(animation: Animation, fallback: number): number {
+ const effect = animation.effect as KeyframeEffect | null;
+ const duration = Number(effect?.getTiming?.().duration);
+ return duration > 0 ? duration : fallback;
+}
+
+/** Each part's slide, by its motion: a stopped slide is no glide. */
+const slideTargets = new WeakMap<Animation, Element>();
+
+/** Cancels a part's slide, and forgets it as the part's glide. */
+function stopGlideOf(animation: Animation): void {
+ const part = slideTargets.get(animation);
+ if (part != null && glides.get(part)?.animation === animation) {
+ glides.delete(part);
+ }
+ animation.cancel();
+}
+
/** The inline properties an exit sets, so a release removes exactly them. */
const EXIT_PROPERTIES = [
'margin-block-end',
@@ -2306,20 +2638,41 @@ export function holdLayoutExit(
);
} else {
const {progress} = motion;
+ // As in a reveal, a block edge's parts slide out under its clip.
+ const extent = edge.startsWith('block') ? extentOf(element, edge) : 0;
+ const sliding = slidingParts(element, edge, area, extent);
+ const partMotions = slideParts(
+ sliding,
+ progress,
+ change,
+ remaining => slideFrame(edge, (1 - from * remaining) * extent),
+ 'forwards',
+ );
animation = safeAnimate(
element,
sampleKeyframes(progress, remaining => {
const shown = from * remaining;
- return {opacity: shown, clipPath: fractionClip(edge, 1 - shown, rtl)};
+ return partMotions.length > 0
+ ? {opacity: shown}
+ : {opacity: shown, clipPath: fractionClip(edge, 1 - shown, rtl)};
}),
{duration: progress.durationMs, easing: 'linear', fill: 'forwards'},
change,
);
- if (animation != null) {
+ if (animation == null) {
+ for (const part of partMotions) {
+ part.cancel();
+ }
+ } else {
const tracked = trackEdgeMotion(
element,
animation,
t => from * progress.remaining(t),
+ partMotions,
+ partMotions.length > 0 && sliding != null
+ ? holdSlideClip(element, sliding.clip)
+ : undefined,
+ true,
);
rideEdge(element, area, edge, rtl, tracked, true);
}
@@ -2357,6 +2710,12 @@ export function releaseLayoutExit(element: HTMLElement): void {
fraction: shownNow(running),
at: timelineNow(element),
});
+ stopSlides(running);
+ }
+ const held = heldSlides.get(element);
+ heldSlides.delete(element);
+ if (held != null) {
+ stopSlides(held);
}
exits.get(element)?.cancel();
exits.delete(element);