An open source design system that's fully customizable and agent ready
TypeScript
fix(core): a layout change made late in a long task plays its motion instead of skipping past it (#9274)
Christopher Chedeau73996f1b2c56
diff --git a/.changeset/layout-start-after-block.md b/.changeset/layout-start-after-block.mdnew file mode 100644index 0000000000..1dbe55996c--- /dev/null+++ b/.changeset/layout-start-after-block.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A layout motion made late in a long main-thread task, such as a tap on a slow device, now plays instead of being skipped: under Reduce Motion the side navigation rail's cross-fade showed no fade at all after such a block. A layout change's animations start on the frame time the page last read only while that frame is at most 34 ms old; otherwise they start at the moment the change makes its first animation, so the block delays the motion. A glide such a change retargets carries on from where the compositor has it. An edge that rides such a glide, as the side navigation rail's does, moves with it. In Safari, a change that reverses such an edge mid-motion reads where the glide shows on the motion's own clock, so the edge no longer trails the content. Such a reversal also starts the rail's and the content area's fades from that moment, so the rail's icons no longer flash back. A change keeps one start from its first animation through the flush of its glides, and the parts riding those glides, however long the rest of the commit runs. A change that begins after a block since the last layout motion takes a fresh start, unless it joins an earlier change in the same area whose glides have not started yet. A side navigation collapse or expand made before the rail first paints, other than by its own toggle, lands at once, so a restored state never animates on load.++@vjeuxdiff --git a/apps/storybook/stories/SideNavInlineRef.stories.tsx b/apps/storybook/stories/SideNavInlineRef.stories.tsxnew file mode 100644index 0000000000..0916cafde6--- /dev/null+++ b/apps/storybook/stories/SideNavInlineRef.stories.tsx@@ -0,0 +1,58 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {useState} from 'react';+import {flushSync} from 'react-dom';+import {Button} from '@astryxdesign/core/Button';+import {SideNav, SideNavItem, SideNavSection} from '@astryxdesign/core/SideNav';+import {FolderIcon, HomeIcon} from '@heroicons/react/24/outline';++const meta: Meta<typeof SideNav> = {+ title: 'Core/SideNav',+ component: SideNav,+ parameters: {layout: 'centered'},+};++export default meta;+type Story = StoryObj<typeof SideNav>;++function InlineRefCollapseDemo() {+ const [isCollapsed, setIsCollapsed] = useState(false);+ const [, setRenderCount] = useState(0);+ return (+ <div style={{display: 'flex', gap: 16, height: 480}}>+ <SideNav+ // A new callback on every render, so React re-attaches the nav.+ ref={node => {+ void node;+ }}+ collapsible={{isCollapsed, onCollapsedChange: setIsCollapsed}}>+ <SideNavSection title="Main">+ <SideNavItem+ label="Dashboard"+ icon={HomeIcon}+ isSelected+ href="/dashboard"+ />+ <SideNavItem label="Projects" icon={FolderIcon} href="/projects" />+ </SideNavSection>+ </SideNav>+ <Button+ label={+ isCollapsed ? 'Expand after a render' : 'Collapse after a render'+ }+ onClick={() => {+ // One commit renders the nav again. A later commit in the same+ // frame changes its state, and that change plays its motion.+ flushSync(() => setRenderCount(count => count + 1));+ setIsCollapsed(collapsed => !collapsed);+ }}+ />+ </div>+ );+}++export const InlineRefCollapse: Story = {+ name: 'Inline ref collapse',+ render: () => <InlineRefCollapseDemo />,+};diff --git a/docs/specs/components/AppShell/AppShell.spec.md b/docs/specs/components/AppShell/AppShell.spec.mdindex e4de333ec2..00620f5e97 100644--- a/docs/specs/components/AppShell/AppShell.spec.md+++ b/docs/specs/components/AppShell/AppShell.spec.md@@ -185,7 +185,7 @@ the only component record in the AppShell root.| FR14 | Main content stays mounted across the breakpoint (`family:layout-regions` FR9); in addition, input values and focus inside `children` survive in both directions. | Current source and tests || FR15 | `className`, `style`, and `xstyle` merge onto the root after component styles. | Current source || FR16 | With `elevated`, a present `topNav`, and an inline side nav, the content area is a raised surface whose block-start, inline-start corner uses the page radius; otherwise the content wrapper creates no layout box. | Current source and stories |-| FR17 | While the side nav collapses or expands, the content area swaps its old wrap for its new one in place: the old wrap slides and fades out while the new wrap slides and fades in, on the side nav's one clock, `spec:AST-105` FR4's one shared motion (`springs.settle`; `component:SideNav` FR6). The old wrap is one transient copy, inert and hidden from assistive technology, removed when the swap ends (`architecture:component-style-authoring` INV7). When the old wrap is not copied, such as on a page too large to copy, no visible gap opens between the rail and the content during an expand. The content area never animates its width. Under reduced motion the swap follows `design:reduced-motion` DR2 under a coarse primary pointer and DR3 otherwise. | `spec:AST-105` FR8; `component:SideNav` FR6 |+| FR17 | While the side nav collapses or expands, the content area swaps its old wrap for its new one in place: the old wrap slides and fades out while the new wrap slides and fades in, on the side nav's one clock, `spec:AST-105` FR4's one shared motion (`springs.settle`; `component:SideNav` FR6). Before the side nav's first paint, a change it did not make with its own toggle lands at once, and the content area lands with it. So the initial state never animates. The old wrap is one transient copy, inert and hidden from assistive technology, removed when the swap ends (`architecture:component-style-authoring` INV7). When the old wrap is not copied, such as on a page too large to copy, no visible gap opens between the rail and the content during an expand. The content area never animates its width. Under reduced motion the swap follows `design:reduced-motion` DR2 under a coarse primary pointer and DR3 otherwise. | `spec:AST-105` FR8; `component:SideNav` FR6 || FR18 | AppShell is a layout root: at its root it applies Layout's `layoutReset` (`component:Layout` FR8), resetting every layout value its ancestors pass down, so its header, side, and main regions lay out the same inside a padded card, inside a Layout, or at the page root. The published container padding (`--container-padding-inline-start`, `--container-padding-inline-end`, `--container-padding-block-start`, `--container-padding-block-end`) resets to zero, so AppShell's Layout escapes nothing (`component:Layout` FR2). The Layout inset and region values (`--layout-padding-outer-x`, `--layout-padding-outer-y`, `--layout-padding-own-outer-x`, `--layout-padding-own-outer-y`, `--layout-padding-inner-x`, `--layout-padding-inner-y`, `--layout-content-width`, `--layout-alignment-width`, `--_layout-flush-block-start`, `--_layout-flush-block-end`), Section padding propagation (`--_section-padding-propagated`), and the container height cap (`--container-max-height`) reset to unset, as at the page root. The Layout area, slot, and divider-default contexts (`LayoutAreaContext`, `LayoutSlotsContext`, `LayoutDividerContext`) reset to their defaults. These names are internal protocol, not theme API (`architecture:container-padding` INV1). A caller's own props and styles on AppShell (`height`, `variant`, `contentPadding`, `mobileNav`, `className`, `style`, `xstyle`) still apply after the reset (FR15). Theme tokens, color mode, writing direction, and translations keep inheriting. | DEC-1; `architecture:container-padding` INV6 (the same reset at overlay roots) |### Allowed variation@@ -299,20 +299,20 @@ reachability, not a decision that it must stay unthemeable.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |-| FR1–FR4, AR1 | `AppShell.test.tsx` slot, landmark, banner, and ref suites; `AppShellMainKeyboard.a11y.browser.spec.ts` for main as a tab stop and its focus ring | Content only; each slot; mobile top bar with banner; Tab, Shift+Tab, click and skip link onto an overflowing main | A missing or duplicate landmark, or a nested banner, fails role queries. | `audit:AppShell/anatomy` |-| FR3, FR4 safe area | `AppShellSafeArea.test.tsx` declared insets for the header region, the sidenav-only mobile top bar, and main; `AppShellSafeArea.a11y.chromium.spec.ts` with the device's insets emulated | Portrait and landscape insets; right to left with a notch on one side; the sidenav-only top bar alone and below a banner, at rest and scrolled in `auto`; no insets; a child that fills main | Items under the status bar or a side inset, sides that follow the text direction instead of the device, a block-end padding other than `contentPadding` plus the bottom inset, a published inset that includes the safe area, or anything moving without insets fails. | `audit:AppShell/behavior` |-| FR5, AR2 | `AppShell.test.tsx` skip-link and keyboard suites | First Tab; Enter; click; translated text | Losing the href, the focus move, or tab order fails. | `audit:AppShell/accessibility` |-| FR6, PR1 | `AppShell.test.tsx` height-mode and main keyboard access suites; `observeMainOverflow.test.ts` | `fill`, `auto`, section header in `auto`; main fitting and overflowing in `fill` | Dropping the header's sticky placement, measuring the header in `fill`, or not measuring main, fails. | `audit:AppShell/behavior` |-| FR8 | `AppShell.test.tsx` breakpoint suites | `lg`, `xl`, `2xl`, explicit `md`, `none`; nearest, root, and built themes; SSR hint | Wrong map, inclusive edge, or `none` entering mobile fails. | `audit:AppShell/behavior` |-| FR9–FR12 | `AppShell.test.tsx` mobile suites; `MobileNavCloseEdgeCases.test.tsx` AppShell drawer suites | Sidenav only; both navs; heading-only TopNav; custom node | A missing toggle, duplicated items, a stale drawer, or an early hide fails. | `audit:AppShell/behavior` |-| FR13, AR3 | `AppShell.test.tsx` keyboard drawer and `useAppShellMobile` suites | Outside a shell; inside, closed and open | A wrong id link or stale state fails. | `audit:AppShell/accessibility` |-| FR14, AR4 | `AppShell.test.tsx` breakpoint continuity test | Desktop to mobile and back with a focused input | Remounting content loses the value or focus. | `audit:AppShell/behavior` |-| FR17 | `SideNavRailMotion.test.tsx`, `animatedLayout.boundary.test.ts`; `SideNavRailMotion.interaction.browser.spec.ts` frames of the content area during a side nav collapse (the scrolled `auto` page and `reducedMotion: 'always'` theme cases pending) | collapse and expand with an inline side nav; Reduce Motion under a coarse and under a fine primary pointer; `fill` and a scrolled `auto` page; a theme with `reducedMotion: 'always'`; a second toggle while the swap runs; an expand whose old wrap is not copied | a visible gap between the rail and the content, a content area that animates its width or moves on its own clock, an old wrap reachable by assistive technology or left after the swap, travel under Reduce Motion, anything but an opacity-only cross-fade of 200 ms or less under Reduce Motion on a coarse pointer (DR2), or any animated property under Reduce Motion on a fine pointer (DR3) fails | `audit:AppShell/behavior` |-| FR18 | `AppShellLayoutRoot.interaction.browser.spec.ts`, a real-browser geometry test of the Layout overhang, header logo, side region, and main region against the page-root render at desktop and phone widths, over the Inside Layout Hosts story; `AppShell.test.tsx` "AppShell layout root (FR18)" suite for the reset values, the reset contexts, and a caller style; `layoutReset.test.tsx` for the reset's coverage (`component:Layout` FR8) | AppShell at the page root; inside a Layout with `padding` and a divider-less header; inside a padded Card in a host that clips overflow; inside a Section with explicit padding; each with a caller `contentPadding` and `style` | A region box, inset, or main padding that differs from the page-root render, a shell clipped by its host, a Layout or Section inside `children` that takes the host's inset or divider default, or a caller prop that loses to the reset, fails | `audit:AppShell/behavior` |-| FR7, FR16 | `AppShell.stories.tsx` and visual baselines | `elevated` with both navs, at desktop width | A changed `elevated` background or missing corner shows in visual review. | `audit:AppShell/visual` |-| Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy and current targets | Missing, extra, stale, or multiply assigned mappings fail repository validation. | `audit:AppShell/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------ |+| FR1–FR4, AR1 | `AppShell.test.tsx` slot, landmark, banner, and ref suites; `AppShellMainKeyboard.a11y.browser.spec.ts` for main as a tab stop and its focus ring | Content only; each slot; mobile top bar with banner; Tab, Shift+Tab, click and skip link onto an overflowing main | A missing or duplicate landmark, or a nested banner, fails role queries. | `audit:AppShell/anatomy` |+| FR3, FR4 safe area | `AppShellSafeArea.test.tsx` declared insets for the header region, the sidenav-only mobile top bar, and main; `AppShellSafeArea.a11y.chromium.spec.ts` with the device's insets emulated | Portrait and landscape insets; right to left with a notch on one side; the sidenav-only top bar alone and below a banner, at rest and scrolled in `auto`; no insets; a child that fills main | Items under the status bar or a side inset, sides that follow the text direction instead of the device, a block-end padding other than `contentPadding` plus the bottom inset, a published inset that includes the safe area, or anything moving without insets fails. | `audit:AppShell/behavior` |+| FR5, AR2 | `AppShell.test.tsx` skip-link and keyboard suites | First Tab; Enter; click; translated text | Losing the href, the focus move, or tab order fails. | `audit:AppShell/accessibility` |+| FR6, PR1 | `AppShell.test.tsx` height-mode and main keyboard access suites; `observeMainOverflow.test.ts` | `fill`, `auto`, section header in `auto`; main fitting and overflowing in `fill` | Dropping the header's sticky placement, measuring the header in `fill`, or not measuring main, fails. | `audit:AppShell/behavior` |+| FR8 | `AppShell.test.tsx` breakpoint suites | `lg`, `xl`, `2xl`, explicit `md`, `none`; nearest, root, and built themes; SSR hint | Wrong map, inclusive edge, or `none` entering mobile fails. | `audit:AppShell/behavior` |+| FR9–FR12 | `AppShell.test.tsx` mobile suites; `MobileNavCloseEdgeCases.test.tsx` AppShell drawer suites | Sidenav only; both navs; heading-only TopNav; custom node | A missing toggle, duplicated items, a stale drawer, or an early hide fails. | `audit:AppShell/behavior` |+| FR13, AR3 | `AppShell.test.tsx` keyboard drawer and `useAppShellMobile` suites | Outside a shell; inside, closed and open | A wrong id link or stale state fails. | `audit:AppShell/accessibility` |+| FR14, AR4 | `AppShell.test.tsx` breakpoint continuity test | Desktop to mobile and back with a focused input | Remounting content loses the value or focus. | `audit:AppShell/behavior` |+| FR17 | `SideNavRailMotion.test.tsx`, with no motion for an app's change before the side nav's first paint; `animatedLayout.boundary.test.ts`; `SideNavRailMotion.interaction.browser.spec.ts` frames of the content area during a side nav collapse, and a second toggle after a long task (the scrolled `auto` page and `reducedMotion: 'always'` theme cases pending) | collapse and expand with an inline side nav; Reduce Motion under a coarse and under a fine primary pointer; `fill` and a scrolled `auto` page; a theme with `reducedMotion: 'always'`; a second toggle while the swap runs, and one after a long task; an expand whose old wrap is not copied | a visible gap between the rail and the content, a content area that animates its width or moves on its own clock, a reversal whose fades start behind its glide, an old wrap reachable by assistive technology or left after the swap, travel under Reduce Motion, anything but an opacity-only cross-fade of 200 ms or less under Reduce Motion on a coarse pointer (DR2), or any animated property under Reduce Motion on a fine pointer (DR3) fails | `audit:AppShell/behavior` |+| FR18 | `AppShellLayoutRoot.interaction.browser.spec.ts`, a real-browser geometry test of the Layout overhang, header logo, side region, and main region against the page-root render at desktop and phone widths, over the Inside Layout Hosts story; `AppShell.test.tsx` "AppShell layout root (FR18)" suite for the reset values, the reset contexts, and a caller style; `layoutReset.test.tsx` for the reset's coverage (`component:Layout` FR8) | AppShell at the page root; inside a Layout with `padding` and a divider-less header; inside a padded Card in a host that clips overflow; inside a Section with explicit padding; each with a caller `contentPadding` and `style` | A region box, inset, or main padding that differs from the page-root render, a shell clipped by its host, a Layout or Section inside `children` that takes the host's inset or divider default, or a caller prop that loses to the reset, fails | `audit:AppShell/behavior` |+| FR7, FR16 | `AppShell.stories.tsx` and visual baselines | `elevated` with both navs, at desktop width | A changed `elevated` background or missing corner shows in visual review. | `audit:AppShell/visual` |+| Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy and current targets | Missing, extra, stale, or multiply assigned mappings fail repository validation. | `audit:AppShell/theming` |Read from source, with no focused test or baseline yet:diff --git a/docs/specs/components/SideNav/SideNav.spec.md b/docs/specs/components/SideNav/SideNav.spec.mdindex 8a1fc41b16..f12993ec9b 100644--- a/docs/specs/components/SideNav/SideNav.spec.md+++ b/docs/specs/components/SideNav/SideNav.spec.md@@ -113,14 +113,14 @@ Consumer migration instructions belong in consumer docs and release notes.## Behavioral and layout contract-| ID | Invariant | Basis | Draft review state |-| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |-| FR1 | SideNav renders its navigation children in a scrollable list, which may be grouped by SideNavSection. A SideNavItem with children renders them, after its own row, in a group labelled by the parent's label; unless `collapsible` is `false`, the group expands and collapses and is hidden from assistive technology and inert while collapsed. | Current source, docs, and tests | Current behavior |-| FR2 | In a collapsed rail, a SideNavItem without an icon is not rendered; a leaf item renders icon-only, named by a non-blank caller `aria-label` or else its label; an item with children renders an icon-only trigger that opens a flyout listing its children as the flyout's top level. | Current source, docs, and tests | Current behavior |-| FR3 | In an expanded rail, in a flyout, and in the mobile navigation drawer, every SideNavItem row MUST span the full inline size of its list at any depth. A row at depth `n` MUST start its content `n` × `--spacing-6` beyond the row's own inline-start padding for its size, inside the row; the nested group MUST add no inset. A flyout's top level is depth 0. | `component:SideNav/DEC-1` | Settled intent; implementation may be staged |-| FR4 | The indent area MUST be part of the row's target: a click there, including a modified or middle click on a link row, does what the same click on the row's primary element does. When the row also carries an independent expand toggle or `actions`, the indent belongs to the primary link or button, and the toggle and actions keep their own activation at the row's trailing edge. | `component:SideNav/DEC-1`; `family:navigation-destinations` | Settled intent; implementation may be staged |-| FR5 | An expanded nested group MUST NOT clip its rows once it has finished opening, so a nested row's focus ring paints in full. The group MAY clip while collapsed and while it opens or closes. | `component:SideNav/DEC-1` | Settled intent; implementation may be staged |-| FR6 | Collapsing or expanding the rail plays one motion on one clock, `spec:AST-105` FR4's one shared motion (`springs.settle`): layout snaps to the final rail width at once, with no width animation, and the rail reveals or covers its labels by a clip, its edge riding the main content's glide and its labels and collapsed icons fading on the same clock (`spec:AST-105` FR9's inline two-state form; the clip and the ride are the shared edge reveal's, and SideNav's own code keeps only the fades; the rail lends no pane to its resize controller, so a collapse plays once; implementation gap: the clip and the ride still run in SideNav's own rail motion code, not in the shared edge reveal): a collapse ends in the real collapsed state, icons only, and an expand ends in the real expanded state, with its labels. On a collapse or an expand the rail's old state is one transient copy, inert and hidden from assistive technology, removed when the motion ends. The main content moves on the same clock, as `component:AppShell` FR17 states. Under reduced motion the rail follows `design:reduced-motion` DR2 under a coarse primary pointer and DR3 otherwise. Collapsing or expanding keeps the nav and its items mounted, a `resizable` rail included, so item state such as an open nested group, and focus, persist (AR3 governs focus on what the collapsed rail does not render). | `component:SideNav/DEC-2`; `component:AppShell` FR17; `spec:AST-105` FR8, FR9 | Verified by `SideNavRailMotion.test.tsx` and `SideNavRailMotion.interaction.browser.spec.ts`; the `reducedMotion: 'always'` theme case pending |+| ID | Invariant | Basis | Draft review state |+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1 | SideNav renders its navigation children in a scrollable list, which may be grouped by SideNavSection. A SideNavItem with children renders them, after its own row, in a group labelled by the parent's label; unless `collapsible` is `false`, the group expands and collapses and is hidden from assistive technology and inert while collapsed. | Current source, docs, and tests | Current behavior |+| FR2 | In a collapsed rail, a SideNavItem without an icon is not rendered; a leaf item renders icon-only, named by a non-blank caller `aria-label` or else its label; an item with children renders an icon-only trigger that opens a flyout listing its children as the flyout's top level. | Current source, docs, and tests | Current behavior |+| FR3 | In an expanded rail, in a flyout, and in the mobile navigation drawer, every SideNavItem row MUST span the full inline size of its list at any depth. A row at depth `n` MUST start its content `n` × `--spacing-6` beyond the row's own inline-start padding for its size, inside the row; the nested group MUST add no inset. A flyout's top level is depth 0. | `component:SideNav/DEC-1` | Settled intent; implementation may be staged |+| FR4 | The indent area MUST be part of the row's target: a click there, including a modified or middle click on a link row, does what the same click on the row's primary element does. When the row also carries an independent expand toggle or `actions`, the indent belongs to the primary link or button, and the toggle and actions keep their own activation at the row's trailing edge. | `component:SideNav/DEC-1`; `family:navigation-destinations` | Settled intent; implementation may be staged |+| FR5 | An expanded nested group MUST NOT clip its rows once it has finished opening, so a nested row's focus ring paints in full. The group MAY clip while collapsed and while it opens or closes. | `component:SideNav/DEC-1` | Settled intent; implementation may be staged |+| FR6 | Collapsing or expanding the rail plays one motion on one clock, `spec:AST-105` FR4's one shared motion (`springs.settle`): layout snaps to the final rail width at once, with no width animation, and the rail reveals or covers its labels by a clip, its edge riding the main content's glide and its labels and collapsed icons fading on the same clock (`spec:AST-105` FR9's inline two-state form; the clip and the ride are the shared edge reveal's, and SideNav's own code keeps only the fades; the rail lends no pane to its resize controller, so a collapse plays once; implementation gap: the clip and the ride still run in SideNav's own rail motion code, not in the shared edge reveal): a collapse ends in the real collapsed state, icons only, and an expand ends in the real expanded state, with its labels. On a collapse or an expand the rail's old state is one transient copy, inert and hidden from assistive technology, removed when the motion ends. The main content moves on the same clock, as `component:AppShell` FR17 states. A change made before the rail first paints lands at once, unless the rail's own toggle made it, so the initial state never animates. Under reduced motion the rail follows `design:reduced-motion` DR2 under a coarse primary pointer and DR3 otherwise. Collapsing or expanding keeps the nav and its items mounted, a `resizable` rail included, so item state such as an open nested group, and focus, persist (AR3 governs focus on what the collapsed rail does not render). | `component:SideNav/DEC-2`; `component:AppShell` FR17; `spec:AST-105` FR8, FR9 | Verified by `SideNavRailMotion.test.tsx` and `SideNavRailMotion.interaction.browser.spec.ts`; the `reducedMotion: 'always'` theme case pending |### Allowed variation@@ -208,17 +208,17 @@ Consumer migration instructions belong in consumer docs and release notes.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |-| FR1, FR2 | `SideNav.test.tsx` nesting, collapsible, and collapsed-rail suites | Nested, collapsible, collapsed rail, flyout | Removing the labelled group, its collapsed inert state, or the collapsed icon-only and flyout paths fails. | `audit:SideNav/anatomy` |-| FR3, ORD1 | Focused `SideNav.test.tsx` indent coverage, required with implementation | Depth 1 and 2; `sm` and `md`; split and actions rows; caller `style`; flyout | A group inset, a missing or wrong indent, a dropped caller `style`, an indent that overrides a caller-set inline-start padding, or an indented flyout top level fails. | `audit:SideNav/layout` |-| FR3, DD1 | Real-browser geometry over the SideNav nested stories | Depths 1–3; `sm`, `md`, `lg`; light and dark; right-to-left; mobile drawer | A nested row's box narrower than a top-level row's, or a label moved from its per-depth position, fails. | `audit:SideNav/layout` |-| FR4 | Real-browser click in the indent area of plain, split, and actions rows | Link and button rows; plain, modified, and middle clicks; nested rows with toggle and actions | A click in the indent that does nothing or differs from the same click on the primary element, or a toggle or action that activates the row, fails. | `audit:SideNav/behavior` |-| FR5, AR2 | `SideNav.test.tsx` group clipping case and real-browser keyboard focus on nested rows | Only-child and last nested rows; after opening; collapsed | A focus ring cut at any edge of an expanded group, or an expanded group that still clips, fails. | `audit:SideNav/a11y` |-| FR2, FR3 | Real-browser collapsed rail and flyout | Collapsed rail with nested children | Any change to the collapsed rail, or an indent on the flyout's top level, fails. | `audit:SideNav/layout` |-| AR1 | Accessibility-tree comparison of nested rows | Plain, split, and actions rows | Any change in role, name, state, or order fails. | `audit:SideNav/a11y` |-| FR6 | `SideNavRailMotion.test.tsx`; `SideNavRailMotion.interaction.browser.spec.ts` frames of a collapse and an expand under a finger and a mouse (the `reducedMotion: 'always'` theme case pending); `SideNav.test.tsx` "keeps its items mounted across a collapse" suite | collapse and expand; a mouse and a finger; Reduce Motion under a coarse and under a fine primary pointer; a theme with `reducedMotion: 'always'`; a second toggle while the motion runs; an open nested group across a collapse and an expand, plain and `resizable` | an animated width, a collapse that does not end icons-only, an expand that does not end with its labels, a rail copy reachable by assistive technology or left after the motion ends, travel under Reduce Motion, anything but an opacity-only change of 200 ms or less under Reduce Motion on a coarse pointer (DR2), or any animated property under Reduce Motion on a fine pointer (DR3) fails A nested group that closes, or item state that resets, across a collapse and an expand fails. | `audit:SideNav/behavior` |-| AR3 | `SideNav.test.tsx` collapse-focus suite; `SideNavCollapseFocus.a11y.chromium.spec.ts`; gap: a rail with no collapse toggle and no row it keeps has no destination, so focus there still falls to the page | Focus on an icon-less row with and without a toggle, also in a resizable SideNav; a nested row and a kept row's action without a toggle; a kept row's replaced link with a toggle; a footer control, the toggle and Enter on the resize handle in a resizable SideNav; an icon-less heading link the collapse removes; a heading link whose subheading the collapsed rail drops, in a resizable SideNav; focus outside the nav; focus on a row the rail keeps; expanding | Focus left on the page body, a move to anything but the kept row's own control, the same header or footer control under the same name, the in-nav toggle, or the nearest kept row (preceding first; the first from a removed header or footer control or the resize handle), or a move of focus the collapse did not take, fails. | `audit:SideNav/a11y` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |+| FR1, FR2 | `SideNav.test.tsx` nesting, collapsible, and collapsed-rail suites | Nested, collapsible, collapsed rail, flyout | Removing the labelled group, its collapsed inert state, or the collapsed icon-only and flyout paths fails. | `audit:SideNav/anatomy` |+| FR3, ORD1 | Focused `SideNav.test.tsx` indent coverage, required with implementation | Depth 1 and 2; `sm` and `md`; split and actions rows; caller `style`; flyout | A group inset, a missing or wrong indent, a dropped caller `style`, an indent that overrides a caller-set inline-start padding, or an indented flyout top level fails. | `audit:SideNav/layout` |+| FR3, DD1 | Real-browser geometry over the SideNav nested stories | Depths 1–3; `sm`, `md`, `lg`; light and dark; right-to-left; mobile drawer | A nested row's box narrower than a top-level row's, or a label moved from its per-depth position, fails. | `audit:SideNav/layout` |+| FR4 | Real-browser click in the indent area of plain, split, and actions rows | Link and button rows; plain, modified, and middle clicks; nested rows with toggle and actions | A click in the indent that does nothing or differs from the same click on the primary element, or a toggle or action that activates the row, fails. | `audit:SideNav/behavior` |+| FR5, AR2 | `SideNav.test.tsx` group clipping case and real-browser keyboard focus on nested rows | Only-child and last nested rows; after opening; collapsed | A focus ring cut at any edge of an expanded group, or an expanded group that still clips, fails. | `audit:SideNav/a11y` |+| FR2, FR3 | Real-browser collapsed rail and flyout | Collapsed rail with nested children | Any change to the collapsed rail, or an indent on the flyout's top level, fails. | `audit:SideNav/layout` |+| AR1 | Accessibility-tree comparison of nested rows | Plain, split, and actions rows | Any change in role, name, state, or order fails. | `audit:SideNav/a11y` |+| FR6 | `SideNavRailMotion.test.tsx`; `SideNavRailMotion.interaction.browser.spec.ts` frames of a collapse and an expand under a finger and a mouse, and of a second click after a long task (the `reducedMotion: 'always'` theme case pending); `SideNav.test.tsx` "keeps its items mounted across a collapse" suite | collapse and expand; a mouse and a finger; Reduce Motion under a coarse and under a fine primary pointer; a theme with `reducedMotion: 'always'`; a second toggle while the motion runs, and one after a long task; an app's change before the rail's first paint and after it, and the rail's own toggle before it; an open nested group across a collapse and an expand, plain and `resizable` | an animated width, a collapse that does not end icons-only, an expand that does not end with its labels, a rail copy reachable by assistive technology or left after the motion ends, a reversal whose fades start behind its edge, travel under Reduce Motion, anything but an opacity-only change of 200 ms or less under Reduce Motion on a coarse pointer (DR2), or any animated property under Reduce Motion on a fine pointer (DR3) fails A nested group that closes, or item state that resets, across a collapse and an expand fails. | `audit:SideNav/behavior` |+| AR3 | `SideNav.test.tsx` collapse-focus suite; `SideNavCollapseFocus.a11y.chromium.spec.ts`; gap: a rail with no collapse toggle and no row it keeps has no destination, so focus there still falls to the page | Focus on an icon-less row with and without a toggle, also in a resizable SideNav; a nested row and a kept row's action without a toggle; a kept row's replaced link with a toggle; a footer control, the toggle and Enter on the resize handle in a resizable SideNav; an icon-less heading link the collapse removes; a heading link whose subheading the collapsed rail drops, in a resizable SideNav; focus outside the nav; focus on a row the rail keeps; expanding | Focus left on the page body, a move to anything but the kept row's own control, the same header or footer control under the same name, the in-nav toggle, or the nearest kept row (preceding first; the first from a removed header or footer control or the resize handle), or a move of focus the collapse did not take, fails. | `audit:SideNav/a11y` |## Decision logdiff --git a/packages/core/src/AppShell/AppShell.tsx b/packages/core/src/AppShell/AppShell.tsxindex 6df6901823..6d7a8a040b 100644--- a/packages/core/src/AppShell/AppShell.tsx+++ b/packages/core/src/AppShell/AppShell.tsx@@ -59,6 +59,7 @@ import {holdLayoutSwap,landLayoutGlide,layoutMotionFor,+ layoutStartFor,playLayoutFrames,playLayoutSwap,reportLayoutChange,@@ -1000,9 +1001,13 @@ export function AppShell({let entering = 0;const last = lastSwapRef.current;if (last != null && motion.kind === 'spring') {- const elapsed =- Number(main.ownerDocument.timeline?.currentTime ?? 0) -- last.startedAt;+ // Read at the change's own start, where the glide it retargets+ // carries on. After a block, that is later than the frame the+ // timeline still reads.+ const elapsed = Math.max(+ 0,+ layoutStartFor(main.ownerDocument) - last.startedAt,+ );if (elapsed < motion.progress.durationMs) {const p = 1 - motion.progress.remaining(elapsed);held = last.entering + (1 - last.entering) * p;@@ -1062,7 +1067,7 @@ export function AppShell({}const {held, entering} = pending;lastSwapRef.current = {- startedAt: Number(main.ownerDocument.timeline?.currentTime ?? 0),+ startedAt: layoutStartFor(main.ownerDocument),held,entering,};diff --git a/packages/core/src/SideNav/SideNav.tsx b/packages/core/src/SideNav/SideNav.tsxindex 665d72ddce..4a07efcbe7 100644--- a/packages/core/src/SideNav/SideNav.tsx+++ b/packages/core/src/SideNav/SideNav.tsx@@ -438,6 +438,12 @@ interface PendingRailFocus {wasOnToggle: boolean;}+/** The timeline holds one time per frame, so two reads in one frame match. */+function frameTimeOf(doc: Document | undefined): number | null {+ const time = doc?.timeline?.currentTime;+ return time == null ? null : Number(time);+}+/*** Sidebar navigation container for application pages.*@@ -456,6 +462,7 @@ interface PendingRailFocus {* </SideNav>* ```*/+export function SideNav({header,topContent,@@ -498,7 +505,27 @@ export function SideNav({// The nav's own document's last input decides the moved focus's ring// (AR3), so a SideNav in a second document tracks input there.const {ref: modalityRef} = useInteractionModalityTracking();- const mergedNavRef = useMergedRefs(ref, navRef, modalityRef);+ // The initial state never animates. A change before the rail's first paint+ // lands at once, unless the rail's own toggle made it. Until a frame runs+ // after the nav attaches, the document timeline reads the frame it read+ // then.+ const mountFrameRef = useRef<number | null>(null);+ const mountedNavRef = useRef<HTMLElement | null>(null);+ const isOwnToggleRef = useRef(false);+ const recordMountFrame = useCallback((nav: HTMLElement | null) => {+ // An inline ref re-attaches the same nav on each render. Only a new nav+ // starts a new initial state.+ if (nav != null && nav !== mountedNavRef.current) {+ mountedNavRef.current = nav;+ mountFrameRef.current = frameTimeOf(nav.ownerDocument);+ }+ }, []);+ const mergedNavRef = useMergedRefs(+ ref,+ navRef,+ modalityRef,+ recordMountFrame,+ );const collapseStateRef = useRef<SideNavCollapseState>({isCollapsed: false,toggle: () => {},@@ -522,10 +549,10 @@ export function SideNav({const collapsed = resizableHook.isCollapsed;- // Every collapse or expand, whatever caused it, plays the rail's motion- // (`component:SideNav` FR6): measured in the commit before the DOM changes,- // played after it before paint. Inside AppShell the content area moves with- // it through AppShell's own handle (`component:AppShell` FR17); outside,+ // A collapse or expand plays the rail's motion, except an app's change+ // before the rail's first paint. It is measured in the commit before the+ // DOM changes and played after it, before paint. Inside AppShell the+ // content area moves with it through AppShell's own handle; outside,// SideNav holds its own over its parent.const shell = use(SideNavShellContext);// A resizable rail's wrapper holds the nav and the handle; outside AppShell@@ -548,6 +575,14 @@ export function SideNav({running?.rail.end();running?.endContent();motionRef.current = null;+ const isOwnToggle = isOwnToggleRef.current;+ isOwnToggleRef.current = false;+ const frame = frameTimeOf(navRef.current?.ownerDocument);+ if (!isOwnToggle && (frame == null || frame === mountFrameRef.current)) {+ railSnapshotRef.current = null;+ shell?.landContent();+ return;+ }railSnapshotRef.current = snapshotRail(shell?.rail() ?? ownRail(),shell?.animatedLayout ?? ownLayout,@@ -707,6 +742,7 @@ export function SideNav({const toggle = useCallback(() => {const next = !collapsed;+ isOwnToggleRef.current = true;// Deprecated `handleRef` path only: an out-of-tree button reads this// snapshot while rendering, which can happen before SideNav re-renders.diff --git a/packages/core/src/SideNav/SideNavRailMotion.test.tsx b/packages/core/src/SideNav/SideNavRailMotion.test.tsxindex 8cbdc1bebe..01c47edb1d 100644--- a/packages/core/src/SideNav/SideNavRailMotion.test.tsx+++ b/packages/core/src/SideNav/SideNavRailMotion.test.tsx@@ -2,6 +2,7 @@import {readFileSync} from 'node:fs';import {join} from 'node:path';+import type {ReactElement, Ref} from 'react';import {act, fireEvent, render, screen} from '@testing-library/react';import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';@@ -77,6 +78,10 @@ beforeEach(() => {configurable: true,value: {currentTime: 1000},});+ // The page's clock reads the timeline's frame time: no block since it.+ vi.spyOn(performance, 'now').mockImplementation(+ () => (document.timeline as {currentTime: number}).currentTime,+ );vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {const width = railWidth();@@ -111,6 +116,11 @@ beforeEach(() => {const listeners: (() => void)[] = [];const animation = {startTime: null as number | null,+ // As a browser reads it: the timeline's time since the start.+ get currentTime() {+ const now = (document.timeline as {currentTime: number}).currentTime;+ return animation.startTime == null ? 0 : now - animation.startTime;+ },finished: {then: () => undefined},onfinish: null as null | (() => void),addEventListener: (_type: string, listener: () => void) => {@@ -139,15 +149,27 @@ function Shell({isResizable = false,height = 'fill',hasCanvas = false,+ isCollapsed,+ navRef,}: {inShell?: boolean;hasNav?: boolean;isResizable?: boolean;height?: 'fill' | 'auto';hasCanvas?: boolean;+ /** Set: the app owns the collapse state. */+ isCollapsed?: boolean;+ navRef?: Ref<HTMLElement>;}) {const nav = (- <SideNav collapsible resizable={isResizable}>+ <SideNav+ ref={navRef}+ collapsible={+ isCollapsed === undefined+ ? true+ : {isCollapsed, onCollapsedChange: () => {}}+ }+ resizable={isResizable}><SideNavItem label="Home" icon={<svg aria-hidden="true" />} /><SideNavItem label="Projects" icon={<svg aria-hidden="true" />} />{hasCanvas && (@@ -179,6 +201,19 @@ async function toggle() {});}+/** A recorded `translate` animation's x offset at `ms`, between its keyframes. */+function translateAt(entry: Recorded, ms: number): number {+ const frames = entry.keyframes.map(frame =>+ parseFloat(String(frame.translate)),+ );+ const at =+ (Math.min(ms, Number(entry.options.duration)) /+ Number(entry.options.duration)) *+ (frames.length - 1);+ const i = Math.min(Math.floor(at), frames.length - 2);+ return frames[i] + (frames[i + 1] - frames[i]) * (at - i);+}+function animated(property: string): Recorded[] {return recorded.filter(entry =>entry.keyframes.some(frame => property in frame),@@ -285,13 +320,37 @@ describe('SideNav rail motion (component:SideNav FR6, component:AppShell FR17)',it('starts a change made mid-motion from the width the rail shows', async () => {render(<Shell />);await toggle();- // 150 ms into the collapse the clip shows part of the old rail: the- // column's glide shows it 102 px past its place, so the rail shows 150.+ // About 150 ms into the collapse, on one of the glide's keyframes, the+ // clip shows part of the old rail. The column shows past its place by its+ // glide's offset then.+ const main = screen.getByRole('main');+ const [slide] = animated('translate').filter(+ entry => entry.element !== main && entry.element.contains(main),+ );+ const step = Number(slide.options.duration) / (slide.keyframes.length - 1);+ const at = Math.round(150 / step) * step;+ const shift = translateAt(slide, at);Object.defineProperty(document, 'timeline', {configurable: true,- value: {currentTime: 1150},+ value: {currentTime: 1000 + at},});- columnShift = 102;+ columnShift = shift;+ // As an engine evaluates it: the column's computed translate is the+ // offset its box shows.+ const computedStyle = window.getComputedStyle.bind(window);+ vi.spyOn(window, 'getComputedStyle').mockImplementation(+ (element, pseudo) => {+ const style = computedStyle(element, pseudo);+ return element !== slide.element+ ? style+ : new Proxy(style, {+ get: (target, key) =>+ key === 'translate'+ ? `${columnShift}px 0px`+ : target[key as keyof CSSStyleDeclaration],+ });+ },+ );recorded = [];await toggle();const reveal = animated('clipPath').find(@@ -301,7 +360,8 @@ describe('SideNav rail motion (component:SideNav FR6, component:AppShell FR17)',/inset\(0px ([\d.]+)px/.exec(String(reveal?.keyframes[0].clipPath))?.[1],);// It reveals from the shown width, not from the collapsed one.- expect(start).toBe(EXPANDED - 150);+ expect(shift).toBeGreaterThan(50);+ expect(start).toBeCloseTo(EXPANDED - (COLLAPSED + shift), 6);});it('continues what the rail and the page show when a change reverses a running one', async () => {@@ -635,6 +695,66 @@ describe('SideNav rail motion (component:SideNav FR6, component:AppShell FR17)',}});+ /** The app sets the collapse state, then the glide's microtask runs. */+ async function setCollapsed(+ rerender: (ui: ReactElement) => void,+ isCollapsed: boolean,+ ) {+ await act(async () => {+ rerender(<Shell isCollapsed={isCollapsed} />);+ });+ }++ it('lands a change the app makes before the rail first paints at once, so the initial state never animates', async () => {+ const {rerender} = render(<Shell isCollapsed={false} />);+ // The app restores a saved state before any frame.+ await setCollapsed(rerender, true);++ expect(railWidth()).toBe(COLLAPSED);+ expect(recorded).toEqual([]);+ expect(copies()).toEqual([]);+ });++ it('plays a change the app makes once the rail has painted', async () => {+ const {rerender} = render(<Shell isCollapsed={false} />);+ // A frame later.+ Object.defineProperty(document, 'timeline', {+ configurable: true,+ value: {currentTime: 1016},+ });+ await setCollapsed(rerender, true);++ expect(railWidth()).toBe(COLLAPSED);+ expect(animated('clipPath')).toHaveLength(1);+ });++ it('plays a change the app makes once the rail has painted, through an inline ref too', async () => {+ const {rerender} = render(<Shell isCollapsed={false} navRef={() => {}} />);+ // A frame later, a render re-attaches the nav through a new inline ref.+ // The app then collapses the rail in a later commit of that frame.+ Object.defineProperty(document, 'timeline', {+ configurable: true,+ value: {currentTime: 1016},+ });+ await act(async () => {+ rerender(<Shell isCollapsed={false} navRef={() => {}} />);+ });+ await act(async () => {+ rerender(<Shell isCollapsed navRef={() => {}} />);+ });++ expect(railWidth()).toBe(COLLAPSED);+ expect(animated('clipPath')).toHaveLength(1);+ });++ it('plays a press on its own toggle before the first paint too', async () => {+ render(<Shell />);+ await toggle();++ expect(railWidth()).toBe(COLLAPSED);+ expect(animated('clipPath')).toHaveLength(1);+ });+it('changes at once without Web Animations', async () => {delete (HTMLElement.prototype as unknown as {animate?: unknown}).animate;render(<Shell />);diff --git a/packages/core/src/SideNav/__tests__/SideNavRailMotion.interaction.browser.spec.ts b/packages/core/src/SideNav/__tests__/SideNavRailMotion.interaction.browser.spec.tsindex b083751aaf..51d5a605cb 100644--- a/packages/core/src/SideNav/__tests__/SideNavRailMotion.interaction.browser.spec.ts+++ b/packages/core/src/SideNav/__tests__/SideNavRailMotion.interaction.browser.spec.ts@@ -13,7 +13,8 @@* stays continuous, an expand whose old wrap is not copied keeps the edges* together, and Reduce Motion cross-fades under a finger (DR2) and changes at* once under a mouse (DR3), also on a loaded machine: those two cases read- * the motion by its own start and end, never at a fixed time+ * the motion by its own start and end, never at a fixed time. A second press+ * after a long task starts its fades where the glide carries on.* @position Testing; the components' unit cases are* SideNav/SideNavRailMotion.test.tsx*@@ -669,6 +670,104 @@ test.describe('component:SideNav FR6 and component:AppShell FR17 under a mouse',});});+ test('a second click after a long task starts the fades where the glide carries on, as the same click without the task does', async ({+ page,+ }) => {+ await openStory(page, DESKTOP_STORY);+ // A collapse, then a click that reverses it 1150 ms later, its handler+ // busy for `blockMs` first. Returns the reversal's fades' first keyframes.+ const reverse = async (blockMs: number) =>+ page.evaluate(async blockMs => {+ const toggle = () =>+ [...document.querySelectorAll('button')].find(button =>+ /^(Collapse|Expand) sidebar$/.test(+ button.getAttribute('aria-label') ?? button.textContent ?? '',+ ),+ ) as HTMLElement;+ const frame = async () =>+ new Promise<void>(resolve => {+ requestAnimationFrame(() => resolve());+ });+ toggle().click();+ const collapsed = performance.now();+ while (performance.now() - collapsed < 1150 - blockMs) {+ await frame();+ }+ await new Promise<void>(resolve => {+ setTimeout(resolve, 0);+ });+ // A press's own feedback reads the timeline first. That holds its time+ // for the rest of this task, as on a real page.+ void document.timeline.currentTime;+ const busy = performance.now() + blockMs;+ while (performance.now() < busy) {+ // the click handler's own work+ }+ const before = new Set(document.getAnimations());+ toggle().click();+ await new Promise<void>(resolve => {+ setTimeout(resolve, 0);+ });+ const main = document.querySelector('[role="main"]');+ const first = (match: (target: Element) => boolean) => {+ const animation = document.getAnimations().find(candidate => {+ const effect = candidate.effect as KeyframeEffect | null;+ const target = effect?.target;+ return (+ !before.has(candidate) &&+ target instanceof Element &&+ match(target) &&+ effect?.getKeyframes().some(frame => frame.opacity != null)+ );+ });+ const opacity = (+ animation?.effect as KeyframeEffect | undefined+ )?.getKeyframes()[0]?.opacity;+ return opacity == null ? null : Number(opacity);+ };+ const copyOf = (target: Element) => target.closest('[inert]');+ return {+ // The content's old wrap, held as its copy, and the new wrap.+ wrapCopy: first(+ target =>+ copyOf(target) === target && target.querySelector('nav') == null,+ ),+ newWrap: first(+ target => copyOf(target) == null && target.parentElement === main,+ ),+ // The rail's old state, held as its copy.+ railCopy: first(+ target =>+ copyOf(target) === target && target.querySelector('nav') != null,+ ),+ };+ }, blockMs);+ const settle = async () => {+ await expect+ .poll(async () => {+ const rest = await railAtRest(page);+ return rest.copies + rest.running;+ })+ .toBe(0);+ };+ const free = await reverse(0);+ await settle();+ const blocked = await reverse(1000);+ await settle();+ test.info().annotations.push({+ type: 'reversal fades (free, blocked)',+ description: JSON.stringify({free, blocked}),+ });+ for (const key of ['wrapCopy', 'newWrap', 'railCopy'] as const) {+ expect(free[key], key).not.toBeNull();+ expect(blocked[key], key).not.toBeNull();+ expect(+ Math.abs(Number(blocked[key]) - Number(free[key])),+ key,+ ).toBeLessThan(0.1);+ }+ });+for (const load of LOADS) {test(`under Reduce Motion a click changes the rail and the page at once${underLoad(load)} (design:reduced-motion DR3)`, async ({page,diff --git a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.tsindex aaaa7214ed..7e76d8d384 100644--- a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts+++ b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts@@ -770,6 +770,441 @@ test.describe('spec:AST-105 Coverage', () => {});}+ test('a change made after a block longer than its motion still shows its motion: the block delays it instead of skipping past it', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area"><div id="grow" class="grow"></div>+ <div id="after" class="row"></div></div>`,+ );+ const run = await page.evaluate(async mutate => {+ const frame = async () =>+ new Promise<number>(resolve => requestAnimationFrame(resolve));+ await frame();+ // In a task after that frame, something reads the timeline first, as+ // any animation started there does. That holds its time for the rest of+ // the task. Then the page is busy for 1000 ms and makes the change.+ await new Promise<void>(resolve => {+ setTimeout(resolve, 0);+ });+ const early = document.timeline.currentTime;+ const end = performance.now() + 1000;+ while (performance.now() < end) {+ // the page's main thread is busy+ }+ const held = document.timeline.currentTime === early;+ await window.change({changed: '#grow', mutate});+ const [animation] = (+ document.querySelector('#after') as HTMLElement+ ).getAnimations();+ const duration = Number(animation.effect?.getComputedTiming().endTime);+ await frame();+ await frame();+ return {+ duration,+ held,+ playState: animation.playState,+ currentTime: Number(animation.currentTime),+ };+ }, OPEN_GROW);+ test.info().annotations.push({+ type: 'after a block',+ description: JSON.stringify(run),+ });+ // The timeline still read the time from before the block, and the glide+ // is shorter than the block. Started on that time, it would be over by the+ // first frame after the block.+ expect(run.held).toBe(true);+ expect(run.duration).toBeLessThan(1000);+ expect(run.playState).toBe('running');+ expect(run.currentTime).toBeLessThan(run.duration / 2);+ });++ test('a change made after a block retargets a running glide from where the compositor has it, not from before the block', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area"><div id="grow" class="grow"></div>+ <div id="second" class="grow"></div><div id="after" class="row"></div></div>`,+ );+ await change(page);+ await page.waitForTimeout(100);+ const run = await page.evaluate(async mutate => {+ const row = document.querySelector('#after') as HTMLElement;+ const frame = async () =>+ new Promise<number>(resolve => requestAnimationFrame(resolve));+ await frame();+ await new Promise<void>(resolve => {+ setTimeout(resolve, 0);+ });+ // Reading the glide reads the timeline, which then holds its time for+ // the rest of this task.+ const [first] = row.getAnimations();+ const heldElapsed = Number(first.currentTime);+ const yHeld = window.glideBoxOf(row).top;+ const keyframes =+ (first.effect as KeyframeEffect | null)?.getKeyframes() ?? [];+ const duration = Number(first.effect?.getComputedTiming().duration);+ // The glide's y offset `elapsed` ms after its start, from its keyframes.+ const yAt = (elapsed: number) => {+ const p = Math.min(1, Math.max(0, elapsed / duration));+ for (let i = 0; i + 1 < keyframes.length; i++) {+ const a = keyframes[i].computedOffset;+ const b = keyframes[i + 1].computedOffset;+ if (p >= a && p <= b) {+ const ya = parseFloat(String(keyframes[i].translate).split(' ')[1]);+ const yb = parseFloat(+ String(keyframes[i + 1].translate).split(' ')[1],+ );+ return ya + ((yb - ya) * (p - a)) / Math.max(b - a, 1e-9);+ }+ }+ return 0;+ };+ const end = performance.now() + 400;+ while (performance.now() < end) {+ // the page's main thread is busy+ }+ // Where the compositor has the row as the block ends.+ const reached =+ yHeld ++ yAt(performance.now() - Number(first.startTime)) -+ yAt(heldElapsed);+ await window.change({changed: '#second', mutate});+ await frame();+ await frame();+ return {yHeld, reached, shown: window.glideBoxOf(row).top};+ }, `document.querySelector('#second').classList.add('open')`);+ test.info().annotations.push({+ type: 'a retarget after a block',+ description: JSON.stringify(run),+ });+ // The row glides down. Two frames after the block it is past where the+ // compositor had it as the block ended, not back near its place before.+ expect(run.reached).toBeGreaterThan(run.yHeld + 20);+ expect(run.shown).toBeGreaterThanOrEqual(run.reached - 1);+ });++ test('a change made after a block that follows an earlier layout motion in the same task still shows its motion', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area" style="height: 200px"><div id="grow" class="grow"></div>+ <div id="after" class="row"></div></div>+ <div id="area2" class="area" style="height: 200px"><div id="grow2" class="grow"></div>+ <div id="after2" class="row"></div></div>`,+ );+ const run = await page.evaluate(async () => {+ const frame = async () =>+ new Promise<number>(resolve => requestAnimationFrame(resolve));+ await frame();+ // In one task after that frame: a layout motion, then the page busy+ // for 1000 ms, then a second change.+ await new Promise<void>(resolve => {+ setTimeout(resolve, 0);+ });+ const early = document.timeline.currentTime;+ await window.change({+ changed: '#grow',+ area: '#area',+ mutate: `document.querySelector('#grow').classList.add('open')`,+ });+ const end = performance.now() + 1000;+ while (performance.now() < end) {+ // the page's main thread is busy+ }+ const blockEnd = performance.now();+ const held = document.timeline.currentTime === early;+ await window.change({+ changed: '#grow2',+ area: '#area2',+ mutate: `document.querySelector('#grow2').classList.add('open')`,+ });+ const [animation] = (+ document.querySelector('#after2') as HTMLElement+ ).getAnimations();+ const duration = Number(animation.effect?.getComputedTiming().endTime);+ return {+ duration,+ held,+ blockEnd,+ startTime: Number(animation.startTime),+ early: Number(early),+ };+ });+ test.info().annotations.push({+ type: 'a second change after a block',+ description: JSON.stringify(run),+ });+ // The timeline still read the time from before the block, and the second+ // change's glide is shorter than the block. Started on that time, as the+ // first change's was, it would be over by the first frame after the block.+ // It starts at the change instead, after the block, whenever the frames+ // after it come.+ expect(run.held).toBe(true);+ expect(run.duration).toBeLessThan(1000);+ expect(run.startTime).toBeGreaterThanOrEqual(run.blockEnd);+ });++ test('a swap whose parts ride the glide starts them with the glide, on the start read for the change, however late in its frame the change is made', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area" style="height: 300px"><div id="grow" class="grow"></div>+ <div id="after" class="row"></div></div>`,+ );+ const run = await page.evaluate(async () => {+ await new Promise<number>(resolve => requestAnimationFrame(resolve));+ const container = document.querySelector('#area') as HTMLElement;+ const target = document.querySelector('#grow') as HTMLElement;+ const row = document.querySelector('#after') as HTMLElement;+ const layout = window.AnimatedLayout.createAnimatedLayout(+ () => container,+ );+ const report = window.AnimatedLayout.reportLayoutChange(+ layout,+ () => target,+ );+ report.measureBefore();+ const swap = window.AnimatedLayout.holdLayoutSwap(layout, row, {+ isVisiblePart: true,+ });+ target.classList.add('open');+ // Late in the frame: the change's start is the moment it is made.+ const end = performance.now() + 50;+ while (performance.now() < end) {+ // the page's main thread is busy+ }+ report.animate();+ // As a shell does, it reads the change's start for its own clock. Then+ // it plays a swap whose parts ride the row's glide, which flushes first.+ const startedAt = window.AnimatedLayout.layoutStartFor(document);+ if (swap != null) {+ window.AnimatedLayout.playLayoutSwap(swap, {+ host: container,+ copy: p => ({opacity: 1 - p}),+ rideWith: {element: row, travel: {x: 0, y: 80}},+ incoming: [],+ });+ }+ await new Promise<void>(resolve => {+ setTimeout(resolve, 0);+ });+ const glide = row+ .getAnimations()+ .find(animation => animation.playState !== 'finished');+ const copy = swap?.copy.getAnimations()[0];+ return {+ startedAt,+ glide: glide == null ? null : Number(glide.startTime),+ copy: copy == null ? null : Number(copy.startTime),+ };+ });+ test.info().annotations.push({+ type: 'the starts of a riding swap',+ description: JSON.stringify(run),+ });+ expect(run.glide).not.toBeNull();+ expect(run.copy).not.toBeNull();+ expect(run.glide).toBe(run.startedAt);+ expect(run.copy).toBe(run.startedAt);+ });++ test('a change begun after a block that follows an earlier layout motion, with nothing run between them, still shows its motion', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area" style="height: 200px"><div id="grow" class="grow"></div>+ <div id="after" class="row"></div></div>+ <div id="area2" class="area" style="height: 200px"><div id="grow2" class="grow"></div>+ <div id="after2" class="row"></div></div>`,+ );+ const run = await page.evaluate(async () => {+ await new Promise<number>(resolve => requestAnimationFrame(resolve));+ await new Promise<void>(resolve => {+ setTimeout(resolve, 0);+ });+ const early = document.timeline.currentTime;+ const make = (area: string, changed: string) => {+ const container = document.querySelector(area);+ const target = document.querySelector(changed) as HTMLElement;+ const layout = window.AnimatedLayout.createAnimatedLayout(+ () => container,+ );+ const report = window.AnimatedLayout.reportLayoutChange(+ layout,+ () => target,+ );+ report.measureBefore();+ target.classList.add('open');+ report.animate();+ return window.AnimatedLayout.playLayoutChange(layout, target);+ };+ // In one run of script, with no microtask between: a layout change,+ // the page busy for 1000 ms, then a second change.+ const firstEntrance = make('#area', '#grow');+ const end = performance.now() + 1000;+ while (performance.now() < end) {+ // the page's main thread is busy+ }+ const blockEnd = performance.now();+ const held = document.timeline.currentTime === early;+ const entrance = make('#area2', '#grow2');+ await new Promise<void>(resolve => {+ queueMicrotask(resolve);+ });+ const [glide] = (+ document.querySelector('#after2') as HTMLElement+ ).getAnimations();+ const [firstGlide] = (+ document.querySelector('#after') as HTMLElement+ ).getAnimations();+ return {+ held,+ blockEnd,+ entrance: entrance == null ? null : Number(entrance.startTime),+ glide: glide == null ? null : Number(glide.startTime),+ firstEntrance:+ firstEntrance == null ? null : Number(firstEntrance.startTime),+ firstGlide: firstGlide == null ? null : Number(firstGlide.startTime),+ };+ });+ test.info().annotations.push({+ type: 'a change begun after a block',+ description: JSON.stringify(run),+ });+ // The second change takes a start of its own, after the block, and its+ // entrance and glide share it. The first change's glide, made at its flush+ // after the block, keeps the start its own entrance took. Two starts there+ // would leave its rows over the content it reveals.+ expect(run.held).toBe(true);+ expect(run.entrance).not.toBeNull();+ expect(Number(run.entrance)).toBeGreaterThanOrEqual(run.blockEnd);+ expect(run.glide).toBe(run.entrance);+ expect(run.firstEntrance).not.toBeNull();+ expect(run.firstGlide).toBe(run.firstEntrance);+ });++ test('a change\u2019s own entrance and the glide of the content after it share one start, however long the rest of its commit runs', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area" style="height: 300px"><div id="grow" class="grow"></div>+ <div id="after" class="row"></div></div>`,+ );+ const run = await page.evaluate(async () => {+ await new Promise<number>(resolve => requestAnimationFrame(resolve));+ const container = document.querySelector('#area');+ const target = document.querySelector('#grow') as HTMLElement;+ const layout = window.AnimatedLayout.createAnimatedLayout(+ () => container,+ );+ const report = window.AnimatedLayout.reportLayoutChange(+ layout,+ () => target,+ );+ report.measureBefore();+ target.classList.add('open');+ report.animate();+ // The entrance plays in the adopter's layout effect. The glide of the+ // row after it is made once the commit's other layout effects have run,+ // here 60 ms of them.+ const entrance = window.AnimatedLayout.playLayoutChange(layout, target);+ const end = performance.now() + 60;+ while (performance.now() < end) {+ // the rest of the commit+ }+ await new Promise<void>(resolve => {+ queueMicrotask(resolve);+ });+ const [glide] = (+ document.querySelector('#after') as HTMLElement+ ).getAnimations();+ return {+ entrance: entrance == null ? null : Number(entrance.startTime),+ glide: glide == null ? null : Number(glide.startTime),+ };+ });+ test.info().annotations.push({+ type: 'the starts of one change',+ description: JSON.stringify(run),+ });+ // Two starts would put the revealed edge ahead of the row after it for+ // the whole motion.+ expect(run.entrance).not.toBeNull();+ expect(run.glide).not.toBeNull();+ expect(run.glide).toBe(run.entrance);+ });++ test('in a same-origin frame made after the page, a change glides at once, on that frame\u2019s own clock', async ({+ page,+ }) => {+ await open(page, '<div id="host"></div>');+ const run = await page.evaluate(async style => {+ const frame = async (view: Window) =>+ new Promise<number>(resolve => view.requestAnimationFrame(resolve));+ // Frames first, so the frame's clock starts well after the page's.+ for (let i = 0; i < 30; i++) {+ await frame(window);+ }+ const iframe = document.createElement('iframe');+ iframe.style.cssText = 'width: 400px; height: 600px; border: 0';+ iframe.srcdoc = `<!doctype html><style>${style}</style>+ <div id="area" class="area"><div id="grow" class="grow"></div>+ <div id="after" class="row"></div></div>`;+ const loaded = new Promise(resolve => {+ iframe.addEventListener('load', resolve, {once: true});+ });+ document.getElementById('host')?.appendChild(iframe);+ await loaded;+ const doc = iframe.contentDocument as Document;+ const view = iframe.contentWindow as Window;+ await frame(view);+ await frame(view);+ const area = doc.getElementById('area') as HTMLElement;+ const grow = doc.getElementById('grow') as HTMLElement;+ const layout = window.AnimatedLayout.createAnimatedLayout(() => area);+ const report = window.AnimatedLayout.reportLayoutChange(+ layout,+ () => grow,+ );+ report.measureBefore();+ grow.classList.add('open');+ report.animate();+ window.AnimatedLayout.playLayoutChange(layout, grow);+ await new Promise<void>(resolve => {+ queueMicrotask(resolve);+ });+ const [animation] = (+ doc.getElementById('after') as HTMLElement+ ).getAnimations();+ await frame(view);+ await frame(view);+ return {+ gap: performance.now() - view.performance.now(),+ playState: animation.playState,+ currentTime: Number(animation.currentTime),+ };+ }, BASE_STYLE);+ test.info().annotations.push({+ type: 'a change in a frame',+ description: JSON.stringify(run),+ });+ // The frame's clock started well after the page's...+ expect(run.gap).toBeGreaterThan(100);+ // ...and the row after the change glides from the first frames, rather+ // than holding its old place until the page's clock comes round.+ expect(run.playState).toBe('running');+ expect(run.currentTime).toBeGreaterThanOrEqual(0);+ expect(run.currentTime).toBeLessThan(200);+ });+test('nested areas: motion stops at the inner area; an inner area moves as one unit', async ({page,}) => {@@ -2324,6 +2759,108 @@ test.describe('spec:AST-105 FR9 (the edge reveal)', () => {});}+ test('the two-state form reversed after a block keeps the edge on the column it rides: the edge starts where the column shows, not where it showed before the block', async ({+ page,+ browserName,+ }) => {+ await open(+ page,+ `<div id="area" class="area"><div id="row" style="display: flex; height: 300px">+ <nav id="panel" style="width: 260px; flex: none; background: #ccf"><span>Projects</span></nav>+ <div id="column" style="flex: 1; background: #efe">The page</div>+ </div></div>`,+ '#panel.narrow { width: 48px !important; }',+ );+ const result = await page.evaluate(async () => {+ const area = document.querySelector('#area');+ const panel = document.querySelector('#panel') as HTMLElement;+ const column = document.querySelector('#column') as HTMLElement;+ const AL = window.AnimatedLayout;+ const layout = AL.createAnimatedLayout(() => area);+ const frames: EdgeFrame[] = [];+ const read = (phase: string) => {+ const box = panel.getBoundingClientRect();+ const next = window.glideBoxOf(column);+ const inset = window.insetOf(panel);+ const computed = window.computedInsetOf(panel);+ frames.push({+ phase,+ edge: box.right - inset.right,+ beside: next.left,+ shown: box.width - inset.left - inset.right,+ skew:+ Math.abs(computed.left - inset.left) ++ Math.abs(computed.right - inset.right) ++ Math.abs(column.getBoundingClientRect().left - next.left),+ });+ };+ const frame = async () =>+ new Promise<void>(resolve => {+ requestAnimationFrame(() => resolve());+ });+ await frame();+ // A collapse, left to run for 120 ms.+ let hold = AL.holdLayoutEdge(layout, panel, {edge: 'inline-end'});+ let report = AL.reportLayoutChange(layout, () => panel);+ report.measureBefore();+ panel.classList.add('narrow');+ report.animate();+ const motion = AL.playLayoutEdge(hold!, panel, layout, {+ edge: 'inline-end',+ rideWith: column,+ });+ const start = performance.now();+ while (performance.now() - start < 120) {+ await frame();+ }+ await new Promise<void>(resolve => {+ setTimeout(resolve, 0);+ });+ // The toggle back runs late in its task, after 50 ms of other work.+ // It reads what the panel shows, then its own work runs for 400 ms.+ const late = performance.now() + 50;+ while (performance.now() < late) {+ // the page's main thread is busy+ }+ const shownBefore = motion.shown()?.extent ?? null;+ const end = performance.now() + 400;+ while (performance.now() < end) {+ // the page's main thread is busy+ }+ motion.end();+ hold = AL.holdLayoutEdge(layout, panel, {+ edge: 'inline-end',+ shown: shownBefore,+ });+ report = AL.reportLayoutChange(layout, () => panel);+ report.measureBefore();+ panel.classList.remove('narrow');+ report.animate();+ AL.playLayoutEdge(hold!, panel, layout, {+ edge: 'inline-end',+ rideWith: column,+ });+ for (let i = 0; i < 60; i++) {+ await frame();+ read('expanding');+ }+ return {frames, shownBefore};+ });+ test.info().annotations.push({+ type: 'a two-state reversal after a block',+ description: JSON.stringify({+ shownBefore: result.shownBefore,+ first: result.frames[0],+ }),+ });+ const moving = result.frames.filter(f => f.shown > 48.5 && f.shown < 259.5);+ expect(moving.length).toBeGreaterThan(5);+ for (const f of moving) {+ expect(Math.abs(f.beside - f.edge), JSON.stringify(f)).toBeLessThan(1.5);+ }+ reportSkew(moving, browserName);+ });+for (const [side, direction, collapsed] of [['start', 'ltr', 48],['start', 'rtl', 0],diff --git a/packages/core/src/motion/__tests__/animatedLayoutBundle.ts b/packages/core/src/motion/__tests__/animatedLayoutBundle.tsindex d74379b04a..4d55fc4290 100644--- a/packages/core/src/motion/__tests__/animatedLayoutBundle.ts+++ b/packages/core/src/motion/__tests__/animatedLayoutBundle.ts@@ -12,8 +12,11 @@ export {createAnimatedLayout,holdLayoutEdge,holdLayoutExit,+ holdLayoutSwap,+ layoutStartFor,playLayoutChange,playLayoutEdge,+ playLayoutSwap,releaseLayoutExit,reportLayoutChange,reportLayoutEdge,diff --git a/packages/core/src/motion/animatedLayout.edge.test.ts b/packages/core/src/motion/animatedLayout.edge.test.tsindex 7e740d4903..d90f307cc0 100644--- a/packages/core/src/motion/animatedLayout.edge.test.ts+++ b/packages/core/src/motion/animatedLayout.edge.test.ts@@ -67,6 +67,8 @@ beforeEach(() => {played = [];media = {};setTimeline(1000);+ // The page's clock reads the timeline's frame time: no block since it.+ vi.spyOn(performance, 'now').mockImplementation(timelineNow);Element.prototype.animate = function (this: Element,keyframes: Keyframe[] | PropertyIndexedKeyframes | null,diff --git a/packages/core/src/motion/animatedLayout.swap.test.ts b/packages/core/src/motion/animatedLayout.swap.test.tsindex 325d5179be..167245bb07 100644--- a/packages/core/src/motion/animatedLayout.swap.test.ts+++ b/packages/core/src/motion/animatedLayout.swap.test.ts@@ -42,6 +42,10 @@ beforeEach(() => {configurable: true,value: {currentTime: 500},});+ // The page's clock reads the timeline's frame time: no block since it.+ vi.spyOn(performance, 'now').mockImplementation(+ () => (document.timeline as {currentTime: number}).currentTime,+ );Element.prototype.animate = function (this: Element,keyframes: Keyframe[] | PropertyIndexedKeyframes | null,@@ -154,6 +158,38 @@ describe('the in-place swap (spec:AST-105 FR8)', () => {expect(typeof end).toBe('function');});+ it('starts every part of one swap together however long making them takes, with no block between two of them', () => {+ const {handle, content, host} = setup();+ const swap = holdLayoutSwap(handle, content);+ const parts = [0, 1, 2, 3].map(() => {+ const part = document.createElement('span');+ host.appendChild(part);+ return part;+ });+ // A slow page: each part takes 15 ms to make, 75 ms in all, while the+ // timeline still reads the frame before them.+ let page = 500;+ vi.spyOn(performance, 'now').mockImplementation(() => page);+ const animate = Element.prototype.animate;+ Element.prototype.animate = function (+ this: Element,+ ...args: Parameters<Element['animate']>+ ) {+ const animation = animate.apply(this, args);+ page += 15;+ return animation;+ };+ playLayoutSwap(swap!, {+ host,+ copy: travel,+ incoming: parts.map(element => ({element, frames: p => ({opacity: p})})),+ });+ expect(played.length).toBe(5);+ expect(new Set(played.map(entry => entry.startTime))).toEqual(+ new Set([500]),+ );+ });+it("fades the copy's text on its own curve when asked", () => {const {handle, content, host} = setup();const swap = holdLayoutSwap(handle, content);diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.tsindex d606a79289..5e2dccb25e 100644--- a/packages/core/src/motion/animatedLayout.ts+++ b/packages/core/src/motion/animatedLayout.ts@@ -3,15 +3,16 @@/*** @file animatedLayout.ts* @input The DOM (layout rectangles, computed style), Web Animations, the- * internal `springs.settle` motion role (motion/roles.ts) and the Reduce Motion- * cross-fade clock (uikit/timing.ts)- * @output Exports `createAnimatedLayout` and the opaque `AnimatedLayout`- * handle, `reportLayoutChange`, `playLayoutChange`, `holdLayoutExit` /- * `releaseLayoutExit`, the in-place swap (`holdLayoutSwap` /- * `playLayoutSwap`), the edge reveal's two-state form (`holdLayoutEdge` /- * `playLayoutEdge`), `playLayoutFrames` and `applyLayoutChangeTransition`:- * the one module that produces the size-change glide and the edge reveal- * `spec:AST-105` defines (`architecture:react-component-runtime` INV12)+ * internal `springs.settle` motion role (motion/roles.ts), the Reduce Motion+ * cross-fade clock (uikit/timing.ts) and the block measure (frameBlock.ts)+ * @output Exports `createAnimatedLayout`, the opaque `AnimatedLayout` handle,+ * `reportLayoutChange`, `playLayoutChange` and `layoutStartFor`. It also+ * exports the exit hold (`holdLayoutExit`, `releaseLayoutExit`), the+ * in-place swap (`holdLayoutSwap`, `playLayoutSwap`), the edge reveal's+ * two-state form (`holdLayoutEdge`, `playLayoutEdge`), `playLayoutFrames`+ * and `applyLayoutChangeTransition`. It is the one module that produces the+ * size-change glide and the edge reveal `spec:AST-105` defines+ * (`architecture:react-component-runtime` INV12)* @position Motion foundation, internal to core. A handle comes from the* public `useAnimatedLayout` hook; a component that takes it reports its* size changes through this module.@@ -79,6 +80,7 @@* (`spec:AST-105` FR2).*/+import {LATE_START_MS} from './frameBlock';import {motionRole} from './roles';import {inertCopy,@@ -228,6 +230,7 @@ function safeAnimate(element: Element,keyframes: Keyframe[],options: KeyframeAnimationOptions,+ change?: ChangeStart,): Animation | null {if (typeof (element as HTMLElement).animate !== 'function') {return null;@@ -239,16 +242,152 @@ function safeAnimate(return null;}ours.add(animation);- // Started on the document timeline's current time, not on the next frame:- // a retargeted glide keeps moving through the frame it is replaced in, and- // every animation of one change shares the same start.- const now = element.ownerDocument.timeline?.currentTime;+ // The animation starts on the document timeline's current time, not on the+ // next frame. So a retargeted glide keeps moving through the frame it is+ // replaced in. After a block since that frame, Chromium's timeline still+ // reads the frame before the block. A motion started there would skip into+ // its curve, or past all of it. So it starts at the moment of the change+ // instead, and the block delays the motion (startFor). Every animation of+ // one change, in one document, shares that start.+ const doc = element.ownerDocument;+ const now = doc.timeline?.currentTime;if (now != null) {- animation.startTime = now;+ // The start of the change it is part of, captured when that change made+ // its first animation (changeStartOf); otherwise the document's.+ const start =+ change != null && change.frame === Number(now)+ ? change+ : startFor(doc, Number(now));+ start.last = clockOf(doc);+ animation.startTime = start.at;+ if (start.at !== Number(now)) {+ // Started after the frame time the timeline still reads: until the+ // timeline gets there it shows its first keyframe, not the element at+ // rest.+ const fill = animation.effect?.getTiming().fill;+ animation.effect?.updateTiming({+ fill: fill === 'forwards' || fill === 'both' ? 'both' : 'backwards',+ });+ }}return animation;}+/**+ * The start a change's animations share. It is the timeline's frame time,+ * unless a block ran more than LATE_START_MS past that frame before the first+ * of them was made. Then they start at the moment the first of them is made.+ * The frame time is from before the block, so a motion started on it would+ * skip into its curve, or past all of it. Chromium holds the timeline at the+ * frame before a long task once anything in the task reads it.+ */+interface ChangeStart {+ /** The frame time the timeline read. */+ readonly frame: number;+ /** When the change's animations start. */+ readonly at: number;+ /** When the last of them was made, on the document's clock. */+ last: number;+}++/**+ * Each document's change start: an iframe or a Picture-in-Picture window+ * keeps its own clock, with its own origin and frames.+ */+const changeStarts = new WeakMap<Document, ChangeStart>();++/** The clock of the document whose timeline a start is read on. */+function clockOf(doc: Document): number {+ return (doc.defaultView?.performance ?? performance).now();+}++/**+ * The start the current change's animations share. A change keeps one start+ * from its first animation through the flush of its glides and the parts that+ * ride them. That holds however long the work between them runs, such as the+ * rest of a commit or a slow swap. The start holds while the timeline reads+ * the same frame: through the task that made it and the microtasks after it.+ * A change that begins after a block takes a start of its own (beginChange).+ */+function startFor(doc: Document, frame: number): ChangeStart {+ const now = clockOf(doc);+ const held = changeStarts.get(doc);+ if (held != null && held.frame === frame) {+ held.last = now;+ return held;+ }+ const start: ChangeStart = {+ frame,+ at: now - frame <= LATE_START_MS ? frame : now,+ last: now,+ };+ changeStarts.set(doc, start);+ // Let go in a later task: every microtask of this one, where the glides+ // flush and the parts riding them play, has run by then.+ const view = doc.defaultView;+ (view?.setTimeout ?? setTimeout)(() => {+ if (changeStarts.get(doc) === start) {+ changeStarts.delete(doc);+ }+ }, 0);+ return start;+}++/**+ * A change begins as its "before" is read. After a block since the last+ * animation of the change before it, it takes a start of its own. So a change+ * made after a block that follows an earlier layout motion still plays.+ * Changes made together, with no block between them, share one start.+ */+function beginChange(doc: Document): void {+ const held = changeStarts.get(doc);+ if (held != null && clockOf(doc) - held.last > LATE_START_MS) {+ changeStarts.delete(doc);+ }+}++/**+ * When the animations of the layout change being made start. Code that+ * follows the change on its own clock reads it, such as a rail's width or a+ * swap's fade. It is the document timeline's current time. After a block+ * since that frame, it is the moment the change made its first animation.+ * Until the timeline reaches it, the change has not started.+ */+export function layoutStartFor(document: Document): number {+ const now = document.timeline?.currentTime;+ return now == null ? 0 : startFor(document, Number(now)).at;+}++/**+ * Where `element` shows at the timeline's time `at`: its layout box, moved by+ * its glide's offset then. After a block, WebKit evaluates a running+ * translate on the live clock. The timeline still reads the frame before the+ * block, as every glide here does, so the evaluated box would sit ahead.+ * Glides write px; a translate in percent is not ours, so the box stays.+ */+function shownBoxAt(element: Element, at: number): DOMRect {+ const box = element.getBoundingClientRect();+ const glide = glides.get(element);+ const startTime = glide?.animation.startTime;+ if (glide == null || startTime == null) {+ return box;+ }+ const translate =+ element.ownerDocument.defaultView?.getComputedStyle(element).translate ??+ '';+ if (translate.includes('%')) {+ return box;+ }+ const [appliedX = 0, appliedY = 0] = numbersIn(translate);+ const offset = glide.offsetAt(Math.max(0, at - Number(startTime)));+ return new DOMRect(+ box.x + (offset.x - appliedX) * glide.scale.x,+ box.y + (offset.y - appliedY) * glide.scale.y,+ box.width,+ box.height,+ );+}+/** Every animation this module started, so it can tell the app's apart. */const ours = new WeakSet<Animation>();@@ -378,6 +517,13 @@ interface Glide {readonly animation: Animation;readonly offsetAt: OffsetCurve;readonly durationMs: number;+ /**+ * The offset where the element showed when its old place was read. After a+ * block the glide starts further on, where the compositor has it.+ */+ readonly shownBefore: {readonly x: number; readonly y: number};+ /** Its ancestors' scale: page px per px of its own offset. */+ readonly scale: {readonly x: number; readonly y: number};}const glides = new WeakMap<Element, Glide>();@@ -823,6 +969,12 @@ interface Batch {scheduled: boolean;/** Called after every reading and before any glide starts. */readonly beforeMove: ((candidates: ReadonlyArray<Element>) => void)[];+ /**+ * The start the change's animations share, taken by its first one: its+ * entrance, or its glides at the flush. A change begun after a block,+ * before this one flushes, takes its own and leaves this one's.+ */+ start: ChangeStart | null;}const batches = new Map<Element, Batch>();@@ -845,6 +997,7 @@ function batchFor(area: Element): Batch {cache: {rects: new Map(), parts: new Map()},scheduled: false,beforeMove: [],+ start: null,};batches.set(area, created);// A measurement no commit claims by the next frame (a controlled owner@@ -866,6 +1019,39 @@ function batchFor(area: Element): Batch {return batch;}+/**+ * The start `batch`'s change shares: taken by its first animation, from the+ * document's (startFor), and kept with the batch through its flush.+ */+function changeStartOf(batch: Batch): ChangeStart | undefined {+ const doc = batch.area.ownerDocument;+ const now = doc.timeline?.currentTime;+ if (now == null) {+ return undefined;+ }+ if (batch.start == null || batch.start.frame !== Number(now)) {+ batch.start = startFor(doc, Number(now));+ }+ return batch.start;+}++/**+ * The start of the change being made in `area`, captured now for animations+ * made later in the task, such as the parts riding a glide. It is its batch's+ * when one is open there, otherwise the document's.+ */+function changeStartIn(+ area: Element | null | undefined,+ doc: Document,+): ChangeStart | undefined {+ const batch = area == null ? undefined : batches.get(area);+ if (batch != null) {+ return changeStartOf(batch);+ }+ const now = doc.timeline?.currentTime;+ return now == null ? undefined : startFor(doc, Number(now));+}+function intersects(a: DOMRect, b: DOMRect): boolean {return (a.width > 0 &&@@ -984,6 +1170,9 @@ function flush(batch: Batch): void {notify([]);return;}+ // The change's own start, taken by its entrance when it played one, even+ // when another change has begun since.+ const change = changeStartOf(batch);const visible = visibleRect(batch.area);// Every running glide stops first and every new place is read before any// glide starts, so no reading includes another's new motion.@@ -992,6 +1181,8 @@ function flush(batch: Batch): void {readonly before: DOMRect;readonly carried: OffsetCurve;readonly carriedMs: number;+ /** The running glide's offset inside `before`, read on the held frame. */+ readonly held: {readonly x: number; readonly y: number};after?: DOMRect;rawX?: number;rawY?: number;@@ -1013,17 +1204,28 @@ function flush(batch: Batch): void {const running = glides.get(element);let carried = AT_REST;let carriedMs = 0;+ let held = AT_REST(0);if (running != null) {const time = Number(running.animation.currentTime);const elapsed = Number.isFinite(time) ? Math.max(0, time) : 0;if (elapsed < running.durationMs) {- carried = t => running.offsetAt(elapsed + t);- carriedMs = running.durationMs - elapsed;+ held = running.offsetAt(elapsed);+ }+ // The new glide starts at the change's start. After a block, the+ // compositor kept this glide moving past the held frame until then.+ const {startTime} = running.animation;+ const shownAt =+ change != null && startTime != null+ ? Math.max(elapsed, change.at - Number(startTime))+ : elapsed;+ if (shownAt < running.durationMs) {+ carried = t => running.offsetAt(shownAt + t);+ carriedMs = running.durationMs - shownAt;}running.animation.cancel();glides.delete(element);}- entries.push({element, before, carried, carriedMs});+ entries.push({element, before, carried, carriedMs, held});}// Every reading (places, transforms, scales) before any glide starts: a// glide started between two readings would make the next one lay the page@@ -1082,7 +1284,7 @@ function flush(batch: Batch): void {// An adopter's own readings join them here, before any glide starts.notify(entries.map(entry => entry.element));for (const entry of entries) {- const {element, before, carried, carriedMs} = entry;+ const {element, before, carried, carriedMs, held} = entry;const after = entry.after as DOMRect;// Nested changes compose: an element inside another moving element moves// only by its own change, whatever order the changes were reported in.@@ -1108,10 +1310,12 @@ function flush(batch: Batch): void {continue;}if (motion.kind === 'fade') {- safeAnimate(element, [{opacity: 0}, {opacity: 1}], {- duration: motion.durationMs,- easing: motion.easing,- });+ safeAnimate(+ element,+ [{opacity: 0}, {opacity: 1}],+ {duration: motion.durationMs, easing: motion.easing},+ change,+ );continue;}if (entry.isMovedByApp === true) {@@ -1119,12 +1323,11 @@ function flush(batch: Batch): void {// (`spec:AST-105` Coverage).continue;}- // Where it shows now, against its new place, in its own px; the part the- // carried glide does not cover is the new move.+ // Where it showed before the change, against its new place, in its own+ // px. The part the glide's offset then does not cover is the new move.const scale = entry.scale ?? {x: 1, y: 1};- const now = carried(0);- const moveX = dx / scale.x - now.x;- const moveY = dy / scale.y - now.y;+ const moveX = dx / scale.x - held.x;+ const moveY = dy / scale.y - held.y;const {progress} = motion;const offsetAt: OffsetCurve = t => {const remaining = progress.remaining(t);@@ -1140,9 +1343,16 @@ function flush(batch: Batch): void {return {translate: `${offset.x}px ${offset.y}px`};}),{duration: durationMs, easing: 'linear'},+ change,);if (animation != null) {- const glide: Glide = {animation, offsetAt, durationMs};+ const glide: Glide = {+ animation,+ offsetAt,+ durationMs,+ shownBefore: {x: dx / scale.x, y: dy / scale.y},+ scale,+ };glides.set(element, glide);animation.addEventListener?.('finish', () => {if (glides.get(element) === glide) {@@ -1196,6 +1406,7 @@ export function reportLayoutChange(if (area == null) {return;}+ beginChange(element.ownerDocument);const batch = batchFor(area);if (batch.changed.has(element)) {return;@@ -1592,11 +1803,22 @@ export function playLayoutChange(return null;}const from = shownAtStart(element, 0);+ // The start of the change it enters with, which its glides then share.+ const batch = batches.get(area);+ const change =+ batch != null &&+ [...batch.changed].some(+ changed => changed === element || changed.contains(element),+ )+ ? changeStartOf(batch)+ : undefined;if (motion.kind === 'fade') {- return safeAnimate(element, [{opacity: from}, {opacity: 1}], {- duration: motion.durationMs,- easing: motion.easing,- });+ return safeAnimate(+ element,+ [{opacity: from}, {opacity: 1}],+ {duration: motion.durationMs, easing: motion.easing},+ change,+ );}const {progress} = motion;const rtl = edge.startsWith('inline') && isRtl(element);@@ -1607,6 +1829,7 @@ export function playLayoutChange(return {opacity: 1 - hidden, clipPath: fractionClip(edge, hidden, rtl)};}),{duration: progress.durationMs, easing: 'linear'},+ change,);if (animation != null) {const tracked = trackEdgeMotion(@@ -1889,13 +2112,16 @@ export function holdLayoutExit(// there.const from = shownAtStart(element, 1);const rtl = edge.startsWith('inline') && isRtl(element);+ // The start of the change it exits with, which its glides then share.+ const change = changeStartOf(batch);let animation: Animation | null;if (motion.kind === 'fade') {- animation = safeAnimate(element, [{opacity: from}, {opacity: 0}], {- duration: motion.durationMs,- easing: motion.easing,- fill: 'forwards',- });+ animation = safeAnimate(+ element,+ [{opacity: from}, {opacity: 0}],+ {duration: motion.durationMs, easing: motion.easing, fill: 'forwards'},+ change,+ );} else {const {progress} = motion;animation = safeAnimate(@@ -1905,6 +2131,7 @@ export function holdLayoutExit(return {opacity: shown, clipPath: fractionClip(edge, 1 - shown, rtl)};}),{duration: progress.durationMs, easing: 'linear', fill: 'forwards'},+ change,);if (animation != null) {const tracked = trackEdgeMotion(@@ -2046,6 +2273,7 @@ export function holdLayoutSwap() {return null;}+ beginChange(element.ownerDocument);const box = element.getBoundingClientRect();if (!isVisiblePart) {const copy = inertCopy(element);@@ -2071,6 +2299,9 @@ export function playLayoutSwap(return () => {};}const {copy} = swap;+ // Captured now: the parts riding a glide play a microtask later, on the+ // start of the change they are part of.+ const change = changeStartIn(swap.area, copy.ownerDocument);placeOver(copy, how.host, swap.rect);if (how.isOpaque === true) {copy.style.zIndex = '1';@@ -2126,6 +2357,7 @@ export function playLayoutSwap(element,sample(t => shape(progressAt(t), rideAt(t))),{duration: durationMs, fill: 'both', ...options},+ change,);if (animation != null) {animations.push(animation);@@ -2173,8 +2405,10 @@ export function playLayoutSwap(if (glide == null) {return {x: -rideWith.travel.x, y: -rideWith.travel.y};}+ // The parts were read where the ridden element showed then. After a+ // block it has moved on by the glide's start, so they move with it.const now = glide.offsetAt(t);- const start = glide.offsetAt(0);+ const start = glide.shownBefore;return {x: now.x - start.x, y: now.y - start.y};};playAll(durationMs, progressAt, rideAt, {easing: 'linear'}, shape =>@@ -2197,9 +2431,10 @@ export function playLayoutFrames(): () => void {const area = handle?.[AREA]() ?? null;const motion = area == null ? null : layoutMotion(area);- if (motion == null || motion.kind === 'instant') {+ if (area == null || motion == null || motion.kind === 'instant') {return () => {};}+ const change = changeStartIn(area, area.ownerDocument);const animations: Animation[] = [];for (const {element, frames: shape} of parts) {const animation =@@ -2214,11 +2449,14 @@ export function playLayoutFrames(easing: 'linear',fill: 'both',},+ change,)- : safeAnimate(element, [{opacity: 0}, {opacity: 1}], {- duration: motion.durationMs,- easing: motion.easing,- });+ : safeAnimate(+ element,+ [{opacity: 0}, {opacity: 1}],+ {duration: motion.durationMs, easing: motion.easing},+ change,+ );if (animation != null) {animations.push(animation);}@@ -2295,6 +2533,7 @@ export function holdLayoutEdge(if (element == null || typeof element.animate !== 'function') {return null;}+ beginChange(element.ownerDocument);const rect = element.getBoundingClientRect();return {element,@@ -2370,20 +2609,32 @@ export function playLayoutEdge(rides ? from + towards(ride) : from + (to - from) * p;const clip = (hidden: number) => pxClip(edge, hidden, rtl);const now = () => Number(element.ownerDocument.timeline?.currentTime ?? 0);- const startedAt = now();+ // The start this change's animations share, which after a block is later+ // than the frame time the timeline still reads (startFor).+ const startedAt =+ changeStartIn(areaOf(handle, element), element.ownerDocument)?.at ?? 0;const durationMs =motion.kind === 'spring' ? motion.progress.durationMs : motion.durationMs;+ const progressAt = (ms: number) =>+ motion.kind === 'spring'+ ? 1 - motion.progress.remaining(Math.min(ms, durationMs))+ : 0;const shown = (): {extent: number; progress: number} | null => {- const elapsed = now() - startedAt;+ const elapsed = Math.max(0, now() - startedAt);if (elapsed >= durationMs) {return null;}- const progress =- motion.kind === 'spring' ? 1 - motion.progress.remaining(elapsed) : 0;- let extent = from + (to - from) * progress;+ // The fades are read at the change's start, where the glide it retargets+ // carries on. The extent stays on the timeline's frame, the frame a ride+ // is measured from.+ const progress = progressAt(+ Math.max(elapsed, layoutStartFor(element.ownerDocument) - startedAt),+ );+ let extent = from + (to - from) * progressAt(elapsed);if (rides && rideWith != null) {- // The edge is the ridden element's: read it where it shows.- const ridden = rideWith.getBoundingClientRect();+ // The edge is the ridden element's: read it where it shows, on the+ // timeline's clock.+ const ridden = shownBoxAt(rideWith, now());const own = element.getBoundingClientRect();extent = !isInline? isEnd@@ -2656,6 +2907,7 @@ export function reportLayoutEdge(const element = getElement();measured = null;if (element != null) {+ beginChange(element.ownerDocument);const running = resizeReveals.get(element);const elapsed = Number(running?.animation?.currentTime);const rect = element.getBoundingClientRect();@@ -2667,7 +2919,9 @@ export function reportLayoutEdge(rect,}: {- shown: running.shownAt(Number.isFinite(elapsed) ? elapsed : 0),+ shown: running.shownAt(+ Number.isFinite(elapsed) ? Math.max(0, elapsed) : 0,+ ),box: running.box,rect,};@@ -2705,12 +2959,15 @@ export function reportLayoutEdge(return;}const isConceal = after < before.shown;+ const change = changeStartIn(area, element.ownerDocument);if (motion.kind === 'fade') {if (!isConceal) {- safeAnimate(element, [{opacity: 0}, {opacity: 1}], {- duration: motion.durationMs,- easing: motion.easing,- });+ safeAnimate(+ element,+ [{opacity: 0}, {opacity: 1}],+ {duration: motion.durationMs, easing: motion.easing},+ change,+ );}return;}@@ -2735,6 +2992,7 @@ export function reportLayoutEdge(clipPath: pxClip(edge, curve(t), rtl),})),{duration: progress.durationMs, easing: 'linear'},+ change,);const reveal: ResizeReveal = {animation,diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.tsindex 3f4dd1d38b..d9af6ca317 100644--- a/packages/core/src/motion/animator.ts+++ b/packages/core/src/motion/animator.ts@@ -181,6 +181,7 @@*/import {cubicBezier} from './bezier';+import {LATE_START_MS} from './frameBlock';import {solveSpring, toSpring, type SpringDescription} from './spring';import {registerPresentedOffset, type PresentedSource} from './presentation';import {resolveMotion} from './resolveMotion';@@ -669,13 +670,6 @@ const REST_FRAMES_PER_SECOND = 60;/** A curve that has not settled by then (an undamped spring) snaps. */const MAX_DURATION_MS = 30_000;-/**- * How long a task must run on past its first call from rest before that- * counts as a block (WebKit; startAfterBlock): two frames at 60 Hz.- */-// Browser start times are frame times and a task's end a live clock, so only a block longer than a frame plus the task's own length can be told apart from that quantization.-const LATE_START_MS = 34;-/*** The task calls from rest are made in, shared by every call made in it* (every animator's), so one motion's parts that are separate calls startdiff --git a/packages/core/src/motion/frameBlock.ts b/packages/core/src/motion/frameBlock.tsnew file mode 100644index 0000000000..4a2d984109--- /dev/null+++ b/packages/core/src/motion/frameBlock.ts@@ -0,0 +1,16 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file frameBlock.ts+ * @input none+ * @output LATE_START_MS+ * @position The motion modules' shared measure of a main-thread block.+ */++/**+ * How long a task must run on past a frame, or past its first call from rest,+ * to count as a block. It is two frames at 60 Hz. Browser start times are+ * frame times, while a task's end is on a live clock. So only a block longer+ * than a frame plus the task's own length stands out from that quantization.+ */+export const LATE_START_MS = 34;