An open source design system that's fully customizable and agent ready
TypeScript
feat(TreeList): the expand moves as one under a finger (#8088)
Christopher Chedeaue89bdc881bab
diff --git a/.changeset/tree-list-expand-motion.md b/.changeset/tree-list-expand-motion.mdnew file mode 100644index 0000000000..99a9e1a544--- /dev/null+++ b/.changeset/tree-list-expand-motion.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Under a coarse primary pointer, expanding a `TreeList` row glides the rows below it to their new places on the shared layout glide while its children fade in on the same timing, so the tree moves as one. A collapse fades the children out as the rows below glide up, and the chevron turns on that timing. The rows used to appear and leave in a single frame. Without an `animatedLayout` handle the motion stays inside the tree, so content after the tree takes its place at once, and the tree clips its bottom edge while it moves so no row paints over that content; pass a handle for it to glide too. The guide lines beside a group now show and hide with its rows. With reduced motion on and a finger, the children fade in where they land. With a mouse the rows still change at once. Under every pointer, a guide line now ends at the last row it joins instead of running on beside an expanded last row's children.++@vjeuxdiff --git a/apps/storybook/stories/TreeList.stories.tsx b/apps/storybook/stories/TreeList.stories.tsxindex 2a7e4e47e0..e9cde292fa 100644--- a/apps/storybook/stories/TreeList.stories.tsx+++ b/apps/storybook/stories/TreeList.stories.tsx@@ -76,6 +76,25 @@ export const Basic: Story = {},};+export const WithContentBelow: Story = {+ render: () => (+ <VStack gap={4}>+ <TreeList items={fileTreeItems} />+ <Button label="Open folder" onClick={() => {}} />+ </VStack>+ ),+ parameters: {+ docs: {+ description: {+ story:+ 'Content after the tree takes its new place by layout when a ' ++ "folder expands or collapses; under a finger only the tree's own " ++ 'rows animate.',+ },+ },+ },+};+export const FullyExpanded: Story = {args: {items: [diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.mdindex 734c575117..7744827d0d 100644--- a/docs/architecture/react-component-runtime.md+++ b/docs/architecture/react-component-runtime.md@@ -253,7 +253,9 @@ those contracts.side nav collapse or expand (`component:AppShell` FR17, `component:SideNav`FR6), each making its copy through the swap. A resize controller also holdsits own handle for a LayoutPanel's collapse and open, with no copy- (`component:Resizable` FR8). The module may also play+ (`component:Resizable` FR8). Under a coarse pointer, a TreeList with no handle+ from the app holds its own for its own expand and collapse, with no copy+ (`component:TreeList` FR8). The module may also playcaller-supplied frames on elements the page already renders, on the oneshared motion, with no copy, releasing them when the motion ends; AppShell'scontent surface uses this to cover an expand's gap when its old wrap is notdiff --git a/docs/specs/AST-105-animated-layout/spec.md b/docs/specs/AST-105-animated-layout/spec.mdindex 71c825efa9..fce16b0e83 100644--- a/docs/specs/AST-105-animated-layout/spec.md+++ b/docs/specs/AST-105-animated-layout/spec.md@@ -69,12 +69,13 @@ const animatedLayout = useAnimatedLayout({containerRef: scrollRef});`animatedLayout` prop or option.- **FR2 — Without a handle, nothing changes.** A component without a handlekeeps its behavior: the changed element shows its change as its own record- says, and content after it takes its place at once. AppShell's content area and- the SideNav rail animate their own change during a side nav collapse or+ says, and content after it takes its place at once. AppShell's content area+ and the SideNav rail animate their own change during a side nav collapse orexpand, and a resizable pane a LayoutPanel renders animates its own collapseand open, as their records state (`component:AppShell` FR17,`component:SideNav` FR6, `component:Resizable` FR8, `component:LayoutPanel`- FR7).+ FR7). Under a coarse pointer, a TreeList with no handle from the app animates+ its own expand and collapse inside the tree (`component:TreeList` FR8).- **FR3 — The content after a change glides within the area.** For any changea component holding the handle reports, such as a disclosure opening,content loading in, a message appearing, or an item inserted or removed,diff --git a/docs/specs/components/TreeList/TreeList.spec.md b/docs/specs/components/TreeList/TreeList.spec.mdindex 3311177b36..64b5692e47 100644--- a/docs/specs/components/TreeList/TreeList.spec.md+++ b/docs/specs/components/TreeList/TreeList.spec.md@@ -15,6 +15,7 @@ verified_by:packages/core/src/TreeList/TreeList.test.tsx,packages/core/src/hooks/nestedTouchPress.adopters.test.tsx,packages/core/src/TreeList/__tests__/TreeListGuideAlignment.interaction.browser.spec.ts,+ packages/core/src/TreeList/__tests__/TreeListExpand.interaction.browser.spec.ts,packages/core/src/theme/themingTargets.test.ts,scripts/check-knowledge.mjs,]@@ -36,15 +37,15 @@ system_specs:## Contract at a glance-| Area | Contract |-| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Public contract | Each `TreeListItemData` may carry the standard `className`, `style`, and `xstyle` styling inputs for its Item row. |-| Behavior | All supplied styling inputs compose on the same Item row box—the element that paints the row, owns its hover state, and contains its visible content. They do not target the outer semantic `<li>`. |-| End-user impact | A builder can reveal or style content for one row without causing every row in the tree to react. |-| Builder impact | The three standard styling mechanisms remain interchangeable parts of one row-styling seam. A builder may use one or combine them; no existing callsite must opt in. |-| Compatibility/readiness | The contract is additive and preserves default output, except FR8's group motion under a coarse pointer. Its authority is current; implementation support may arrive separately, but the durable API is incomplete until all three mechanisms are supported on the same row. |-| Review checks | Reject an implementation that omits one mechanism from the durable API, sends the mechanisms to different elements, drops a supplied value, targets the semantic `<li>`, or moves the promised row target without an explicit compatibility decision. |-| Governing rules | [Public component API INV5–INV6](../../../architecture/public-component-api.md) and [AST-002 FR1, FR4, FR7–FR10, FR12, and DEC-1](../../AST-002/spec.md) govern admission, predictability, and composition of the component-local styling seam. |+| Area | Contract |+| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | Each `TreeListItemData` may carry the standard `className`, `style`, and `xstyle` styling inputs for its Item row. |+| Behavior | All supplied styling inputs compose on the same Item row box—the element that paints the row, owns its hover state, and contains its visible content. They do not target the outer semantic `<li>`. |+| End-user impact | A builder can reveal or style content for one row without causing every row in the tree to react. |+| Builder impact | The three standard styling mechanisms remain interchangeable parts of one row-styling seam. A builder may use one or combine them; no existing callsite must opt in. |+| Compatibility/readiness | The contract is additive and keeps default output, except FR8's coarse-pointer glide and DD5's Guides. Its authority is current; implementation support may arrive separately, but the durable API is incomplete until all three mechanisms are supported on the same row. |+| Review checks | Reject an implementation that omits one mechanism from the durable API, sends the mechanisms to different elements, drops a supplied value, targets the semantic `<li>`, or moves the promised row target without an explicit compatibility decision. |+| Governing rules | [Public component API INV5–INV6](../../../architecture/public-component-api.md) and [AST-002 FR1, FR4, FR7–FR10, FR12, and DEC-1](../../AST-002/spec.md) govern admission, predictability, and composition of the component-local styling seam. |This table is a review projection; the body below is authoritative.@@ -57,12 +58,15 @@ requiring product code to reconstruct TreeList behavior.## Compatibility and migration-- Released default preserved: `no` under a coarse primary pointer, where a- toggled group slides (FR8); fine pointers are unchanged without an- `animatedLayout` handle+- Released default preserved: `no`. Under a coarse primary pointer, the rows+ below a toggled group glide as it fades (FR8). Under every pointer, a Guide+ line ends at the last row it joins instead of running on beside an expanded+ last row's children (DD5). With a fine pointer and no `animatedLayout` handle,+ rows still change at once- Compatibility class: additive optional public API, plus FR8's group motion- under a coarse pointer; no other default rendering, DOM, styling, or- interaction changes when the inputs are absent+ under a coarse pointer and DD5's Guide lines under every pointer; no other+ default rendering, DOM, styling, or interaction changes when the inputs are+ absent- Controlled/uncontrolled behavior: unchanged- Migration decision: none; existing callsites remain valid@@ -112,7 +116,7 @@ Supporting one does not justify omitting another from the durable contract.| FR5 | `TreeListItemData` MUST admit `className`, `style`, and `xstyle` as one per-item styling seam. Every supplied value MUST compose on the same Item row box; an implementation MUST NOT treat current support for only one mechanism as authority to exclude the other two. | Owner decision; `architecture:public-component-api` INV5–INV6; `spec:AST-002/DEC-1` | Settled intent; implementation may be staged || FR6 | The Item row box is the logical element that paints the row, owns its hover state, and contains Start content, Item label and description, and End content. The styling seam MUST NOT move to the semantic `<li>` or another element without a compatibility decision. | Owner decision and the caller-owned per-row interaction boundary | Settled intent || FR7 | A click on an Item row outside its Item label performs the row's action: an Item with `onClick` runs it; otherwise an Item with children toggles; otherwise an Item whose only action is its link follows that link as Enter does, with modified and middle clicks following the shared enlarged-surface rule in `family:navigation-destinations`. The Chevron and controls in Start content and End content keep their own activation, and on any row a touch press that starts on one of them, or on the Chevron of a row whose surface runs a different action, shows no pressed paint on the row (a mouse press keeps the `:active` paint, as `component:Item` FR9 states); a disabled Item does nothing. A press inside an open Tooltip or HoverCard surface performs no row action (`component:Tooltip` FR11). | Owner decision; `family:navigation-destinations` | Settled intent; implementation may be staged |-| FR8 | Expanding or collapsing an Item with children MUST play its group's own motion: under a coarse primary pointer its rows slide out from under the parent as one block, clipped to the group's box, and back on collapse, a collapsing group's rows leaving the accessibility tree as the slide starts, while the Chevron turns, by transform only, on the theme's duration and easing tokens (`spec:AST-094` FR5, FR45); under a fine pointer the group appears and leaves at once. With an `animatedLayout` handle, the group and the rows after it follow `spec:AST-105`'s shared motion under every pointer (FR4, FR5); without one, the group's own slide stays touch-only and the rows after the group take their places at once (`spec:AST-105` FR2). | UIKit outline list (`UICollectionView`), iOS 26.2; `spec:AST-105` FR2 | Proposed; awaiting an engineering owner's approval |+| FR8 | Expanding or collapsing an Item with children under a coarse primary pointer MUST play its motion. When a branch expands or collapses, the rows below glide on the shared layout glide (`spec:AST-105` FR4, `--duration-medium`) and the entering or leaving children fade on the same timing, so the tree moves as one; the children take the glide's timing, not `--duration-fast`. The Chevron turns on that timing, and a collapsing group's rows leave the accessibility tree at the tap. Without an `animatedLayout` handle the motion stays inside the tree, so content after the tree takes its place at once (`spec:AST-105` DEC-1), and under a fine pointer the group appears and leaves at once. With a handle, the group and the content after it follow its shared motion under every pointer (FR9). | `spec:AST-105` FR4; Owner feedback, Nov 6 2026 (Cindy): the expand felt too jumpy. | Current behavior || FR9 | `TreeList` MUST accept `animatedLayout?: AnimatedLayout`. With a handle, expanding and collapsing a row report the row's size change through it, so the content after the row glides inside the handle's container, and the shown rows and the row's Chevron move on the same motion (`spec:AST-105` FR1–FR4; `spec:AST-108` FR4a). Without one, expanding and collapsing follow FR8. The prop MUST NOT change tree semantics or keyboard behavior. | `spec:AST-105` FR1, FR2; `spec:AST-108` FR4a | Current behavior |### Allowed variation@@ -140,7 +144,7 @@ Supporting one does not justify omitting another from the durable contract.| Flat items | Each Item contains an Item label. | Description and consumer slots may be absent. || Styled item | The supplied `className`, `style`, and `xstyle` values compose on only that item's row box. | Any subset of the three inputs may be absent. || Expandable item | Item may contain Chevron and delegated Chevron glyph. | Expanded or collapsed state. |-| Item toggled by a finger | Its group slides out from under it, or back, as one block while the Chevron turns. | Reduced motion: a fade, no travel. |+| Item toggled by a finger | The rows below glide as its group fades in or out, on one timing; the Chevron turns. | Reduced motion: a fade, no travel. || Nested `lineGuides` tree | Guide instances show parent-child relationships. | Count and position follow hierarchy. || `noGuides` tree | Guide instances are absent; indentation remains. | All other anatomy remains unchanged. || Described item | Item description renders below Item label. | Caller-provided description text. |@@ -212,12 +216,13 @@ caller-owned even though TreeList positions their slot wrappers.<!-- design-decisions:v1 -->-| ID | Decision | Intent or reason | Applies to | Allowed variation |-| --- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| DD1 | Every Item spans the full width of the tree list at any depth; its nesting indent sits inside the row, ahead of its content. | Hover, pressed, and selected fills line up across depths, so the tree reads as one list of equal rows while labels keep their per-level alignment. | Item at every depth, at rest and through hover, pressed, selected, disabled, and focus | Themes set the indent step with `--tree-list-indent` and may restyle the row's fill, radius, and padding; row padding adds to the indent instead of replacing it. |-| DD2 | A nested Item's indent area is part of the row's painted target: it shows the row's hover and press feedback. | The whole painted row reads as one target, matching where a click acts (FR7), so no part of a row lights up apart from the rest. | Nested Items that act on click | Themes may restyle the feedback through the `tree-list-item` target. |-| DD3 | Guides paint above row fills, and an Item whose focus ring is showing paints above the guides. | Hierarchy lines stay continuous through hover and selection, and the focus indicator is never cut; on a focused row that is also filled, the ring takes precedence and the fill covers the guides at that row. | Guide and Item in `lineGuides` trees | Themes may recolor or hide guides through the `tree-list-guide` target. |-| DD4 | A Chevron stays in its natural column; a Guide aligns its center to that Chevron rather than moving the control. | Guide visibility is decoration, so switching between `lineGuides` and `noGuides` must not reposition an interactive control. | Chevron and Guide at every depth, in LTR and RTL, across both guide variants | Themes may restyle or hide either part through its target; a theme that moves the Chevron or changes Item padding also owns the corresponding Guide alignment. |+| ID | Decision | Intent or reason | Applies to | Allowed variation |+| --- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| DD1 | Every Item spans the full width of the tree list at any depth; its nesting indent sits inside the row, ahead of its content. | Hover, pressed, and selected fills line up across depths, so the tree reads as one list of equal rows while labels keep their per-level alignment. | Item at every depth, at rest and through hover, pressed, selected, disabled, and focus | Themes set the indent step with `--tree-list-indent` and may restyle the row's fill, radius, and padding; row padding adds to the indent instead of replacing it. |+| DD2 | A nested Item's indent area is part of the row's painted target: it shows the row's hover and press feedback. | The whole painted row reads as one target, matching where a click acts (FR7), so no part of a row lights up apart from the rest. | Nested Items that act on click | Themes may restyle the feedback through the `tree-list-item` target. |+| DD3 | Guides paint above row fills, and an Item whose focus ring is showing paints above the guides. | Hierarchy lines stay continuous through hover and selection, and the focus indicator is never cut; on a focused row that is also filled, the ring takes precedence and the fill covers the guides at that row. | Guide and Item in `lineGuides` trees | Themes may recolor or hide guides through the `tree-list-guide` target. |+| DD4 | A Chevron stays in its natural column; a Guide aligns its center to that Chevron rather than moving the control. | Guide visibility is decoration, so switching between `lineGuides` and `noGuides` must not reposition an interactive control. | Chevron and Guide at every depth, in LTR and RTL, across both guide variants | Themes may restyle or hide either part through its target; a theme that moves the Chevron or changes Item padding also owns the corresponding Guide alignment. |+| DD5 | While a group enters or leaves, its Guides show and hide with its rows; no Guide line runs past the rows it joins. | The lines move as one with the rows they join, so no line hangs in empty space while the tree moves. | Guide at the last row it joins and beside an entering or leaving group, under every pointer | Themes may recolor or hide guides through the `tree-list-guide` target. |### Theming anatomy@@ -275,8 +280,8 @@ authorize or prohibit a future target.item paths to preserve that result.- TreeList's current custom-router path inherits the `useLinkComponent` adoptiongap recorded by the family until the accepted implementation lands.-- `spec:AST-105` owns the animated layout handle and how the content after a- toggled group moves; TreeList owns only the group's own motion (FR8).+- `spec:AST-105` owns the animated layout handle and its shared glide; under a+ coarse pointer TreeList plays that glide inside the tree (FR8).## Verification map@@ -290,10 +295,11 @@ authorize or prohibit a future target.| AR1 (empty header) | `TreeList.test.tsx` "TreeList empty slots" suite: "a header of %s names nothing; the tree keeps its own label" for `''`, `false`, `true`, and `null`, and `0` as a rendered Header | Empty, boolean, and null header with `aria-label`; `0` header | A tree named by an empty Header, or carrying `aria-labelledby` without a rendered Header, fails. | `audit:TreeList/accessibility` || FR5, FR6, ORD1 | Focused `TreeList.test.tsx` row-identity and styling-composition coverage, required with implementation | One input at a time; all three together; sibling rows | Dropping any mechanism, applying mechanisms to different elements, targeting the `<li>`, changing the merge order, or styling a sibling row fails. | `audit:TreeList/api` || FR7 | Focused `TreeList.test.tsx` row-click coverage, required with implementation | Action, parent, link, and disabled rows; clicks in the indent and padding, on the Chevron, and on Start and End content controls; plain, modified, and middle clicks | A click outside the label does nothing or runs the wrong action, a link-row click reaches ancestors twice, the Chevron or a Start or End content control activates the row, or a disabled row acts. | `audit:TreeList/behavior` |-| FR8 | Real-browser frame evidence under a finger and a mouse | expand and collapse; a toggle mid-motion; reduced motion; rows after the group, with and without an `animatedLayout` handle | Rows inside the group that jump, travel under a fine pointer without a handle or under reduced motion, an animated property under a fine pointer with reduced motion, a fade under a mouse without a handle, collapsing rows still in the accessibility tree during the slide, layout or paint per frame, or rows after the group moving without a handle fails | `audit:TreeList/behavior` |+| FR8 | `TreeListExpand.interaction.browser.spec.ts`: per-frame evidence under a finger and a mouse | expand and collapse; reduced motion; the theme's glide token; the rows below and content after the tree, with and without an `animatedLayout` handle | A blank band above the rows below, on any frame, a group that shows at rest before it fades in, rows below that jump, timing other than the theme's glide, motion under a fine pointer without a handle, travel under reduced motion, a collapsed group's rows in the accessibility tree after the tap, or content after the tree moving without a handle fails | `audit:TreeList/behavior` || FR9 | `animatedLayoutAdopters.test.tsx` (with and without a handle; `isExpanded` changed in `items` glides; the collapsing group kept inert and out of the keyboard order until its exit ends) and `animatedLayoutAdopters.interaction.browser.spec.ts` (the `Core/Animated layout` story through a ScrollableArea ref, expanding and collapsing) | No handle; a handle; click, keyboard, and `items`-driven changes; expanding and collapsing | The rows after a row jump with a handle, an `items` change lands at once, a collapsing group vanishes before its exit or its rows stay focusable during it, or anything changes without a handle | `audit:TreeList/behavior` || AR2 | `TreeList.test.tsx` collapse-focus suite; `animatedLayoutAdopters.test.tsx` collapse with focus inside during the exit; `TreeListCollapseFocus.a11y.chromium.spec.ts` | Focus on a child row, `items`-driven collapse, with and without a handle; nested outer and inner collapse; a disabled collapsing row; focus on another row or outside | Focus left in the removed or inert group, on the page body, or moved when it was not inside the group fails. | `audit:TreeList/accessibility` || DD4 | `TreeListGuideAlignment.interaction.browser.spec.ts` measures Chevron logical-start placement and Guide/Chevron center alignment in the built Fully Expanded story. | `lineGuides` and `noGuides`; LTR and RTL | Reintroducing Chevron edge margins, moving a Chevron when guides are hidden, or placing a Guide off the Chevron center fails the browser geometry assertions. | `audit:TreeList/anatomy` |+| DD5 | `TreeListExpand.interaction.browser.spec.ts` guide case: the Guide column measured on every frame | expand and collapse under a finger | A Guide line running past the last row it joins on any frame fails | `audit:TreeList/anatomy` || Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and five current local targets | Missing, extra, duplicated, prefixed, or stale mappings fail repository validation. | `audit:TreeList/theming` |Focused target-placement assertions cover all five local targets. Runtime supportdiff --git a/packages/core/src/List/__tests__/reducedMotion.ts b/packages/core/src/List/__tests__/reducedMotion.tsnew file mode 100644index 0000000000..0261de0b44--- /dev/null+++ b/packages/core/src/List/__tests__/reducedMotion.ts@@ -0,0 +1,101 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file reducedMotion.ts+ * @input The interaction harness's held animations+ * @output `expectReducedMotionCrossFade`: the browser check of the Reduce+ * Motion cross-fade over what a change started+ * @position Test helper for the TreeList interaction specs. Each case runs+ * under Reduce Motion with a coarse pointer (a finger).+ */++import {expect} from '@astryxdesign/a11y-spec/playwright';+import type {HeldAnimation} from '@astryxdesign/interaction-harness';++/** The limit on a touch presentation's cross-fade under Reduce Motion. */+const REDUCED_MOTION_FADE_MS = 200;++const TIMING_KEYS = new Set([+ 'offset',+ 'computedOffset',+ 'easing',+ 'composite',+]);++/** Properties that move, turn or scale an element. */+const TRAVEL = new Set(['translate', 'rotate', 'scale', 'transform']);++/** The properties an animation's keyframes change. */+function animatedProperties(animation: HeldAnimation): string[] {+ const properties = new Set<string>();+ for (const frame of animation.keyframes) {+ for (const key of Object.keys(frame)) {+ if (!TIMING_KEYS.has(key)) {+ properties.add(key);+ }+ }+ }+ return [...properties];+}++/**+ * Whether the animation only lands `property` at a new value, rather than+ * moving it through the values between. A step lands it: the value changes+ * between keyframes at the same offset, or under a step easing.+ */+function onlyLands(animation: HeldAnimation, property: string): boolean {+ const frames = animation.keyframes.filter(frame => property in frame);+ for (let index = 0; index + 1 < frames.length; index += 1) {+ const from = frames[index];+ const to = frames[index + 1];+ if (String(from[property]) === String(to[property])) {+ continue;+ }+ const sameOffset =+ Number(from.computedOffset) === Number(to.computedOffset);+ const easing = typeof from.easing === 'string' ? from.easing : '';+ const stepped = /^step|steps\(/.test(easing);+ if (!sameOffset && !stepped) {+ return false;+ }+ }+ return true;+}++/**+ * The Reduce Motion cross-fade under a coarse pointer. At least one opacity+ * animation runs, and its curve ends within 200 ms. Nothing travels, scales+ * or resizes on the way, though an element may land at its new place in one+ * step, hidden by the fade. Nothing but opacity animates. `held` is what+ * `holdAnimations` returned right after the change.+ */+export function expectReducedMotionCrossFade(+ held: ReadonlyArray<HeldAnimation>,+): void {+ const summary = JSON.stringify(+ held.map(animation => ({+ target: animation.target,+ properties: animatedProperties(animation),+ curveEndMs: animation.curveEndMs,+ })),+ );+ let fades = 0;+ for (const animation of held) {+ for (const property of animatedProperties(animation)) {+ if (property === 'opacity') {+ fades += 1;+ expect(animation.curveEndMs, summary).toBeGreaterThan(0);+ expect(animation.curveEndMs, summary).toBeLessThanOrEqual(+ REDUCED_MOTION_FADE_MS + 1,+ );+ } else if (TRAVEL.has(property)) {+ expect(onlyLands(animation, property), `${property}: ${summary}`).toBe(+ true,+ );+ } else {+ expect(property, summary).toBe('opacity');+ }+ }+ }+ expect(fades, summary).toBeGreaterThan(0);+}diff --git a/packages/core/src/TreeList/TreeList.doc.mjs b/packages/core/src/TreeList/TreeList.doc.mjsindex 2460d5fb40..23d49ef3c8 100644--- a/packages/core/src/TreeList/TreeList.doc.mjs+++ b/packages/core/src/TreeList/TreeList.doc.mjs@@ -143,7 +143,7 @@ export const docs = {usage: {anatomy,description:- 'An expandable tree structure for displaying hierarchical data with branch connector lines. Use it for file explorers, nested category browsers, or any interface that visualizes parent-child relationships.',+ 'An expandable tree structure for displaying hierarchical data with branch connector lines. Use it for file explorers, nested category browsers, or any interface that visualizes parent-child relationships. Under a finger, expanding a row glides the rows below it while its children fade in on the same timing, and a collapse plays it back; pass an `animatedLayout` handle for content after the tree to glide too.',bestPractices: [{guidance: true, description: 'Provide meaningful labels and icons for each node to make the hierarchy easy to scan.'},{guidance: true, description: 'Pre-expand important branches so users see key content immediately.'},diff --git a/packages/core/src/TreeList/TreeList.tsx b/packages/core/src/TreeList/TreeList.tsxindex 681308aa2c..c277c6a26e 100644--- a/packages/core/src/TreeList/TreeList.tsx+++ b/packages/core/src/TreeList/TreeList.tsx@@ -26,7 +26,7 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import {isRenderable} from '../utils/isRenderable';-import {spacingVars} from '../theme/tokens.stylex';+import {focusVars, spacingVars} from '../theme/tokens.stylex';import {mergeProps} from '../utils';import type {BaseProps} from '../BaseProps';import {TreeListItem} from './TreeListItem';@@ -38,6 +38,7 @@ import type {import {themeProps} from '../utils/themeProps';import {useTreeFocusInternal} from '../hooks/useTreeFocus';import {LayoutChangeSnapshot} from '../motion/LayoutChangeSnapshot';+import {useTouchPresentation} from '../utils/touchPresentation';import {moveFocusLeftBehind,noteFocusWithin,@@ -46,6 +47,7 @@ import {import {useInteractionModalityTracking} from '../utils/interactionModality';import {useFocusLeavingChange} from '../utils/useFocusLeavingChange';import {useMergedRefs} from '../hooks/useMergedRefs';+import {useAnimatedLayout} from '../hooks/useAnimatedLayout';import {applyLayoutChangeTransition,holdLayoutExit,@@ -56,6 +58,46 @@ import {type LayoutChange,} from '../motion/animatedLayout';+/**+ * The clip a tree with no handle takes while it moves. Rows that glide up into+ * a shorter tree show only inside it, so they never paint over the content+ * after it. A table view clips to its bounds the same way. Only the bottom+ * edge clips, past the reach of a row's focus ring.+ */+const MOVING_CLIP = `inset(-100vmax -100vmax calc(-1 * (${focusVars['--focus-outline-width']} + ${focusVars['--focus-outline-offset']})) -100vmax)`;++const clipGenerations = new WeakMap<HTMLElement, number>();++/** Clips `tree` with `MOVING_CLIP` until each finite motion in it settles. */+function clipWhileMoving(tree: HTMLElement): void {+ if (typeof tree.getAnimations !== 'function') {+ return;+ }+ const moving = tree+ .getAnimations({subtree: true})+ .filter(+ animation =>+ animation.playState === 'running' &&+ Number.isFinite(+ animation.effect?.getComputedTiming().endTime ?? Infinity,+ ),+ );+ if (moving.length === 0) {+ return;+ }+ const generation = (clipGenerations.get(tree) ?? 0) + 1;+ clipGenerations.set(tree, generation);+ tree.style.setProperty('clip-path', MOVING_CLIP);+ void Promise.allSettled(+ moving.map(async animation => animation.finished),+ ).then(() => {+ if (clipGenerations.get(tree) === generation) {+ clipGenerations.delete(tree);+ tree.style.removeProperty('clip-path');+ }+ });+}+// =============================================================================// Types// =============================================================================@@ -246,7 +288,7 @@ export function TreeList({'aria-labelledby': ariaLabelledby,ref,onKeyDown: onKeyDownProp,- animatedLayout,+ animatedLayout: animatedLayoutProp,...restProps}: TreeListProps) {const headerId = useId();@@ -270,6 +312,14 @@ export function TreeList({// (`architecture:react-component-runtime` INV12). Read through a ref// because the tree element comes from the focus hook below.const treeElementRef = useRef<HTMLUListElement | null>(null);+ const {isTouch} = useTouchPresentation();+ // Under a finger, a tree with no handle animates inside itself. The rows+ // after a toggled row glide while its group fades on the same timing.+ // Content after the tree takes its place at once, because only an app's own+ // handle moves it.+ const ownLayout = useAnimatedLayout({containerRef: treeElementRef});+ const animatedLayout =+ animatedLayoutProp ?? (isTouch ? ownLayout : undefined);// The rows expanded now, whatever expanded them (a click, the keyboard, or// `isExpanded` changed in `items`).const expandedIds = useMemo(() => {@@ -557,7 +607,11 @@ export function TreeList({endAll();}}- }, [expandedIds, animatedLayout, endExit]);+ const tree = treeElementRef.current;+ if (pendings.length > 0 && animatedLayout === ownLayout && tree != null) {+ clipWhileMoving(tree);+ }+ }, [expandedIds, animatedLayout, ownLayout, endExit]);const {treeRef, handleKeyDown, handleFocus, takeTabStop} =useTreeFocusInternal<HTMLUListElement>({@@ -595,7 +649,6 @@ export function TreeList({const hasExpandableItems = items.some(item => item.children != null && item.children.length > 0,);-function renderItems(items: TreeListItemData[],nestedLevel: number,diff --git a/packages/core/src/TreeList/TreeListBranches.tsx b/packages/core/src/TreeList/TreeListBranches.tsxindex bcb80b0568..f9d94169b2 100644--- a/packages/core/src/TreeList/TreeListBranches.tsx+++ b/packages/core/src/TreeList/TreeListBranches.tsx@@ -40,6 +40,9 @@ const styles = stylex.create({// and let pointer input fall through to the row underneath.container: {height: '100%',+ // From the row wrapper's top edge, so a line spans the gap padding above+ // the row too.+ insetBlockStart: 0,position: 'absolute',width: GUIDE_COLUMN_WIDTH,zIndex: 1,@@ -54,12 +57,12 @@ const styles = stylex.create({width: LINE_WIDTH,backgroundColor: colorVars['--color-border-emphasized'],},- // Guide segment spanning the full <li>. The row box's inter-row gap now lives- // INSIDE the <li> (as `padding-block` on the row wrapper), so `height: 100%`- // already covers it — the segment only needs the original `1px` to bridge the- // hairline into the next contiguous sibling so the connector reads as one- // continuous line. Independent of `--tree-list-row-gap`: the gap is absorbed- // by the <li> height, not added on top here.+ // Guide segment spanning its row wrapper. The row box's inter-row gap lives+ // inside the row wrapper, as its `padding-block`. So `height: 100%` already+ // covers it. The segment adds only the original `1px`, which bridges the+ // hairline into the next sibling, so the connector reads as one line.+ // Independent of `--tree-list-row-gap`: the gap is absorbed by the row+ // wrapper's height, not added on top here.verticalFull: {height: 'calc(100% + 1px)',},@@ -90,7 +93,8 @@ interface TreeListBranchesProps {/*** Renders vertical lines showing parent-child relationships in the tree.- * Positioned in a full-height container to span the entire item including children.+ * Each line spans its own row. An expanded row's children draw the lines+ * beside them, so the lines show and hide with its group.** The line element carries the stable `astryx-tree-list-guide` theme target so a* theme can recolor or hide the connectors via `defineTheme` (e.g.@@ -104,14 +108,16 @@ export function TreeListBranches({}: TreeListBranchesProps) {return (<>- {ancestorsIsLast.map((ancestorIsLast, level) => {+ {ancestorsIsLast.map((_, level) => {const branchOffset = `calc(${GUIDE_COLUMN_START} + ${level} * ${LEVEL_INDENT})`;+ // A column holds the connector of the ancestor one level deeper, so+ // its line runs past this row while that ancestor has a sibling+ // below. The current item's own connector column (nestedLevel - 1)+ // is rendered below with its terminus or continuation style.+ const continues =+ level < nestedLevel - 1 && !ancestorsIsLast[level + 1];return (- // Skip the level that the current-item connector occupies- // (nestedLevel - 1), since that position is rendered below- // with the correct terminus/continuation style.- !ancestorIsLast &&- level !== nestedLevel - 1 && (+ continues && (<div// eslint-disable-next-line @eslint-react/no-array-index-key -- tree branch levels are fixed positional connectorskey={level}diff --git a/packages/core/src/TreeList/TreeListItem.tsx b/packages/core/src/TreeList/TreeListItem.tsxindex 40858be52e..d7bf02fde3 100644--- a/packages/core/src/TreeList/TreeListItem.tsx+++ b/packages/core/src/TreeList/TreeListItem.tsx@@ -93,9 +93,9 @@ const styles = stylex.create({// collapse, so adjacent rows end up a full gap apart — and it rides the// `rowWrapper`, which carries no theme target, so the paintable// `tree-list-item` stays a pure paint seam (layout lives off it). The <li>s- // stay contiguous — the gap is padding INSIDE each <li>, not space between- // them — so the per-<li> connector guide can still span it and read as a- // continuous line (see TreeListBranches). The lever's default is a subtle+ // stay contiguous, because the gap is padding inside each <li>, not space+ // between them. So the per-row connector guide can still span it and read+ // as one line (see TreeListBranches). The lever's default is a subtle// `--spacing-0-5` (2px, set on the tree-list root); a theme widens or closes// it via the `tree-list` target.paddingBlock: 'calc(var(--tree-list-row-gap, 0px) / 2)',@@ -712,16 +712,16 @@ export function TreeListItem({data-tree-level={nestedLevel + 1}data-tree-disabled={isDisabled || undefined}{...focusOutlineProps.publishFocusVisibleVars(styles.wrapper)}>- {variant !== 'noGuides' && (- <div {...stylex.props(styles.treeBranches)}>- <TreeListBranches- ancestorsIsLast={ancestorsIsLast}- isLast={isLast}- nestedLevel={nestedLevel}- />- </div>- )}<div {...stylex.props(styles.rowWrapper)}>+ {variant !== 'noGuides' && (+ <div {...stylex.props(styles.treeBranches)}>+ <TreeListBranches+ ancestorsIsLast={ancestorsIsLast}+ isLast={isLast}+ nestedLevel={nestedLevel}+ />+ </div>+ )}<div{...(isInteractive || (hasChildren && onClick == null)? pressablediff --git a/packages/core/src/TreeList/__tests__/TreeListExpand.interaction.browser.spec.ts b/packages/core/src/TreeList/__tests__/TreeListExpand.interaction.browser.spec.tsnew file mode 100644index 0000000000..7b2c8c65e5--- /dev/null+++ b/packages/core/src/TreeList/__tests__/TreeListExpand.interaction.browser.spec.ts@@ -0,0 +1,1082 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TreeListExpand.interaction.browser.spec.ts+ * @input The built TreeList stories, real touch and mouse input, and the+ * interaction harness+ * @output Proofs for a TreeList row's expand and collapse. Under a finger the+ * rows below glide on the shared layout glide, and the group fades on the+ * same timing. No frame shows a blank band, and the guide lines show and+ * hide with the group. A mouse changes at once.+ * @position Interaction evidence for TreeList's expansion motion, with an+ * Android case, a mouse case and an animatedLayout handle case+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ animationStoryboard,+ armHold,+ blockMainThread,+ busyWindowProof,+ MARKER_RGB,+ openStory,+ releaseAnimations,+ requireFrames,+ seekAnimations,+ startCompositorTrace,+ startScreencast,+ touchDriver,+ trackMarker,+ withStorybook,+ writeEvidence,+ type HeldAnimation,+} from '@astryxdesign/interaction-harness';+import {expectReducedMotionCrossFade} from '../../List/__tests__/reducedMotion';++const storybook = withStorybook(test);++const STORY = 'core-treelist--basic';++/** A tree row by its item id (an ancestor row contains its label too). */+const treeItem = (page: Page, id: string) =>+ page.locator(`[role="treeitem"][data-tree-id="${id}"]`);++/** The "components" folder's toggle, group and chevron, a child, a row below. */+function parts(page: Page) {+ const parent = treeItem(page, 'components');+ return {+ parent,+ // Its own toggle, group and chevron: not a descendant row's.+ toggle: parent.locator(':scope > :not([role="group"]) [data-tree-toggle]'),+ group: parent.locator(':scope > [role="group"]'),+ // The chevron's Icon, which turns: its own target, around the glyph.+ chevron: parent.locator(+ ':scope > :not([role="group"]) [data-tree-toggle] .astryx-icon',+ ),+ child: treeItem(page, 'button'),+ below: treeItem(page, 'app'),+ };+}++/** The `y` of an element's `translate`, as the engine presents it. */+const translateY = async (element: Locator) =>+ element.evaluate(el => {+ const value = getComputedStyle(el).translate;+ if (value === 'none' || value === '') {+ return 0;+ }+ const [, y = '0px'] = value.split(' ');+ return Number.parseFloat(y);+ });++/**+ * The chevron's angle on screen, degrees, read from its transform. The angle+ * of `b` over `d` reads the same with the right-to-left mirror.+ */+const rotation = async (element: Locator) =>+ element.evaluate(el => {+ const matrix = /matrix\(([^)]+)\)/.exec(getComputedStyle(el).transform);+ const [, b = 0, , d = 1] =+ matrix == null ? [] : matrix[1].split(',').map(Number);+ return (Math.atan2(b, d) * 180) / Math.PI;+ });++async function tapToggle(page: Page) {+ const {toggle} = parts(page);+ const box = await toggle.boundingBox();+ if (box == null) {+ throw new Error('no toggle');+ }+ const driver = await touchDriver(page);+ await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2});+}++async function open(page: Page, story = STORY) {+ await openStory(page, storybook(), story);+ const touch = await page.evaluate(+ () => matchMedia('(pointer: coarse)').matches,+ );+ test.skip(!touch, 'the expansion moves under a finger only');+ await expect(parts(page).below).toBeVisible();+}++/** What one frame of an expand or a collapse shows, in px. */+interface Frame {+ readonly t: number;+ /** The bottom of the folder's own row. */+ readonly parentBottom: number;+ /**+ * The group's top, its height, the part of it that shows, its opacity, and+ * whether it is inert.+ */+ readonly group: {+ readonly top: number;+ readonly height: number;+ readonly shown: number;+ readonly opacity: number;+ readonly isInert: boolean;+ } | null;+ /** The top of the first row below the folder, with its motion. */+ readonly belowTop: number;+ /** The bottom of the folder's last sibling's own row, with its motion. */+ readonly lastBottom: number;+ /** The lowest point the folder's guide column paints. */+ readonly guideBottom: number;+ /** The tree's box, top and bottom. */+ readonly treeTop: number;+ readonly treeBottom: number;+ /** How far past its top and bottom edges the tree paints; null: no clip. */+ readonly paint: {readonly top: number; readonly bottom: number} | null;+ /** The bottom of the tree's last row, with its motion. */+ readonly lowestBottom: number;+ /** The focused row's focus ring, top and bottom; null: no ring. */+ readonly ring: {readonly top: number; readonly bottom: number} | null;+}++/**+ * Records every frame the page presents while `act` runs and for `ms` after.+ * The part of the group that shows is its box less its clip and the slide of+ * its rows. A blank band then reads as a gap above the row below.+ */+async function recordFrames(+ page: Page,+ act: () => Promise<void>,+ ms = 700,+): Promise<Frame[]> {+ await page.evaluate(() => {+ const w = window as unknown as {__frames: unknown[]; __record: boolean};+ w.__frames = [];+ w.__record = true;+ const item = (id: string) =>+ document.querySelector<HTMLElement>(+ `[role="treeitem"][data-tree-id="${id}"]`,+ );+ // A row's own box: the part of its item that holds its content.+ const rowBox = (li: Element) =>+ [...li.children].find(+ child =>+ child.tagName === 'DIV' &&+ child.querySelector('.astryx-tree-list-item') != null,+ ) ?? li;+ const insetBottom = (clip: string) => {+ const match = /inset\(([^)]*)\)/.exec(clip);+ if (match == null) {+ return 0;+ }+ const sides = match[1].trim().split(/\s+/).map(Number.parseFloat);+ return sides.length >= 3 ? sides[2] : sides[0];+ };+ const translateOf = (el: Element) => {+ const value = getComputedStyle(el).translate;+ return value === 'none' || value === ''+ ? 0+ : Number.parseFloat(value.split(' ')[1] ?? '0');+ };+ const tick = () => {+ const parent = item('components');+ const below = item('app');+ const last = item('index');+ if (parent == null || below == null || last == null) {+ return;+ }+ const group = parent.querySelector<HTMLElement>(+ ':scope > [role="group"]',+ );+ let shownGroup = null;+ if (group != null) {+ const box = group.getBoundingClientRect();+ const style = getComputedStyle(group);+ const first = group.querySelector(':scope > [role="treeitem"]');+ const slide = first == null ? 0 : Math.min(0, translateOf(first));+ shownGroup = {+ top: box.top,+ height: box.height,+ shown: Math.max(+ 0,+ Math.min(box.height, box.height - insetBottom(style.clipPath)) ++ slide,+ ),+ opacity: Number(style.opacity),+ isInert: group.inert,+ };+ }+ const column = below+ .querySelector('.astryx-tree-list-guide')+ ?.getBoundingClientRect();+ const columnX = column == null ? 0 : column.left + column.width / 2;+ let guideBottom = 0;+ for (const line of document.querySelectorAll(+ '[role="tree"] .astryx-tree-list-guide',+ )) {+ const box = line.getBoundingClientRect();+ if (+ box.height === 0 ||+ Math.abs(box.left + box.width / 2 - columnX) > 1+ ) {+ continue;+ }+ const bottom =+ group != null && shownGroup != null && group.contains(line)+ ? Math.min(box.bottom, shownGroup.top + shownGroup.shown)+ : box.bottom;+ guideBottom = Math.max(guideBottom, bottom);+ }+ const tree = parent.closest<HTMLElement>('[role="tree"]');+ const treeBox = tree?.getBoundingClientRect();+ const treeClip = tree == null ? 'none' : getComputedStyle(tree).clipPath;+ const sides = /inset\(([^)]*)\)/+ .exec(treeClip)?.[1]+ .trim()+ .split(/\s+/)+ .map(Number.parseFloat);+ const rows = tree?.querySelectorAll('[role="treeitem"]') ?? [];+ const lowest = rows[rows.length - 1];+ // The ring is the outline of the part of the focused row that draws it.+ const focused = document.activeElement?.closest('[role="treeitem"]');+ const ringOwner =+ focused == null+ ? null+ : [rowBox(focused), ...rowBox(focused).querySelectorAll('*')].find(+ el => Number.parseFloat(getComputedStyle(el).outlineWidth) > 0,+ );+ let ring = null;+ if (ringOwner != null) {+ const style = getComputedStyle(ringOwner);+ const reach =+ Number.parseFloat(style.outlineWidth) ++ Number.parseFloat(style.outlineOffset);+ const box = ringOwner.getBoundingClientRect();+ ring = {top: box.top - reach, bottom: box.bottom + reach};+ }+ w.__frames.push({+ t: performance.now(),+ parentBottom: rowBox(parent).getBoundingClientRect().bottom,+ group: shownGroup,+ belowTop: below.getBoundingClientRect().top,+ lastBottom: rowBox(last).getBoundingClientRect().bottom,+ guideBottom,+ treeTop: treeBox?.top ?? 0,+ treeBottom: treeBox?.bottom ?? 0,+ paint:+ sides == null || treeBox == null+ ? null+ : {+ top: treeBox.top + sides[0],+ bottom:+ treeBox.bottom - (sides.length >= 3 ? sides[2] : sides[0]),+ },+ lowestBottom:+ lowest == null ? 0 : rowBox(lowest).getBoundingClientRect().bottom,+ ring,+ });+ if (w.__record) {+ requestAnimationFrame(tick);+ }+ };+ requestAnimationFrame(tick);+ });+ await act();+ await page.waitForTimeout(ms);+ return page.evaluate(() => {+ const w = window as unknown as {__frames: Frame[]; __record: boolean};+ w.__record = false;+ return w.__frames;+ });+}++/** The gap above the row below that no row of the group fills, per frame. */+const blankBands = (frames: ReadonlyArray<Frame>) =>+ frames.map(frame =>+ frame.group == null+ ? frame.belowTop - frame.parentBottom+ : frame.belowTop - (frame.group.top + frame.group.shown),+ );++/** How far a frame may put the rows that glide off the group's shown part. */+const BAND_ALLOWANCE = 1.5;++/**+ * Whether a frame shows the row below inside its travel, between a tenth and+ * nine tenths of the way. A jump shows it there at no frame rate.+ */+const insideTravel = (from: number, to: number) => {+ const margin = Math.abs(to - from) / 10;+ const low = Math.min(from, to) + margin;+ const high = Math.max(from, to) - margin;+ return (frame: Pick<Frame, 'belowTop'>) =>+ frame.belowTop > low && frame.belowTop < high;+};++/**+ * The times, ms into the glide, at which the theme's move curve covers each+ * share of the way. The glide samples that curve (`--ease-move`) over its+ * duration. The browser evaluates the curve here on a probe of its own. So+ * at these times a glide that jumps is at its end, not inside its travel.+ */+async function timesAtShares(+ page: Page,+ ms: number,+ shares: ReadonlyArray<number>,+): Promise<number[]> {+ return page.locator('[role="tree"]').evaluate(+ (tree, {duration, wanted}) => {+ const easing = getComputedStyle(tree)+ .getPropertyValue('--ease-move')+ .trim();+ const probe = document.createElement('div');+ document.body.append(probe);+ const curve = probe.animate([{opacity: 0}, {opacity: 1}], {+ duration: 1000,+ easing,+ fill: 'both',+ });+ curve.pause();+ const shareAt = (fraction: number) => {+ curve.currentTime = fraction * 1000;+ return Number(getComputedStyle(probe).opacity);+ };+ const times = wanted.map(share => {+ let low = 0;+ let high = 1;+ for (let step = 0; step < 30; step++) {+ const middle = (low + high) / 2;+ if (shareAt(middle) < share) {+ low = middle;+ } else {+ high = middle;+ }+ }+ return ((low + high) / 2) * duration;+ });+ curve.cancel();+ probe.remove();+ return times;+ },+ {duration: ms, wanted: shares},+ );+}++/** The shares of the travel at which the held glide is read. */+const SHARES = [0.2, 0.4, 0.6, 0.8];++/**+ * Seeks the held motion to each time in `times`, offset from the held origin+ * like the rows' glide. At each point it reads the row below's top and the+ * group, while the group shows.+ */+async function seekThroughGlide(+ page: Page,+ held: ReadonlyArray<HeldAnimation>,+ times: ReadonlyArray<number>,+) {+ const glide = held.find(+ animation =>+ animation.kind === 'Animation' &&+ animation.keyframes.some(frame => 'translate' in frame),+ );+ if (glide == null) {+ throw new Error(`no glide held: ${JSON.stringify(held)}`);+ }+ const {below, group} = parts(page);+ const points = [];+ for (const time of times) {+ await seekAnimations(page, time + glide.offsetMs);+ points.push({+ time,+ belowTop: (await below.boundingBox())?.y ?? 0,+ group:+ (await group.count()) === 0+ ? null+ : await group.evaluate(el => ({+ opacity: Number(getComputedStyle(el).opacity),+ isInert: (el as HTMLElement).inert,+ })),+ });+ }+ return points;+}++/**+ * The glide's duration in the two cases that record every frame, ms. WebKit+ * can present no frame for about 70 ms while it first composites a newly+ * animated layer, longer on a loaded runner. The stock 300 ms glide eases out+ * and is mid-travel for only about 113 ms, so one such stall can leave a+ * single frame there. At 1200 ms the same curve is mid-travel for about+ * 450 ms. A theme may set any duration; the stock one is checked on its own.+ */+const RECORDED_GLIDE_MS = 1200;++/** Sets the glide's duration where the tree reads it, as a theme does. */+const lengthenGlide = async (page: Page, ms: number) =>+ page+ .locator('[role="tree"]')+ .evaluate(+ (tree, duration) =>+ (tree as HTMLElement).style.setProperty(+ '--duration-medium',+ `${duration}ms`,+ ),+ ms,+ );++/** Waits until nothing in the tree animates. */+const treeAtRest = async (page: Page) =>+ expect+ .poll(async () =>+ page+ .locator('[role="tree"]')+ .evaluate(tree => tree.getAnimations({subtree: true}).length),+ )+ .toBe(0);++/** The theme's glide duration where the tree is, in ms. */+const glideMs = async (page: Page) =>+ page.locator('[role="tree"]').evaluate(tree => {+ const probe = document.createElement('div');+ probe.style.transitionDuration = 'var(--duration-medium)';+ tree.append(probe);+ const value = getComputedStyle(probe).transitionDuration;+ probe.remove();+ return value.endsWith('ms')+ ? Number.parseFloat(value)+ : Number.parseFloat(value) * 1000;+ });++/** The durations of the motion a toggle starts, read on its first frame. */+async function startedDurations(page: Page) {+ return page.evaluate(async () => {+ await new Promise(requestAnimationFrame);+ const parent = document.querySelector(+ '[role="treeitem"][data-tree-id="components"]',+ );+ const durationOf = (el: Element | null | undefined) =>+ el+ ?.getAnimations()+ .map(animation =>+ Number(animation.effect?.getComputedTiming().duration),+ ) ?? [];+ return {+ group: durationOf(parent?.querySelector(':scope > [role="group"]')),+ below: durationOf(+ document.querySelector('[role="treeitem"][data-tree-id="app"]'),+ ),+ chevron: durationOf(+ parent?.querySelector(+ ':scope > :not([role="group"]) [data-tree-toggle] .astryx-icon',+ ),+ ),+ };+ });+}++test('expand under a finger: the rows below glide while the group fades in, and no frame shows a blank band', async ({+ page,+}) => {+ await open(page);+ await lengthenGlide(page, RECORDED_GLIDE_MS);+ const before = (await parts(page).below.boundingBox())?.y ?? 0;+ const frames = await recordFrames(+ page,+ async () => tapToggle(page),+ RECORDED_GLIDE_MS + 400,+ );+ const moving = frames.filter(frame => frame.group != null);+ expect(moving.length, 'frames with the group').toBeGreaterThan(4);+ const height = moving[0].group?.height ?? 0;+ // The checks below judge at least two frames of the glide. A page starved+ // of frames fails by name.+ requireFrames(frames, {+ min: 2,+ during: 'the rows below glide down',+ where: insideTravel(before, before + height),+ });+ // Every frame: the row below sits right under the part of the group that+ // shows. A blank band between them is the flicker.+ for (const [i, band] of blankBands(moving).entries()) {+ expect(band, `frame ${i}: ${JSON.stringify(moving[i])}`).toBeLessThan(+ BAND_ALLOWANCE,+ );+ }+ // The group fades in from its first frame: it does not show at rest first.+ expect(moving[0].group?.opacity ?? 1).toBeLessThan(1);+ expect(frames[frames.length - 1].belowTop - before).toBeCloseTo(height, 0);+ // The row below passes through its travel, not one jump. How many frames+ // land inside it depends on the runner. So the glide's own timeline is read+ // too: the row moves down through its travel as the glide's time runs.+ const {below, group} = parts(page);+ await tapToggle(page);+ await expect(group).toHaveCount(0);+ await treeAtRest(page);+ const times = await timesAtShares(page, await glideMs(page), SHARES);+ const glide = await armHold(page, below, {+ judges: {target: below, property: 'translate'},+ });+ await tapToggle(page);+ const points = await seekThroughGlide(page, await glide.held(), times);+ for (const [i, point] of points.entries()) {+ expect(+ insideTravel(before, before + height)(point),+ JSON.stringify(points),+ ).toBe(true);+ if (i > 0) {+ expect(point.belowTop, JSON.stringify(points)).toBeGreaterThan(+ points[i - 1].belowTop,+ );+ }+ }+ await releaseAnimations(page, {finish: true});+ await expect.poll(async () => translateY(below)).toBe(0);+});++test('collapse under a finger: the group fades out as the rows below glide up, with no jump and no blank band', async ({+ page,+}) => {+ await open(page);+ await tapToggle(page);+ await expect(parts(page).child).toBeVisible();+ await page.waitForTimeout(700);+ await lengthenGlide(page, RECORDED_GLIDE_MS);+ const expanded = (await parts(page).below.boundingBox())?.y ?? 0;+ const height = (await parts(page).group.boundingBox())?.height ?? Number.NaN;+ const frames = await recordFrames(+ page,+ async () => tapToggle(page),+ RECORDED_GLIDE_MS + 400,+ );+ // The checks below judge at least two frames of the glide, three of the+ // fade and five of the leaving group. A page starved of frames fails by name.+ requireFrames(frames, {+ min: 2,+ during: 'the rows below glide up',+ where: insideTravel(expanded, expanded - height),+ });+ requireFrames(frames, {+ min: 5,+ during: 'the group leaves',+ where: frame => frame.group != null,+ });+ const fading = requireFrames(frames, {+ min: 3,+ during: 'the group fades out',+ where: frame => frame.group != null && frame.group.opacity < 1,+ });+ // It takes no input while it fades out, on every frame that shows it.+ for (const frame of fading) {+ expect(frame.group?.isInert, JSON.stringify(frame)).toBe(true);+ }+ for (const [i, band] of blankBands(frames).entries()) {+ expect(band, `frame ${i}: ${JSON.stringify(frames[i])}`).toBeLessThan(1.5);+ }+ expect(expanded - frames[frames.length - 1].belowTop).toBeCloseTo(height, 0);+ await expect(parts(page).group).toHaveCount(0);+ // How many frames land inside the collapse depends on the runner, so its+ // own timeline is read too. As its time runs, the group still shows, inert+ // and fading, and the row below moves up through its travel.+ const {group, below} = parts(page);+ await tapToggle(page);+ await expect(parts(page).child).toBeVisible();+ await treeAtRest(page);+ const times = await timesAtShares(page, await glideMs(page), SHARES);+ const collapse = await armHold(page, page.locator('[role="tree"]'), {+ count: 2,+ judges: [+ {target: group, property: 'opacity'},+ {target: below, property: 'translate'},+ ],+ });+ await tapToggle(page);+ const points = await seekThroughGlide(page, await collapse.held(), times);+ for (const [i, point] of points.entries()) {+ const summary = JSON.stringify(points);+ expect(point.group?.isInert, summary).toBe(true);+ expect(point.group?.opacity ?? 0, summary).toBeGreaterThan(0.05);+ expect(point.group?.opacity ?? 1, summary).toBeLessThan(0.95);+ expect(insideTravel(expanded, expanded - height)(point), summary).toBe(+ true,+ );+ if (i > 0) {+ expect(point.belowTop, summary).toBeLessThan(points[i - 1].belowTop);+ expect(point.group?.opacity ?? 1, summary).toBeLessThan(+ points[i - 1].group?.opacity ?? 0,+ );+ }+ }+ await releaseAnimations(page, {finish: true});+ await expect(group).toHaveCount(0);+});++test('collapse under a finger: no row of the tree paints past its bottom edge onto the content after it', async ({+ page,+}) => {+ await open(page, 'core-treelist--with-content-below');+ await tapToggle(page);+ await expect(parts(page).child).toBeVisible();+ await page.waitForTimeout(700);+ const frames = await recordFrames(page, async () => tapToggle(page));+ expect(+ frames.some(frame => frame.lowestBottom > frame.treeBottom + 1),+ 'frames where the last row lies past the tree',+ ).toBe(true);+ for (const [i, frame] of frames.entries()) {+ // The rows gliding up show only as they enter the tree's box. Past it,+ // only a focus ring's reach paints: 5 px in the default theme.+ expect(+ Math.min(frame.lowestBottom, frame.paint?.bottom ?? Infinity),+ `frame ${i}: ${JSON.stringify(frame)}`,+ ).toBeLessThan(frame.treeBottom + 5.5);+ }+ // At rest the tree takes no clip.+ expect(frames[frames.length - 1].paint).toBeNull();+});++test('a focus ring on a row at the edge of a moving tree stays whole, while the tree moves and at rest', async ({+ page,+}) => {+ await open(page, 'core-treelist--with-content-below');+ const {toggle} = parts(page);+ // A click from the page toggles the folder and leaves focus where it is.+ const toggleFromPage = async () =>+ toggle.evaluate(el => {+ (el as HTMLElement).click();+ });+ // The last row, at the tree's bottom edge, while an expand moves the tree.+ await page.keyboard.press('Tab');+ await page.keyboard.press('End');+ const expand = await recordFrames(page, toggleFromPage);+ // The first row, at its top edge, while a collapse moves it.+ await page.keyboard.press('Home');+ const collapse = await recordFrames(page, toggleFromPage);+ for (const frames of [expand, collapse]) {+ expect(+ frames.some(frame => frame.paint != null),+ 'frames with the clip',+ ).toBe(true);+ for (const [i, frame] of frames.entries()) {+ expect(frame.ring, `frame ${i}: no ring`).not.toBeNull();+ if (frame.ring != null && frame.paint != null) {+ expect(+ frame.ring.top,+ `frame ${i}: ${JSON.stringify(frame)}`,+ ).toBeGreaterThanOrEqual(frame.paint.top - 0.5);+ expect(+ frame.ring.bottom,+ `frame ${i}: ${JSON.stringify(frame)}`,+ ).toBeLessThanOrEqual(frame.paint.bottom + 0.5);+ }+ }+ expect(frames[frames.length - 1].paint).toBeNull();+ }+});++test('the guide lines beside a group show and hide with it: none runs past the last row it joins', async ({+ page,+}) => {+ await open(page);+ const expand = await recordFrames(page, async () => tapToggle(page));+ const collapse = await recordFrames(page, async () => tapToggle(page));+ for (const phase of [expand, collapse]) {+ for (const [i, frame] of phase.entries()) {+ expect(+ frame.guideBottom,+ `frame ${i}: ${JSON.stringify(frame)}`,+ ).toBeLessThan(frame.lastBottom + BAND_ALLOWANCE);+ }+ }+});++test('the rows below, the group and the chevron move on one timing: the theme’s glide', async ({+ page,+}) => {+ await open(page);+ const ms = await glideMs(page);+ await tapToggle(page);+ const started = await startedDurations(page);+ expect(started.group, JSON.stringify(started)).toContain(ms);+ expect(started.below, JSON.stringify(started)).toContain(ms);+ expect(started.chevron, JSON.stringify(started)).toContain(ms);+});++for (const [written, value] of [+ ['a length', '600ms'],+ ['calc()', 'calc(300ms * 2)'],+] as const) {+ test(`a theme that lengthens the glide, written as ${written}, lengthens the expand`, async ({+ page,+ }) => {+ await open(page);+ // A theme sets its tokens on an ancestor: the tree reads them where it is.+ await page+ .locator('[role="tree"]')+ .evaluate(+ (tree, duration) =>+ (tree as HTMLElement).style.setProperty(+ '--duration-medium',+ duration,+ ),+ value,+ );+ expect(await glideMs(page)).toBe(600);+ await tapToggle(page);+ const started = await startedDurations(page);+ expect(started.group, JSON.stringify(started)).toContain(600);+ expect(started.below, JSON.stringify(started)).toContain(600);+ });+}++async function expandWithHandle(page: Page) {+ await openStory(page, storybook(), 'core-animated-layout--animated-layout');+ const folder = page.locator('[role="treeitem"][data-tree-id="photos"]');+ const toggle = folder.locator(+ ':scope > :not([role="group"]) [data-tree-toggle]',+ );+ return folder.evaluate(+ async (row, button) => {+ (button as HTMLElement).click();+ await new Promise(requestAnimationFrame);+ const tree = row.closest('[role="tree"]');+ const group = row.querySelector(':scope > [role="group"]');+ return document.getAnimations().map(animation => {+ const effect = animation.effect as KeyframeEffect | null;+ const target = effect?.target ?? null;+ const moves = [+ ...new Set(+ (effect?.getKeyframes() ?? []).flatMap(frame =>+ Object.keys(frame).filter(+ key =>+ !['offset', 'computedOffset', 'easing', 'composite'].includes(+ key,+ ),+ ),+ ),+ ),+ ];+ const where =+ target == null+ ? 'none'+ : group?.contains(target)+ ? 'group'+ : tree?.contains(target)+ ? 'tree'+ : 'after';+ return {where, moves};+ });+ },+ await toggle.elementHandle(),+ );+}++test('with an animatedLayout handle, expanding a folder glides what follows it, after the tree too, under a finger and with a mouse', async ({+ page,+ browser,+}) => {+ const isGlideAfter = (animation: {where: string; moves: string[]}) =>+ animation.where === 'after' &&+ animation.moves.some(move => move === 'translate' || move === 'transform');+ const touch = await expandWithHandle(page);+ expect(touch.some(isGlideAfter), JSON.stringify(touch)).toBe(true);+ const context = await browser.newContext({+ hasTouch: false,+ isMobile: false,+ viewport: {width: 900, height: 900},+ });+ try {+ const mouse = await expandWithHandle(await context.newPage());+ expect(mouse.some(isGlideAfter), JSON.stringify(mouse)).toBe(true);+ } finally {+ await context.close();+ }+});++test('Android: a tap expands with the same motion (one touch model)', async ({+ page,+ browserName,+}) => {+ test.skip(browserName !== 'chromium', 'Android is Chromium');+ await open(page);+ const {child, below} = parts(page);+ await tapToggle(page);+ await expect(child).toBeVisible();+ expect(await below.evaluate(el => el.getAnimations().length)).toBeGreaterThan(+ 0,+ );+ await expect.poll(async () => translateY(below)).toBe(0);+});++test('a mouse: a click expands and collapses in one frame, as before', async ({+ browser,+}) => {+ const context = await browser.newContext({+ hasTouch: false,+ isMobile: false,+ viewport: {width: 900, height: 700},+ });+ const page = await context.newPage();+ try {+ await openStory(page, storybook(), STORY);+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ const {group, child, below, toggle} = parts(page);+ await expect(below).toBeVisible();+ await toggle.click();+ await expect(child).toBeVisible();+ // No motion: the row below is already in place, nothing animating it.+ expect(await translateY(below)).toBe(0);+ expect(await below.evaluate(el => el.getAnimations().length)).toBe(0);+ expect(+ await group.evaluate(el => el.getAnimations({subtree: true}).length),+ ).toBe(0);+ await toggle.click();+ // The children leave with the click's own commit.+ await page.evaluate(+ async () =>+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),+ );+ expect(await group.count()).toBe(0);+ expect(await translateY(below)).toBe(0);+ } finally {+ await context.close();+ }+});++test('a mouse under reduced motion: the group comes and goes at once, and the chevron turns on its own transition', async ({+ browser,+}) => {+ const context = await browser.newContext({+ hasTouch: false,+ isMobile: false,+ reducedMotion: 'reduce',+ viewport: {width: 900, height: 700},+ });+ const page = await context.newPage();+ try {+ await openStory(page, storybook(), STORY);+ expect(+ await page.evaluate(() => [+ matchMedia('(pointer: coarse)').matches,+ matchMedia('(prefers-reduced-motion: reduce)').matches,+ ]),+ ).toEqual([false, true]);+ const {group, child, toggle, chevron} = parts(page);+ await expect(parts(page).below).toBeVisible();+ // The page holds the chevron's turn as soon as it runs.+ const turn = await armHold(page, chevron, {+ judges: {target: chevron, property: 'transform'},+ });+ await toggle.click();+ await expect(child).toBeVisible();+ const held = await turn.held();+ expect(+ held.map(animation => animation.kind),+ JSON.stringify(held),+ ).toContain('CSSTransition');+ // Nothing in the group moves or fades.+ expect(+ await group.evaluate(el => el.getAnimations({subtree: true}).length),+ ).toBe(0);+ await releaseAnimations(page, {finish: true});+ await expect.poll(async () => rotation(chevron)).toBeCloseTo(90, 1);+ await toggle.click();+ await page.evaluate(+ async () =>+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),+ );+ expect(await group.count()).toBe(0);+ } finally {+ await context.close();+ }+});++test('under reduced motion and a finger, an expand cross-fades the group in place, opacity only, and the chevron lands at once', async ({+ page,+}) => {+ await page.emulateMedia({reducedMotion: 'reduce'});+ await open(page);+ const {parent, group, child, chevron, below} = parts(page);+ // The page holds the fade as it starts: a hold sent after the tap can come+ // too late on a busy machine.+ const fadeIn = await armHold(page, parent, {+ judges: {target: group, property: 'opacity'},+ });+ await tapToggle(page);+ await expect(child).toBeVisible();+ expectReducedMotionCrossFade(await fadeIn.held());+ // Nothing travels: the row below takes its place at once.+ expect(await translateY(below)).toBe(0);+ expect(await rotation(chevron)).toBeCloseTo(90, 1);+ await releaseAnimations(page, {finish: true});+ // A collapse fades the group out where it is, and nothing travels.+ const fadeOut = await armHold(page, parent, {+ newOnly: true,+ judges: {target: group, property: 'opacity'},+ });+ await tapToggle(page);+ expectReducedMotionCrossFade(await fadeOut.held());+ expect(await translateY(below)).toBe(0);+ await releaseAnimations(page, {finish: true});+ await expect(child).toHaveCount(0);+});++test("right to left: the chevron's quarter turn mirrors", async ({page}) => {+ // Storybook's direction toolbar (a global, not an arg).+ await page.goto(+ `${storybook()}/iframe.html?id=${STORY}&viewMode=story&globals=direction:rtl`,+ );+ await page.locator('#storybook-root > *').first().waitFor();+ await page.evaluate(async () => {+ await document.fonts.ready;+ await new Promise(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(resolve)),+ );+ });+ const touch = await page.evaluate(+ () => matchMedia('(pointer: coarse)').matches,+ );+ test.skip(!touch, 'the expansion moves under a finger only');+ const {chevron, child} = parts(page);+ await expect(parts(page).below).toBeVisible();+ expect(await chevron.evaluate(el => getComputedStyle(el).direction)).toBe(+ 'rtl',+ );+ await tapToggle(page);+ await expect(child).toBeVisible();+ // The mirror lives in the chevron's transform: its horizontal scale is+ // negative, while its angle turns as it does left to right.+ expect(+ await chevron.evaluate(el =>+ Number(/matrix\(([^,]+)/.exec(getComputedStyle(el).transform)?.[1]),+ ),+ ).toBeLessThan(0);+ await expect.poll(async () => rotation(chevron)).toBeCloseTo(90, 1);+});++test('content after the tree takes its place by layout at once, while the rows below inside the tree glide', async ({+ page,+}) => {+ await open(page, 'core-treelist--with-content-below');+ const button = page.getByRole('button', {name: 'Open folder'});+ const {group, below} = parts(page);+ await expect(button).toBeVisible();+ // More content after the tree, holding a position: fixed element, which+ // stays where the viewport puts it as long as nothing transforms its+ // ancestors.+ await button.evaluate(el => {+ const after = document.createElement('div');+ after.style.height = '20px';+ const fixed = document.createElement('div');+ fixed.setAttribute('data-test-fixed', '');+ fixed.style.cssText =+ 'position: fixed; top: 10px; left: 10px; width: 8px; height: 8px;';+ after.append(fixed);+ el.insertAdjacentElement('afterend', after);+ });+ const fixedTop = async () =>+ page+ .locator('[data-test-fixed]')+ .evaluate(el => el.getBoundingClientRect().top);+ const rest = (await button.boundingBox())?.y ?? 0;++ const glide = await armHold(page, page.locator('[role="tree"]'), {+ count: 2,+ judges: {target: below, property: 'translate'},+ });+ await tapToggle(page);+ await glide.held();+ await seekAnimations(page, 0);+ const height = await group.evaluate(el => (el as HTMLElement).offsetHeight);+ // Its new layout at once, one group height down, with nothing on it.+ expect(await button.evaluate(el => getComputedStyle(el).translate)).toBe(+ 'none',+ );+ expect(((await button.boundingBox())?.y ?? 0) - rest).toBeCloseTo(height, 0);+ expect(await fixedTop()).toBeCloseTo(10, 0);+ // The row after the group inside the tree starts at its old place.+ expect(await translateY(below)).toBeCloseTo(-height, 0);+ await releaseAnimations(page, {finish: true});+ await expect.poll(async () => translateY(below)).toBe(0);+ expect(await fixedTop()).toBeCloseTo(10, 0);+});++test('the rows below keep moving on every frame while the main thread is blocked', async ({+ page,+ browserName,+}, testInfo) => {+ test.skip(+ browserName !== 'chromium',+ 'screencast frame evidence is Chromium-only in Playwright',+ );+ await open(page);+ // A longer glide, so the block spans many frames.+ await page+ .locator('[role="tree"]')+ .evaluate(tree =>+ (tree as HTMLElement).style.setProperty('--duration-medium', '900ms'),+ );+ const {below} = parts(page);+ // The row below carries the harness's chip, 16 px, 8 px in from its corner.+ await below.evaluate(+ (row, rgb) => {+ const chip = document.createElement('div');+ chip.setAttribute('data-harness-marker-chip', 'tree-below');+ chip.setAttribute('aria-hidden', 'true');+ chip.style.cssText = `position:absolute;top:8px;left:8px;width:16px;height:16px;background:rgb(${rgb.join(',')});z-index:2147483647;pointer-events:none;`;+ (row as HTMLElement).style.position = 'relative';+ row.append(chip);+ },+ [...MARKER_RGB],+ );+ const cast = await startScreencast(page);+ // The compositor's own record of the frames it presents, so a frame the+ // screencast skips under load is not read as a stall.+ const compositor = await startCompositorTrace(page);+ await page.waitForTimeout(100);+ // The page starts the block itself, once the glide runs: a block the test+ // sends lands later on a busy machine.+ const [block] = await Promise.all([+ blockMainThread(page, 300, {during: below}),+ tapToggle(page),+ ]);+ await page.waitForTimeout(200);+ const presented = await compositor.stop();+ const frames = await cast.stop();+ const tracked = await trackMarker(page, frames);+ const proof = busyWindowProof(tracked, block, {+ axis: 'y',+ settledWithin: 1,+ presented,+ });+ await writeEvidence(+ 'busy-main-thread/tree-list-expand',+ {[`${testInfo.project.name}.json`]: JSON.stringify(proof, null, 1)},+ testInfo,+ );+ // Frames kept coming through the block, each one further down.+ expect(proof.changed, JSON.stringify(proof)).toBeGreaterThanOrEqual(3);+ expect(proof.monotonic, JSON.stringify(proof)).toBe(true);+ expect(proof.longestStallMs, JSON.stringify(proof)).toBeLessThan(40);+});++test(+ 'storyboard: a TreeList row expanding under a finger',+ {tag: '@storyboard'},+ async ({page}, testInfo) => {+ await open(page);+ const ms = await glideMs(page);+ await tapToggle(page);+ const {storyboard} = await animationStoryboard(page, {+ name: 'tree-list-expand',+ clip: {x: 0, y: 0, width: 402, height: 340},+ times: [0, 1, 2, 3, 4, 5, 6, 7].map(k => Math.round((k * ms) / 7)),+ columns: 8,+ cellScale: 0.45,+ judges: {target: parts(page).below, property: 'translate'},+ });+ await releaseAnimations(page, {finish: true});+ await storyboard.write(testInfo);+ },+);diff --git a/packages/core/src/TreeList/__tests__/TreeListGuideAlignment.interaction.browser.spec.ts b/packages/core/src/TreeList/__tests__/TreeListGuideAlignment.interaction.browser.spec.tsindex b71b2dd802..b419880617 100644--- a/packages/core/src/TreeList/__tests__/TreeListGuideAlignment.interaction.browser.spec.ts+++ b/packages/core/src/TreeList/__tests__/TreeListGuideAlignment.interaction.browser.spec.ts@@ -125,3 +125,124 @@ test('guide visibility does not move chevrons', async ({page}) => {expect(withGuides.chevronCenters).toEqual(withoutGuides.chevronCenters);expect(withoutGuides.guideCenters).toEqual([]);});++/**+ * The stretches no guide line paints in the bottom row's connector column,+ * from the top row's bottom edge to the bottom row's middle.+ */+async function guideGaps(page: Page, ids: {top: string; bottom: string}) {+ return page.evaluate(({top, bottom}) => {+ const row = (id: string) => {+ const item = document.querySelector(`[data-tree-id="${id}"]`);+ return item?.querySelector('.astryx-tree-list-item') ?? item;+ };+ const topRow = row(top)?.getBoundingClientRect();+ const bottomRow = row(bottom)?.getBoundingClientRect();+ // The column of the bottom row's own connector.+ const own = [+ ...(document+ .querySelector(`[data-tree-id="${bottom}"]`)+ ?.querySelectorAll('.astryx-tree-list-guide') ?? []),+ ]+ .map(line => line.getBoundingClientRect())+ .filter(box => box.height > 0)+ .sort((a, b) => b.left - a.left)[0];+ if (topRow == null || bottomRow == null || own == null) {+ throw new Error('rows or connector not found');+ }+ const x = own.left + own.width / 2;+ const spans = [+ ...document.querySelectorAll('[role="tree"] .astryx-tree-list-guide'),+ ]+ .map(line => line.getBoundingClientRect())+ .filter(+ box => box.height > 0 && Math.abs(box.left + box.width / 2 - x) < 1,+ )+ .map(box => [box.top, box.bottom] as const)+ .sort((a, b) => a[0] - b[0]);+ const from = topRow.bottom;+ const to = bottomRow.top + bottomRow.height / 2;+ const gaps: [number, number][] = [];+ let reached = from;+ for (const [start, end] of spans) {+ if (start > reached + 0.5 && start < to) {+ gaps.push([reached, Math.min(start, to)]);+ }+ reached = Math.max(reached, end);+ }+ if (reached < to - 0.5) {+ gaps.push([reached, to]);+ }+ return gaps;+ }, ids);+}++test("a parent's guide line runs unbroken past an expanded child's rows to its last child, at rest, with a mouse and under a finger", async ({+ page,+ browser,+}) => {+ // Project is the last row at its level, and src, its expanded child, is not+ // its last. So the line from src to package.json passes src's own rows.+ const open = async (target: Page) => {+ await target.goto(+ `${storybook.origin}/iframe.html?id=core-treelist--themed-guides&viewMode=story`,+ );+ await target.locator('[data-tree-id="pkg"]').waitFor();+ };+ await open(page);+ expect(await guideGaps(page, {top: 'src', bottom: 'pkg'})).toEqual([]);+ const context = await browser.newContext({hasTouch: true, isMobile: true});+ try {+ const touchPage = await context.newPage();+ await open(touchPage);+ expect(await guideGaps(touchPage, {top: 'src', bottom: 'pkg'})).toEqual([]);+ } finally {+ await context.close();+ }+});++test('at a wide row gap a last connector ends at its row, and a first one starts at its parent', async ({+ page,+}) => {+ await openStory(page, 'ltr', 'lineGuides');+ const issues = await page.evaluate(async () => {+ const tree = document.querySelector<HTMLElement>('.astryx-tree-list');+ tree?.style.setProperty('--tree-list-row-gap', '16px');+ await new Promise(requestAnimationFrame);+ const found: string[] = [];+ for (const item of document.querySelectorAll('[role="treeitem"]')) {+ if (Number(item.getAttribute('aria-level')) < 2) {+ continue;+ }+ const wrapper = item.firstElementChild;+ const row = wrapper?.querySelector('.astryx-tree-list-item');+ // The row's own connector is the guide in its innermost column.+ const own = [+ ...(wrapper?.firstElementChild?.querySelectorAll(+ '.astryx-tree-list-guide',+ ) ?? []),+ ]+ .map(line => line.getBoundingClientRect())+ .sort((a, b) => b.left - a.left)[0];+ if (wrapper == null || row == null || own == null) {+ found.push(`${item.getAttribute('data-tree-id')}: no connector`);+ continue;+ }+ const name = item.getAttribute('data-tree-id');+ const last =+ item.getAttribute('aria-posinset') ===+ item.getAttribute('aria-setsize');+ if (last && own.bottom > row.getBoundingClientRect().bottom + 0.5) {+ found.push(+ `${name}: ends ${own.bottom} past ${row.getBoundingClientRect().bottom}`,+ );+ }+ const top = wrapper.getBoundingClientRect().top;+ if (item.getAttribute('aria-posinset') === '1' && own.top > top + 0.5) {+ found.push(`${name}: starts ${own.top} below ${top}`);+ }+ }+ return found;+ });+ expect(issues).toEqual([]);+});diff --git a/packages/core/src/motion/animatedLayoutAdopters.test.tsx b/packages/core/src/motion/animatedLayoutAdopters.test.tsxindex f4f6d4fb0b..ab0c163394 100644--- a/packages/core/src/motion/animatedLayoutAdopters.test.tsx+++ b/packages/core/src/motion/animatedLayoutAdopters.test.tsx@@ -173,6 +173,117 @@ describe.each([});});+describe('a TreeList under a finger with no handle (component:TreeList FR8)', () => {+ const originalMatchMedia = window.matchMedia;++ afterEach(() => {+ window.matchMedia = originalMatchMedia;+ });++ function stubPointer(isCoarse: boolean) {+ window.matchMedia = (query: string) =>+ ({+ matches: isCoarse && query.includes('coarse'),+ media: query,+ addEventListener() {},+ removeEventListener() {},+ }) as unknown as MediaQueryList;+ }++ function Page() {+ return (+ <div>+ <TreeList+ items={+ [+ {+ id: 'src',+ label: 'src',+ children: [{id: 'index', label: 'index.ts'}],+ },+ {id: 'readme', label: 'README.md'},+ ] satisfies TreeListItemData[]+ }+ />+ <p data-testid="after">Notes</p>+ </div>+ );+ }++ /** The row after the folder and the content after the tree each sit 80 px lower once measured. */+ function stubTreeGeometry() {+ vi.spyOn(screen.getByRole('tree'), 'getBoundingClientRect').mockReturnValue(+ new DOMRect(0, 0, 400, 600),+ );+ const below =+ document.querySelector<HTMLElement>('[data-tree-id="readme"]') ??+ document.body;+ const after = screen.getByTestId('after');+ for (const element of [below, after]) {+ let reads = 0;+ vi.spyOn(element, 'getBoundingClientRect').mockImplementation(() => {+ reads += 1;+ return new DOMRect(0, reads === 1 ? 40 : 120, 400, 20);+ });+ }+ return {below, after};+ }++ it('glides the rows after a toggled row inside the tree, and leaves the content after the tree in place', async () => {+ stubPointer(true);+ const user = userEvent.setup();+ render(<Page />);+ const {below, after} = stubTreeGeometry();+ await user.click(+ document.querySelector<HTMLElement>('[data-tree-toggle]') ??+ document.body,+ );+ await flush();+ expect(animated).toContain(below);+ expect(animated).not.toContain(after);+ });++ it('clips the bottom edge of the tree while its own motion runs, and not at rest', async () => {+ stubPointer(true);+ const user = userEvent.setup();+ render(<Page />);+ stubTreeGeometry();+ const tree = screen.getByRole('tree');+ let settle = () => {};+ const motion = {+ playState: 'running',+ effect: {getComputedTiming: () => ({endTime: 300})},+ finished: new Promise<void>(resolve => {+ settle = resolve;+ }),+ } as unknown as Animation;+ tree.getAnimations = () => [motion];+ await user.click(+ document.querySelector<HTMLElement>('[data-tree-toggle]') ??+ document.body,+ );+ await flush();+ expect(tree.style.clipPath).toMatch(/^inset\(-100vmax -100vmax calc/);+ settle();+ await flush();+ expect(tree.style.clipPath).toBe('');+ });++ it('changes nothing under a mouse', async () => {+ stubPointer(false);+ const user = userEvent.setup();+ render(<Page />);+ stubTreeGeometry();+ await user.click(+ document.querySelector<HTMLElement>('[data-tree-toggle]') ??+ document.body,+ );+ await flush();+ expect(animated).toEqual([]);+ expect(screen.getByRole('tree').style.clipPath).toBe('');+ });+});+describe('Collapsible changes another component made (spec:AST-105 FR3)', () => {it('glides the items between when a single-mode group closes one item to open another', async () => {const user = userEvent.setup();