From 08652ac2b38987250de89bd45c10b939477757e4 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 2 Nov 2026 22:18:08 -0800 Subject: [PATCH 01/10] feat(List): animate row inserts, removals and moves with animatedLayout A List that takes the handle useAnimatedLayout returns animates its row changes on one shared motion, for every pointer. An inserted row enters, a removed row collapses in place, and a row that crosses rows moving the other way rides above them. The rows after a change, and the content after the list, glide to their new places. Rows match across renders by their itemKey; a row without one changes at once. The row marks the update module writes (item key, leaving, travelling) live in their own private-attribute owner modules. A list under the handle isolates for every pointer, so a sliding row stays below a page-level sticky header. The List and ListItem records now say the row updates and itemKey are implemented, and their verified_by lists the files that verify them. --- .changeset/list-animated-layout.md | 7 + apps/storybook/stories/List.stories.tsx | 152 ++++ docs/specs/components/List/List.spec.md | 4 +- docs/specs/components/List/ListItem.spec.md | 8 +- packages/core/api-report.md | 2 + packages/core/src/List/List.doc.mjs | 5 + packages/core/src/List/List.test.tsx | 27 +- packages/core/src/List/List.tsx | 58 +- packages/core/src/List/ListContext.tsx | 5 + packages/core/src/List/ListItem.doc.mjs | 11 + packages/core/src/List/ListItem.tsx | 52 +- .../ListUpdates.interaction.browser.spec.ts | 812 ++++++++++++++++++ .../core/src/List/listLayoutUpdates.test.tsx | 632 ++++++++++++++ packages/core/src/List/listLayoutUpdates.ts | 541 ++++++++++++ .../motion/animatedLayout.boundary.test.ts | 2 + .../src/privateAttributes/itemKey.stylex.ts | 25 + .../src/privateAttributes/leaving.stylex.ts | 23 + .../privateAttributes/travelling.stylex.ts | 63 ++ 18 files changed, 2404 insertions(+), 25 deletions(-) create mode 100644 .changeset/list-animated-layout.md create mode 100644 packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts create mode 100644 packages/core/src/List/listLayoutUpdates.test.tsx create mode 100644 packages/core/src/List/listLayoutUpdates.ts create mode 100644 packages/core/src/privateAttributes/itemKey.stylex.ts create mode 100644 packages/core/src/privateAttributes/leaving.stylex.ts create mode 100644 packages/core/src/privateAttributes/travelling.stylex.ts diff --git a/.changeset/list-animated-layout.md b/.changeset/list-animated-layout.md new file mode 100644 index 0000000000000..f42b0aaab843d --- /dev/null +++ b/.changeset/list-animated-layout.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] `List` takes `animatedLayout`, the handle from `useAnimatedLayout({containerRef})`, and `ListItem` takes `itemKey`, the row's identity. With the handle, when rows are inserted, removed or reordered, an inserted row enters, a removed row (a swiped one with its action showing) collapses in place, and a row that crosses rows moving the other way rides above them with the surface color behind it, as an iOS table's opaque cell does. The rows after a change and the content after the list, up to the handle's container, glide to their new places. All of it runs on one shared motion and starts together, under every pointer; under Reduce Motion nothing travels. A row without an `itemKey` changes at once, and without the handle the whole list does. + +@vjeux diff --git a/apps/storybook/stories/List.stories.tsx b/apps/storybook/stories/List.stories.tsx index 8d40fa67154f0..34a26bdbff615 100644 --- a/apps/storybook/stories/List.stories.tsx +++ b/apps/storybook/stories/List.stories.tsx @@ -19,6 +19,7 @@ import {Icon} from '@astryxdesign/core/Icon'; import {Switch} from '@astryxdesign/core/Switch'; import {Heading, Text} from '@astryxdesign/core/Text'; import {VStack} from '@astryxdesign/core/Layout'; +import {useAnimatedLayout} from '@astryxdesign/core/hooks'; import {rtlStyles} from '@astryxdesign/core/utils'; import { Cog6ToothIcon, @@ -762,3 +763,154 @@ export const HeaderInFlexParent: Story = { }, }, }; + +function AnimatedChangesDemo() { + const [rows, setRows] = useState([ + 'Inbox', + 'Sent', + 'Drafts', + 'Archive', + 'Spam', + ]); + const [next, setNext] = useState(1); + const containerRef = useRef(null); + const animatedLayout = useAnimatedLayout({containerRef}); + return ( +
+ + + {rows.map(label => ( + {}} + /> + ))} + + {`${rows.length} folders`} +
+ ); +} + +export const AnimatedChanges: Story = { + render: () => , + parameters: { + docs: { + description: { + story: + 'With `animatedLayout` (the handle from `useAnimatedLayout`) and ' + + 'an `itemKey` on each row, an inserted row enters, a removed row ' + + 'collapses in place, a row crossing rows that move the other way ' + + 'rides above them with the surface color behind it, and the rows ' + + 'after a change and the buttons below the list glide to their new ' + + 'places, all on one shared motion, under every pointer.', + }, + }, + }, +}; + +/** The swipe story's row with no swipe actions. */ +const PLAIN_ROW = 'Notes'; + +function AnimatedChangesSwipeDemo() { + const [rows, setRows] = useState([ + 'Inbox', + 'Sent', + 'Drafts', + 'Archive', + PLAIN_ROW, + ]); + const containerRef = useRef(null); + const animatedLayout = useAnimatedLayout({containerRef}); + const moveFirst = (label: string) => + setRows(current => + current.includes(label) + ? [label, ...current.filter(row => row !== label)] + : current, + ); + return ( +
+ + {rows.map(label => ( + {}} + swipeActions={ + label === PLAIN_ROW + ? undefined + : { + trailing: [ + { + label: 'Delete', + variant: 'destructive', + hasRemoval: true, + onActivate: () => + setRows(current => + current.filter(row => row !== label), + ), + }, + ], + } + } + /> + ))} + +
+ ); +} + +export const AnimatedChangesSwipe: Story = { + render: () => , + parameters: { + docs: { + description: { + story: + 'With `animatedLayout`, a row swiped away with a removal action ' + + 'collapses in place, its action showing, while the rows below ' + + 'glide up into its gap on the shared motion. A row moved up ' + + 'across the swipeable rows, with swipe actions (Archive) or ' + + 'without (Notes), rides above the rows it crosses.', + }, + }, + }, +}; diff --git a/docs/specs/components/List/List.spec.md b/docs/specs/components/List/List.spec.md index 7da2fb008afe9..ef704aabc0fd6 100644 --- a/docs/specs/components/List/List.spec.md +++ b/docs/specs/components/List/List.spec.md @@ -16,6 +16,8 @@ verified_by: packages/core/src/Item/Item.test.tsx, packages/core/src/List/ListItem.hitArea.test.tsx, packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.ts, + packages/core/src/List/listLayoutUpdates.test.tsx, + packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts, packages/core/src/theme/derivedVarRegistry.test.ts, packages/core/src/theme/generateThemeRules.test.ts, apps/storybook/stories/List.stories.tsx, @@ -51,7 +53,7 @@ system_specs: | Behavior | One edge treatment applies to every ListItem row and decides where row content and row paint sit relative to the list's edges and the host's padding. With `reorderable`, rows reorder by dragging a handle or through reorder mode (`spec:AST-103` FR3, FR4). Under a coarse pointer a row's press follows the cell profile (`spec:AST-094` FR11); with `animatedLayout`, row updates animate (`spec:AST-105`). A row menu opens from the row's own `
  • ` on the context request (FR13). | | End-user impact | Row text can share the line of the list header and a heading above, with row paint stopping at the text, reaching into the host padding, or reaching the host edges. Touch users get a 44 px row target (FR10) and the cell press (FR11); with `animatedLayout`, row updates animate for every pointer (FR12). A row with a menu opens it by a long press, a right click, or Shift+F10, or through its More actions button (FR13). | | Builder impact | One `edge` choice per list. `flush` works anywhere; `outset` and `bleed` act only inside a host that publishes container padding. Passing an `animatedLayout` handle is one new choice, and a row menu is the other: the caller passes a ListItem's ref to `useContextMenu` (FR13), and who draws a plain row's More actions button is open (OQ2); and rows animate only with an `itemKey`; the touch target and press need none. | -| Compatibility/readiness | Additive; omission keeps current geometry; `edgeCompensation` keeps working with a codemod to `edge`. `reorderable` and `itemKey` are additive and stable, specified and not implemented yet; without them nothing changes. `animatedLayout` is additive and specified, not implemented yet. The touch target (FR10) and the press's compositor release (FR11) are implemented under coarse primary pointers. Neither changes anything under a fine pointer. Row menus (FR13) are additive and specified, not implemented yet. | +| Compatibility/readiness | Additive; omission keeps current geometry; `edgeCompensation` keeps working with a codemod to `edge`. `reorderable` is additive and stable, specified and not implemented yet. `itemKey` and `animatedLayout`'s row updates (FR12) are implemented; its start and end content motion is not. The touch target (FR10) and the press's compositor release (FR11) are implemented under coarse primary pointers. Neither changes anything under a fine pointer. Row menus (FR13) are additive and specified, not implemented yet. | | Review checks | Reject header movement, row paint past the host's padding edge, duplicated padding values, physical-edge logic, automatic opt-in, a ListItem-level edge prop, or a second prop that can contradict `edge`. | | Governing rules | `architecture:container-padding/INV3`, `INV9–INV11`; `spec:AST-002/DEC-1–DEC-2`; `spec:AST-017/FR4`; `spec:AST-057/FR9`. `spec:AST-103`. `spec:AST-094` FR4, FR5, FR11, FR13; `spec:AST-105` FR1–FR5, FR8. `spec:AST-107` FR8 (row menus). | diff --git a/docs/specs/components/List/ListItem.spec.md b/docs/specs/components/List/ListItem.spec.md index 7f99b78f3faa0..8ab0bb88cd9fc 100644 --- a/docs/specs/components/List/ListItem.spec.md +++ b/docs/specs/components/List/ListItem.spec.md @@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, layout, theming] verified_by: [ packages/core/src/List/List.test.tsx, + packages/core/src/List/listLayoutUpdates.test.tsx, packages/core/src/theme/themingTargets.test.ts, scripts/check-knowledge.mjs, apps/storybook/rtl-audit/targets.json, @@ -36,11 +37,11 @@ system_specs: [spec:AST-057, spec:AST-103] | Area | Contract | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Public contract | `ListItem` with `label`, `description`, `startContent`, `endContent`, `onClick`, `interactiveRef`, `href`, `target`, `rel`, `align`, `isDisabled`, `isSelected`, `swipe`, `xstyle`, `className`, `style`, and `ref`, with the deprecated `swipeActions` and `swipeBehavior` until `spec:AST-057` CLN-0025; the row carries `component:List`'s `list-item` target. `itemKey` (`spec:AST-103` DEC-4) is specified but not shipped. | +| Public contract | `ListItem` with `label`, `description`, `startContent`, `endContent`, `onClick`, `interactiveRef`, `href`, `target`, `rel`, `align`, `isDisabled`, `isSelected`, `itemKey`, `swipe`, `xstyle`, `className`, `style`, and `ref`, with the deprecated `swipeActions` and `swipeBehavior` until `spec:AST-057` CLN-0025; the row carries `component:List`'s `list-item` target. `itemKey` is the item's key (`spec:AST-103` DEC-4). | | Behavior | One `
  • ` row rendered by `component:Item`, which receives every row prop. Inside a List the row takes the list's density, dividers, edge treatment, and marker; outside a List it uses Item's defaults and draws no marker. | | End-user impact | Each list entry reads as one list item, with the list's bullet, number, or task checkbox before it and the same interaction Item gives any row. | | Builder impact | The deprecated `swipeActions` and `swipeBehavior` move to `swipe={createSwipe(…)}` under `spec:AST-057` DEP-0017; its `astryx upgrade` codemod is an opt-in early migration from the deprecating release and runs again in 0.8.0's upgrade with CLN-0025's removal. | -| Compatibility/readiness | Records shipped behavior; no public change. Three implementation gaps, listed under Current-state impact. | +| Compatibility/readiness | Records shipped behavior; `itemKey` is additive. Two implementation gaps, listed under Current-state impact. | | Review checks | Reject a row that is not an `
  • `, a ListItem-level edge, density, or divider prop, a marker drawn outside a marked List, or a dropped Item prop. | | Governing rules | `component:Item` (`align` for start and end content); `component:List`; `family:navigation-destinations`; `spec:AST-057`; `spec:AST-103`; `architecture:component-theming-surface`; `architecture:component-style-authoring` INV7. | @@ -73,9 +74,6 @@ Consumer migration instructions belong in consumer docs and release notes. pseudo-element, beside the row's content. `architecture:component-style-authoring` INV7 carries decoration with no semantic role on a pseudo-element rather than an added element. -- **ListItem has no `itemKey` yet.** `spec:AST-103` DEC-4 and `component:List` - FR12 have each reorderable row name its item through an `itemKey` prop; - ListItem does not accept one yet. - **ListItem has no `swipe` yet.** `spec:AST-057` FR1 has ListItem pass `swipe` through to `Item`, which replaces the deprecated `swipeActions` and `swipeBehavior` (`spec:AST-057` DEP-0017); `swipe` is not built, so diff --git a/packages/core/api-report.md b/packages/core/api-report.md index dfebb429057af..719d88b8cb9a9 100644 --- a/packages/core/api-report.md +++ b/packages/core/api-report.md @@ -1504,6 +1504,7 @@ component LinkProvider(props: LinkProviderProps) prop children: ReactNode prop component: LinkComponentType component List(props: ListProps) + prop animatedLayout?: AnimatedLayout prop children: ReactNode prop data-testid?: string prop density?: ListDensity = 'balanced' @@ -1524,6 +1525,7 @@ component ListItem(props: ListItemProps) prop interactiveRef?: React.RefObject prop isDisabled?: boolean = false prop isSelected?: boolean = false + prop itemKey?: string | number prop label: ReactNode prop onClick?: (e: React.MouseEvent) => void prop ref?: React.Ref diff --git a/packages/core/src/List/List.doc.mjs b/packages/core/src/List/List.doc.mjs index dd41c8fce154e..70075ff3fcd19 100644 --- a/packages/core/src/List/List.doc.mjs +++ b/packages/core/src/List/List.doc.mjs @@ -50,6 +50,11 @@ export const docs = { description: 'Show dividers between items.', default: 'false', }, + { + name: 'animatedLayout', + type: 'AnimatedLayout', + description: 'The handle from useAnimatedLayout({containerRef}). With it, when rows are inserted, removed or reordered, an inserted row enters, a removed row collapses in place, a row that crosses rows moving the other way rides above them with the surface color behind it, and the rows after a change and the content after the list, up to that container, glide to their new places, all on one shared motion, under every pointer. Under Reduce Motion nothing travels. A row is identified by its itemKey: a row without one changes at once. Without a handle the list changes at once.', + }, { name: 'edge', type: "'padded' | 'flush' | 'outset' | 'bleed'", diff --git a/packages/core/src/List/List.test.tsx b/packages/core/src/List/List.test.tsx index 0cbcdbaf9af67..8568cfa85a68e 100644 --- a/packages/core/src/List/List.test.tsx +++ b/packages/core/src/List/List.test.tsx @@ -54,6 +54,7 @@ import {List} from './List'; import {ListItem} from './ListItem'; import {ListMarkerScope} from './ListContext'; import {HIT_INSET_PROPERTIES} from '../utils/hitArea'; +import {useAnimatedLayout} from '../hooks/useAnimatedLayout'; describe('List', () => { it('forwards ListItem align to its Item row unchanged', () => { @@ -1159,6 +1160,23 @@ describe('List and swipe actions', () => { expect(other.filter(rule => rule.includes('isolation'))).toEqual([]); }); + it('isolates for every pointer under an animatedLayout handle, since a sliding row rides above its neighbors with a mouse too', () => { + function Animated() { + const containerRef = useRef(null); + const animatedLayout = useAnimatedLayout({containerRef}); + return ( +
    + + {}} /> + +
    + ); + } + render(); + const {other} = touchGatedRules(screen.getByRole('list')); + expect(other.join('\n')).toMatch(/isolation: isolate/); + }); + it('under a finger, raises a swipeable interactive row above the rows after it: it is a stacking context, so its touch band’s own z-index orders only inside it', () => { render( @@ -1193,8 +1211,13 @@ describe('List and swipe actions', () => { }; const swipeable = rowZ(row('Swipeable')); expect(swipeable.touch.join('\n')).toMatch(/z-index: 1/); - // With a mouse there is no band, and nothing changes. - expect(swipeable.other).toEqual([]); + // With a mouse there is no band: the row's only z-index is an update's + // travelling raise, while it slides across other rows. + for (const rule of swipeable.other) { + expect(rule.slice(0, rule.indexOf('{'))).toContain( + '[data-astryx-travelling]', + ); + } // A row that is no stacking context needs no raise (its band's own // z-index orders it), and a swipeable row with no band gets none. expect(rowZ(row('Pressable')).touch).toEqual([]); diff --git a/packages/core/src/List/List.tsx b/packages/core/src/List/List.tsx index 359d8738c2fb3..68c4ffebff1bd 100644 --- a/packages/core/src/List/List.tsx +++ b/packages/core/src/List/List.tsx @@ -19,7 +19,7 @@ * - /packages/cli/assets/templates/blocks/components/List/ (showcase blocks) */ -import {useId, useMemo, type ReactNode} from 'react'; +import {useId, useMemo, useRef, type ReactNode} from 'react'; import * as stylex from '@stylexjs/stylex'; import {spacingVars} from '../theme/tokens.stylex'; import type {BaseProps} from '../BaseProps'; @@ -30,6 +30,10 @@ import { type ListMarkerStyle, } from './ListContext'; import {mergeProps} from '../utils/mergeProps'; +import {useMergedRefs} from '../hooks/useMergedRefs'; +import {useListLayoutUpdates} from './listLayoutUpdates'; +import {LayoutChangeSnapshot} from '../motion/LayoutChangeSnapshot'; +import type {AnimatedLayout} from '../motion/animatedLayout'; import {themeProps} from '../utils/themeProps'; import {useDevWarning} from '../hooks/useDevWarning'; @@ -58,6 +62,17 @@ export interface ListProps extends BaseProps< */ density?: ListDensity; + /** + * The handle from `useAnimatedLayout({containerRef})`. With it, the list + * animates its row changes on one shared motion, under every pointer. An + * inserted row enters, and a removed row collapses in place. A row that + * crosses rows moving the other way rides above them. The rows after a + * change, and the content after the list up to that container, glide to + * their new places. A row's identity is its `itemKey`, so a row without one + * changes at once. Without a handle the list changes at once. + */ + animatedLayout?: AnimatedLayout; + /** * Whether to show dividers between list items. * @default false @@ -154,6 +169,12 @@ const styles = stylex.create({ // mouse nothing rises, so the list keeps its stacking. isolation: {default: null, '@media (pointer: coarse)': 'isolate'}, }, + // A list under an `animatedLayout` handle isolates for every pointer. A row + // that slides across others rides above them with a mouse too, and it must + // stay below a page-level sticky header. + animatedIsolation: { + isolation: 'isolate', + }, // Subgridded numbered rows contribute their marker's intrinsic width to // one column, so text and nested lists never move with an individual number. numberColumns: { @@ -225,6 +246,7 @@ const dynamicStyles = stylex.create({ */ export function List({ children, + animatedLayout, density = 'balanced', hasDividers = false, edge: edgeProp, @@ -240,6 +262,12 @@ export function List({ ...props }: ListProps) { const headerId = useId(); + const listRef = useRef(null); + const measureRows = useListLayoutUpdates(listRef, animatedLayout); + const mergedRef = useMergedRefs( + listRef, + ref as React.Ref, + ); const isOrdered = listStyle === 'decimal'; const Tag = isOrdered ? 'ol' : 'ul'; // Plain use of the deprecated prop is reported by its @deprecated type; @@ -255,13 +283,19 @@ export function List({ const reachesContainerPadding = edge === 'outset' || edge === 'bleed'; const contextValue = useMemo( - () => ({density, hasDividers, edge, listStyle}), - [density, hasDividers, edge, listStyle], + () => ({ + density, + hasDividers, + edge, + listStyle, + animatedLayout, + }), + [density, hasDividers, edge, listStyle, animatedLayout], ); const listElement = ( } + ref={mergedRef} // Consumer props first: everything the component sets for itself below // is part of its contract and wins on conflict. {...props} @@ -281,6 +315,7 @@ export function List({ themeProps('list', {density, listStyle}), stylex.props( styles.list, + animatedLayout != null && styles.animatedIsolation, isOrdered && styles.numberColumns, hasDividers && styles.withDividers, reachesContainerPadding && styles.reachesContainerPadding, @@ -297,12 +332,25 @@ export function List({ ); + // Every change of the rows is measured before it lands. LayoutChangeSnapshot + // calls this in the commit, before the DOM changes. + const snapshot = + animatedLayout != null ? ( + + ) : null; + if (header == null) { - return {listElement}; + return ( + + {snapshot} + {listElement} + + ); } return ( + {snapshot}
    {header} diff --git a/packages/core/src/List/ListContext.tsx b/packages/core/src/List/ListContext.tsx index f90cd1dfad705..8f32232e4c0b2 100644 --- a/packages/core/src/List/ListContext.tsx +++ b/packages/core/src/List/ListContext.tsx @@ -15,6 +15,7 @@ import {use, useMemo, type ReactNode} from 'react'; import {createLayerScopedContext as createContext} from '../Layer/layerScopedContext'; +import type {AnimatedLayout} from '../hooks/useAnimatedLayout'; export type ListDensity = 'compact' | 'balanced' | 'spacious'; export type ListMarkerStyle = 'none' | 'disc' | 'decimal' | 'circle'; @@ -63,6 +64,10 @@ export interface ListContextValue { * on their List, so its text starts match RichText without a width threshold. */ hasMarkerGutter?: boolean; + /** + * The list's `animatedLayout` handle, for its rows. + */ + animatedLayout?: AnimatedLayout; } export const ListContext = createContext(null); diff --git a/packages/core/src/List/ListItem.doc.mjs b/packages/core/src/List/ListItem.doc.mjs index 74b23fd4b92c6..52a2267180f55 100644 --- a/packages/core/src/List/ListItem.doc.mjs +++ b/packages/core/src/List/ListItem.doc.mjs @@ -107,6 +107,11 @@ export const docs = { description: 'Selected state; marks the item as the current one with aria-current="true" (a list item cannot carry aria-selected).', default: 'false', }, + { + name: 'itemKey', + type: 'string | number', + description: "The row's item key, a string or a number from the data (the shape Table's idKey returns). It is the row's identity for the list's animated layout (List animatedLayout): with a handle, the list matches rows by it to animate inserts, removals and moves, and a row without one changes at once. Separate from React's key.", + }, { name: 'swipeActions', type: '{leading?: ItemSwipeAction[]; trailing?: ItemSwipeAction[]}', @@ -199,6 +204,11 @@ export const docsZh = { description: '选中状态;在项目上设置 aria-current="true",将其标为当前项(列表项不能使用 aria-selected)。', default: 'false', }, + { + name: 'itemKey', + type: 'string | number', + description: '行的项目键,取自数据的字符串或数字(与 Table 的 idKey 返回的形状相同)。它是列表动画布局(List animatedLayout)中该行的身份:传入句柄时,列表按它匹配各行,为插入、删除和移动添加动画;没有项目键的行会立即变化。与 React 的 key 相互独立。', + }, { name: 'swipeActions', type: '{leading?: ItemSwipeAction[]; trailing?: ItemSwipeAction[]}', @@ -237,5 +247,6 @@ export const docsDense = { rel: 'Link relationship tokens. noopener noreferrer are merged for target="_blank".', isDisabled: 'Disabled state; sets aria-disabled.', isSelected: 'Selected state; sets aria-current="true".', + itemKey: "The row's identity for List animatedLayout; a row without one changes at once.", }, }; diff --git a/packages/core/src/List/ListItem.tsx b/packages/core/src/List/ListItem.tsx index 81b11413e95ba..3454bd6941806 100644 --- a/packages/core/src/List/ListItem.tsx +++ b/packages/core/src/List/ListItem.tsx @@ -6,9 +6,11 @@ * @file ListItem.tsx * @input Uses React, ReactNode, StyleXStyles, theme tokens and the List row * edge treatment. It also uses the touch hit area (utils/touchHitArea.ts and - * its layer) and CheckboxInput. It reads the marker or task checkbox a - * ListMarkerScope sets, for Markdown's nested lists and the task items of mixed - * lists. It also reads Item's private exact-marker formatting scope for numbered + * its layer), the travelling marker of an update's slide + * (List/listLayoutUpdates.ts) and CheckboxInput. It reads the marker or task + * checkbox a ListMarkerScope sets, for Markdown's nested lists and the task + * items of mixed lists. It also reads Item's private exact-marker formatting + * scope for numbered * rows. Number markers stay on one line in the List's shared column, * keeping every sibling's text and nested list on the same start line; * they end on one line too, right-aligned with tabular figures, and hang @@ -48,6 +50,9 @@ import {ItemMarkerColumnsContext} from '../Item/ItemMarkerColumnsContext'; import type {ItemAlign, ItemSwipeActions, ItemSwipeBehavior} from '../Item'; import {themeProps} from '../utils/themeProps'; import {useMergedRefs} from '../hooks/useMergedRefs'; +import {isReportedRow, keepPresentation} from './listLayoutUpdates'; +import {itemKeyProps} from '../privateAttributes/itemKey.stylex'; +import {travellingStyles} from '../privateAttributes/travelling.stylex'; import {useTouchHitArea} from '../utils/touchHitArea'; import {touchHitAreaStyles} from '../utils/touchHitArea.stylex'; @@ -140,6 +145,14 @@ export interface ListItemProps extends BaseProps { */ isSelected?: boolean; + /** + * The row's item key, a string or a number from the data, in the shape + * Table's `idKey` returns. It is the row's identity for the list's + * `animatedLayout`. A row without one changes at once. It is separate from + * React's `key`, which stays React's own. + */ + itemKey?: string | number; + /** * Swipe actions for touch, passed through to `Item` unchanged: the verbs a * sideways drag uncovers on each side. See `Item.swipeActions`; `List` @@ -211,13 +224,6 @@ const styles = stylex.create({ zIndex: {default: null, '@media (pointer: coarse)': 1}, }, }, - // A swipeable row is a stacking context at rest, since Item translates its - // swipe root. So its band's own z-index orders only inside it. Under a - // finger the row itself rises above the rows after it, whose boxes its band - // reaches into. The list isolates, so the row stays below a sticky header. - swipeRaised: { - zIndex: {default: null, '@media (pointer: coarse)': 1}, - }, withDivider: { borderBlockEndWidth: borderVars['--border-width'], borderBlockEndStyle: 'solid', @@ -373,6 +379,25 @@ const embeddedStyles = stylex.create({ // Component // ============================================================================= +/** + * The row's callback ref for the Web Animations on its parts, such as a + * swipe's travel on the compositor. A detached row loses them. So when React + * detaches a row in an animating list, the row records what they present. It + * is still in the document then, so a removal's collapse shows the row as it + * was on screen. Only a row its list reported for the commit can exit. So + * when StrictMode replays the detach of a new row, it records nothing. + */ +function keepPresentationOnDetach(row: HTMLLIElement | null) { + if (row == null) { + return undefined; + } + return () => { + if (isReportedRow(row)) { + keepPresentation(row); + } + }; +} + /** * A list item component for use within List. * @@ -399,6 +424,7 @@ export function ListItem({ rel, isDisabled = false, isSelected = false, + itemKey, align, xstyle, className, @@ -415,7 +441,7 @@ export function ListItem({ const isTouchTarget = (onClick != null || href != null || interactiveRef != null) && !isDisabled; const hitAreaRef = useTouchHitArea(isTouchTarget); - const mergedRef = useMergedRefs(ref, hitAreaRef); + const mergedRef = useMergedRefs(ref, hitAreaRef, keepPresentationOnDetach); // A row that Item serves swipe actions on is a stacking context at rest. So // its band's own z-index orders only inside it, and under a finger the row // raises itself. Its root is its `
  • `, never a link. @@ -502,11 +528,12 @@ export function ListItem({ [ listStyle === 'decimal' && styles.numberColumns, hasMarkers && styles.withCounter, + travellingStyles.row, hasDividers && styles.withDivider, hasDividers && embeddedStyles.noRadius, isTouchTarget && touchHitAreaStyles.layer, isTouchTarget && isInList && styles.bandRaised, - isRaisedSwipeRow && styles.swipeRaised, + isRaisedSwipeRow && travellingStyles.raisedSwipeRow, edge === 'flush' && styles.edgeFlush, edge === 'outset' && styles.edgeOutset, edge === 'bleed' && styles.edgeBleed, @@ -514,6 +541,7 @@ export function ListItem({ ] as StyleXStyles } {...mergeProps(themeProps('list-item'), {className, style})} + {...itemKeyProps(itemKey)} {...restProps} /> ); diff --git a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts new file mode 100644 index 0000000000000..902820c79a522 --- /dev/null +++ b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts @@ -0,0 +1,812 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file ListUpdates.interaction.browser.spec.ts + * @input The built List "Animated Changes" stories, in the touch phone + * context and in a mouse context + * @output Browser proofs of a List's animated row updates. They cover a + * removal, an insert, a move, Reduce Motion, the last row's exit, no Layout + * or Paint per frame, and swiped rows. + * @position Interaction evidence for List/listLayoutUpdates.ts. The module's + * own proofs are motion/__tests__/animatedLayout*.browser.spec.ts. + * + * SYNC: When modified, update the Verification rows of + * /docs/specs/components/List/List.spec.md. + */ + +// The stories' List takes the handle that `useAnimatedLayout` returns for a +// container around it and the buttons after it. Each row has an `itemKey`. + +import { + expect, + test, + type Browser, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + countBetween, + openStory, + traceRendering, + withStorybook, +} from '@astryxdesign/interaction-harness'; + +const storybook = withStorybook(test); + +const STORY = 'core-list--animated-changes'; +const SWIPE_STORY = 'core-list--animated-changes-swipe'; + +/** A row of the list, never a row put back for its exit. */ +const row = (page: Page, label: string) => + page + .locator('#storybook-root li:not([data-astryx-leaving])') + .filter({hasText: label}) + .first(); + +/** The row put back for its exit, if any. */ +const leaving = (page: Page) => + page.locator('#storybook-root li[data-astryx-leaving]'); + +/** + * Records the keyframes of every script animation made from now on, however + * short: a reduced-motion cross-fade can end before a later read sees it. + */ +async function recordMadeAnimations( + page: Page, +): Promise<() => Promise[][]>> { + await page.evaluate(() => { + const w = window as unknown as { + __madeAnimations?: Record[][]; + }; + w.__madeAnimations = []; + const animate = Element.prototype.animate; + Element.prototype.animate = function ( + this: Element, + ...args: Parameters + ) { + const animation = animate.apply(this, args); + w.__madeAnimations?.push( + (animation.effect as KeyframeEffect) + .getKeyframes() + .map(frame => ({...frame})), + ); + return animation; + }; + }); + return async () => + page.evaluate( + () => + (window as unknown as {__madeAnimations: Record[][]}) + .__madeAnimations, + ); +} + +/** + * Every glide start (px, vertical) and clip running right now, by row label. + * A button reads as `button:` and its name, and a row put back for its exit + * as `leaving:` and its label. It reads all of them in one pass right after a + * change. The glides last under half a second, so reading them one by one + * would miss the later ones. + */ +async function snapshot( + page: Page, +): Promise<{glides: Record; clipped: string[]}> { + return page.evaluate(() => { + const nameOf = (el: Element) => { + const testId = el.getAttribute('data-testid'); + if (testId != null) { + return `testid:${testId}`; + } + if (el instanceof HTMLButtonElement) { + return `button:${el.textContent?.trim() ?? ''}`; + } + const copy = el.cloneNode(true) as Element; + for (const panel of copy.querySelectorAll('[data-swipe-panel]')) { + panel.remove(); + } + const label = copy.textContent?.trim() ?? ''; + return el.hasAttribute('data-astryx-leaving') + ? `leaving:${label}` + : label; + }; + const glides: Record = {}; + const clipped: string[] = []; + for (const animation of document.getAnimations()) { + const effect = animation.effect as KeyframeEffect; + const target = effect.target; + if (target == null) { + continue; + } + const frames = effect.getKeyframes(); + const first = frames[0]?.translate; + if (typeof first === 'string') { + const match = /^(-?[\d.e+-]+)px(?:\s+(-?[\d.e+-]+)px)?/.exec(first); + glides[nameOf(target)] = match == null ? 0 : Number(match[2] ?? 0); + } + if (frames.some(frame => frame.clipPath != null)) { + clipped.push(nameOf(target)); + } + } + return {glides, clipped}; + }); +} + +/** + * The start times of the animations on the list and its rows, in ms: the + * update's own, whatever drives them. An animation outside the list (a + * pressed button's release) is not part of the update. + */ +async function startTimes(page: Page): Promise { + return page.evaluate(() => { + const list = document.querySelector('#storybook-root ul'); + return document + .getAnimations() + .filter(animation => { + const target = (animation.effect as KeyframeEffect | null)?.target; + return list != null && target != null && list.contains(target); + }) + .map(animation => Number(animation.startTime)) + .filter(time => Number.isFinite(time)); + }); +} + +/** The distance between two consecutive rows' tops, in px. */ +async function rowGap(page: Page): Promise { + return page.evaluate(() => { + const rows = [...document.querySelectorAll('#storybook-root li')]; + return ( + rows[1].getBoundingClientRect().top - rows[0].getBoundingClientRect().top + ); + }); +} + +async function press(page: Page, name: string) { + await page.getByRole('button', {name}).click(); +} + +async function open(page: Page, story = STORY) { + await openStory(page, storybook(), story); + await expect(row(page, 'Inbox')).toBeVisible(); +} + +/** A context with a mouse and no touch, for the every-pointer cases. */ +async function withMouse( + browser: Browser, + run: (page: Page) => Promise, +): Promise { + const context = await browser.newContext({ + hasTouch: false, + isMobile: false, + viewport: {width: 900, height: 900}, + }); + const page = await context.newPage(); + try { + return await run(page); + } finally { + await context.close(); + } +} + +test('a removal: the removed row stays in place, inert and out of the accessibility tree, and conceals while the rows after it and the content after the list glide up from their old places', async ({ + page, +}) => { + await open(page); + const gap = await rowGap(page); + await press(page, 'Remove the second row'); + const {glides, clipped} = await snapshot(page); + // The rows after it, and the content after the list, start where they were. + // So do the buttons: the pressed one glides with its neighbors, never onto + // them. + for (const label of [ + 'Drafts', + 'Archive', + 'Spam', + 'testid:after-list', + 'button:Insert a row second', + 'button:Remove the second row', + 'button:Move the last row first', + ]) { + expect(glides[label], `${label} ${JSON.stringify(glides)}`).toBeCloseTo( + gap, + 0, + ); + } + expect(glides.Inbox).toBeUndefined(); + // It conceals on the same motion. + expect(clipped).toEqual(['leaving:Sent']); + // Back where it was for its exit: inert, hidden from assistive technology. + const exit = leaving(page); + await expect(exit).toHaveCount(1); + await expect(exit).toHaveAttribute('inert', ''); + await expect(exit).toHaveAttribute('aria-hidden', 'true'); + await expect( + page.getByRole('listitem').filter({hasText: 'Sent'}), + ).toHaveCount(0); + // Then it goes. + await expect(exit).toHaveCount(0, {timeout: 3000}); +}); + +test('an insert: the new row enters in the same frame the rows after it and the content after the list start gliding down', async ({ + page, +}) => { + await open(page); + const gap = await rowGap(page); + await press(page, 'Insert a row second'); + const {glides, clipped} = await snapshot(page); + const starts = await startTimes(page); + expect(clipped).toEqual(['Folder 1']); + expect(glides['Folder 1']).toBeUndefined(); + for (const label of [ + 'Sent', + 'Drafts', + 'Archive', + 'Spam', + 'testid:after-list', + 'button:Insert a row second', + 'button:Remove the second row', + 'button:Move the last row first', + ]) { + expect(glides[label], `${label} ${JSON.stringify(glides)}`).toBeCloseTo( + -gap, + 0, + ); + } + // One frame: the new row's entrance and the glides of the four rows after + // it started together. + expect(starts.length, JSON.stringify(starts)).toBe(5); + expect( + Math.max(...starts) - Math.min(...starts), + JSON.stringify(starts), + ).toBeLessThan(1); +}); + +test('a reorder: the row moved to the top glides up from its old place riding above the rows it crosses, and they glide down', async ({ + page, +}) => { + await open(page); + const gap = await rowGap(page); + await press(page, 'Move the last row first'); + const {glides} = await snapshot(page); + const spam = row(page, 'Spam'); + const travelling = await spam.evaluate(el => + el.hasAttribute('data-astryx-travelling'), + ); + expect(glides.Spam, JSON.stringify(glides)).toBeCloseTo(4 * gap, 0); + expect(travelling).toBe(true); + for (const label of ['Inbox', 'Sent', 'Drafts', 'Archive']) { + expect(glides[label], `${label} ${JSON.stringify(glides)}`).toBeCloseTo( + -gap, + 0, + ); + } + // The list's height did not change: nothing after it moves. Present + // first: the content after the list is on screen. + const afterList = page.getByTestId('after-list'); + await expect(afterList).toBeVisible(); + expect((await afterList.boundingBox())?.height ?? 0).toBeGreaterThan(0); + expect(glides['testid:after-list']).toBeUndefined(); + // It rides above them only while it glides. + await expect(spam).not.toHaveAttribute('data-astryx-travelling', /.*/, { + timeout: 3000, + }); +}); + +test('a mouse gets the same motion: a removal glides the rows after it (every pointer)', async ({ + browser, +}) => { + await withMouse(browser, async page => { + await open(page); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + const gap = await rowGap(page); + await press(page, 'Remove the second row'); + const {glides, clipped} = await snapshot(page); + expect(glides.Drafts, JSON.stringify(glides)).toBeCloseTo(gap, 0); + expect(clipped).toEqual(['leaving:Sent']); + }); +}); + +test('under Reduce Motion: a finger cross-fades with no travel, a mouse changes at once', async ({ + page, + browser, +}) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + await open(page); + // Present first: the row the removal takes, on screen. + await expect(row(page, 'Sent')).toBeVisible(); + const made = await recordMadeAnimations(page); + await press(page, 'Remove the second row'); + const {glides, clipped} = await snapshot(page); + expect(glides).toEqual({}); + expect(clipped).toEqual([]); + // Every animation the removal made, however short: at least one plays, a + // fade, and none of them travels. + const animations = await made(); + const summary = JSON.stringify(animations); + expect(animations.length, summary).toBeGreaterThan(0); + expect( + animations.some(frames => frames.some(frame => frame.opacity != null)), + summary, + ).toBe(true); + expect( + animations.every(frames => + frames.every(frame => frame.translate == null && frame.clipPath == null), + ), + summary, + ).toBe(true); + await withMouse(browser, async mouse => { + await mouse.emulateMedia({reducedMotion: 'reduce'}); + await open(mouse); + await expect(row(mouse, 'Sent')).toBeVisible(); + await press(mouse, 'Remove the second row'); + await expect(row(mouse, 'Sent')).toHaveCount(0); + await expect(leaving(mouse)).toHaveCount(0); + expect(await mouse.evaluate(() => document.getAnimations().length)).toBe(0); + }); +}); + +test('under Reduce Motion, an inserted row fades in where it lands under a finger, and lands at once with a mouse', async ({ + page, + browser, +}) => { + await page.emulateMedia({reducedMotion: 'reduce'}); + await open(page); + await press(page, 'Insert a row second'); + const fades = await page.evaluate(() => { + const inserted = [...document.querySelectorAll('#storybook-root li')].find( + li => li.textContent?.trim() === 'Folder 1', + ); + return (inserted?.getAnimations() ?? []).map(animation => { + const frames = (animation.effect as KeyframeEffect).getKeyframes(); + return { + from: Number(frames[0]?.opacity ?? 1), + to: Number(frames.at(-1)?.opacity ?? 1), + travels: frames.some( + frame => + frame.translate != null || + frame.transform != null || + frame.clipPath != null, + ), + }; + }); + }); + // The row's own fade, from transparent to opaque, with no travel. + expect(fades.length, JSON.stringify(fades)).toBeGreaterThan(0); + for (const fade of fades) { + expect(fade.travels, JSON.stringify(fades)).toBe(false); + expect(fade.from, JSON.stringify(fades)).toBeLessThan(1); + expect(fade.to, JSON.stringify(fades)).toBeCloseTo(1, 2); + } + await withMouse(browser, async mouse => { + await mouse.emulateMedia({reducedMotion: 'reduce'}); + await open(mouse); + await press(mouse, 'Insert a row second'); + await expect(row(mouse, 'Folder 1')).toBeVisible(); + expect(await mouse.evaluate(() => document.getAnimations().length)).toBe(0); + }); +}); + +test('removing the last row: its exit never paints over the content after the list', async ({ + page, +}) => { + await open(page); + // Removing the second row three times leaves the second row the last one. + for (let i = 0; i < 3; i++) { + await press(page, 'Remove the second row'); + await expect(leaving(page)).toHaveCount(0, {timeout: 3000}); + } + await press(page, 'Remove the second row'); + const samples = await page.evaluate(() => { + const animations = document.getAnimations(); + for (const animation of animations) { + animation.pause(); + } + const duration = Math.max( + ...animations.map(animation => + Number(animation.effect?.getComputedTiming().endTime ?? 0), + ), + ); + const exit = document.querySelector( + '#storybook-root li[data-astryx-leaving]', + ); + const after = document.querySelector('#storybook-root ul + *'); + if (exit == null || after == null) { + return { + duration, + rows: [] as {t: number; exit: number; exitTop: number; after: number}[], + }; + } + // The element a positioned or in-flow box is clipped by: its containing + // blocks, up the page. + const containingBlock = (node: Element): Element | null => { + const position = getComputedStyle(node).position; + if (position === 'fixed') { + return null; + } + let parent = node.parentElement; + if (position === 'absolute') { + while ( + parent != null && + getComputedStyle(parent).position === 'static' && + getComputedStyle(parent).transform === 'none' + ) { + parent = parent.parentElement; + } + } + return parent; + }; + // Where the exit's painted part ends: its box, less its clip-path inset, + // within the boxes that clip it. + const paintedBottom = (element: HTMLElement): number => { + const rect = element.getBoundingClientRect(); + let bottom = rect.bottom; + const inset = /^inset\(([^)]*)\)/.exec( + getComputedStyle(element).clipPath, + ); + if (inset != null) { + const parts = inset[1] + .replace(/round.*$/, '') + .trim() + .split(/\s+/); + const value = parts.length >= 3 ? parts[2] : parts[0]; + bottom -= value.endsWith('%') + ? (rect.height * Number.parseFloat(value)) / 100 + : Number.parseFloat(value); + } + for ( + let block = containingBlock(element); + block != null && block !== document.body; + block = containingBlock(block) + ) { + if (getComputedStyle(block).overflowY !== 'visible') { + bottom = Math.min(bottom, block.getBoundingClientRect().bottom); + } + } + return bottom; + }; + const rows = [0, 0.1, 0.25, 0.5, 0.75, 0.95].map(fraction => { + const t = duration * fraction; + for (const animation of animations) { + animation.currentTime = t; + } + return { + t, + exit: paintedBottom(exit), + exitTop: exit.getBoundingClientRect().top, + after: after.getBoundingClientRect().top, + }; + }); + for (const animation of animations) { + animation.play(); + } + return {duration, rows}; + }); + expect(samples.rows.length, JSON.stringify(samples)).toBe(6); + // Present first: an exit plays, and it starts on screen, painted. + expect(samples.duration, JSON.stringify(samples)).toBeGreaterThan(0); + expect( + samples.rows[0].exit - samples.rows[0].exitTop, + JSON.stringify(samples), + ).toBeGreaterThan(1); + for (const sample of samples.rows) { + expect(sample.exit, JSON.stringify(samples)).toBeLessThanOrEqual( + sample.after + 1, + ); + } + await expect(leaving(page)).toHaveCount(0, {timeout: 3000}); +}); + +for (const [change, button] of [ + ['an insert', 'Insert a row second'], + ['a removal', 'Remove the second row'], + ['a reorder', 'Move the last row first'], +] as const) { + test(`${change}: the motion does no Layout or Paint per frame`, async ({ + page, + browserName, + }) => { + test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only'); + await open(page); + let window = {from: 0, to: 0}; + const trace = await traceRendering(page, async () => { + await press(page, button); + const starts = await startTimes(page); + const durations = await page.evaluate(() => + document + .getAnimations() + .map(animation => Number(animation.effect?.getTiming().duration)), + ); + const from = Math.min(...starts); + window = {from, to: from + Math.max(...durations)}; + await page.waitForTimeout(Math.max(...durations) + 100); + }); + const during = countBetween(trace, window.from + 30, window.to - 30); + expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0); + expect(during.Paint ?? 0, JSON.stringify(during)).toBe(0); + }); +} + +/** + * Presses one of the swipe story's move buttons and freezes the motion + * halfway. Then it reports which row the browser hit-tests where the moved + * row overlaps a row it crosses. + */ +async function crossingHit(page: Page, button: string) { + await press(page, button); + return page.evaluate(() => { + const list = document.querySelector('#storybook-root ul'); + for (const animation of document.getAnimations()) { + const target = (animation.effect as KeyframeEffect | null)?.target; + if (list != null && target != null && list.contains(target)) { + animation.pause(); + animation.currentTime = + Number(animation.effect?.getComputedTiming().duration) / 2; + } + } + const label = (row: Element | null | undefined) => { + if (row == null) { + return null; + } + const copy = row.cloneNode(true) as Element; + for (const panel of copy.querySelectorAll('[data-swipe-panel]')) { + panel.remove(); + } + return copy.textContent?.trim() ?? ''; + }; + const rows = [...document.querySelectorAll('#storybook-root li')]; + const moved = rows.find(row => row.hasAttribute('data-astryx-travelling')); + if (moved == null) { + return null; + } + const m = moved.getBoundingClientRect(); + const crossed = rows.find(row => { + const r = row.getBoundingClientRect(); + return row !== moved && r.top < m.bottom - 4 && r.bottom > m.top + 4; + }); + if (crossed == null) { + return {moved: label(moved), crossed: null, hit: null}; + } + const c = crossed.getBoundingClientRect(); + const y = (Math.max(m.top, c.top) + Math.min(m.bottom, c.bottom)) / 2; + const hit = document.elementFromPoint(m.left + 40, y)?.closest('li'); + return {moved: label(moved), crossed: label(crossed), hit: label(hit)}; + }); +} + +test('a reorder among swipeable rows: the moved row rides above the rows it crosses, under a finger and with a mouse', async ({ + page, + browser, +}) => { + await open(page, SWIPE_STORY); + const touch = await crossingHit(page, 'Move Archive first'); + expect(touch?.moved, JSON.stringify(touch)).toBe('Archive'); + expect(touch?.crossed, JSON.stringify(touch)).not.toBeNull(); + expect(touch?.hit, JSON.stringify(touch)).toBe('Archive'); + const mouse = await withMouse(browser, async mousePage => { + await open(mousePage, SWIPE_STORY); + return crossingHit(mousePage, 'Move Archive first'); + }); + expect(mouse?.crossed, JSON.stringify(mouse)).not.toBeNull(); + expect(mouse?.hit, JSON.stringify(mouse)).toBe('Archive'); +}); + +test('a row without swipe actions, moved across swipeable rows, rides above them, under a finger and with a mouse', async ({ + page, + browser, +}) => { + await open(page, SWIPE_STORY); + // Notes has no swipe actions; the rows it crosses do, and under a finger + // each of them is raised. + await expect(row(page, 'Notes')).toBeVisible(); + await expect(row(page, 'Notes').locator('[data-swipe-panel]')).toHaveCount(0); + const touch = await crossingHit(page, 'Move Notes first'); + expect(touch?.moved, JSON.stringify(touch)).toBe('Notes'); + expect(touch?.crossed, JSON.stringify(touch)).not.toBeNull(); + expect(touch?.hit, JSON.stringify(touch)).toBe('Notes'); + const mouse = await withMouse(browser, async mousePage => { + await open(mousePage, SWIPE_STORY); + return crossingHit(mousePage, 'Move Notes first'); + }); + expect(mouse?.crossed, JSON.stringify(mouse)).not.toBeNull(); + expect(mouse?.hit, JSON.stringify(mouse)).toBe('Notes'); +}); + +test('a row swiped away with a removal action exits in place as it was on screen, as itself with no element added, while the rows after it glide up', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'the swipe is driven with Chromium touch events (CDP)', + ); + await open(page, SWIPE_STORY); + const sent = row(page, 'Sent'); + await expect(sent).toBeVisible(); + const gap = await rowGap(page); + const box = await sent.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + // From the frame where Sent is put back for its exit, record what exits and + // where its content and its action show. Also record where Drafts starts + // its glide. + await page.evaluate(() => { + const samples: { + offset: number; + glide: number | null; + nested: boolean; + added: number; + rowLeft: number; + panelRight: number | null; + }[] = []; + (window as unknown as {__samples: typeof samples}).__samples = samples; + const tick = () => { + const exit = document.querySelector( + '#storybook-root li[data-astryx-leaving]', + ); + if (exit != null && samples.length === 0) { + const drafts = [ + ...document.querySelectorAll('#storybook-root li'), + ].find( + li => + !li.hasAttribute('data-astryx-leaving') && + li.textContent?.includes('Drafts'), + ); + let glide: number | null = null; + for (const animation of drafts?.getAnimations() ?? []) { + const first = (animation.effect as KeyframeEffect).getKeyframes()[0] + ?.translate; + if (typeof first === 'string') { + glide = Number(first.split(' ')[1]?.replace('px', '') ?? 0); + } + } + // What exits is the row itself: no row nested in another element the + // list made, and nothing beside the rows but it. + const list = exit.parentElement; + const content = exit.querySelector( + ':scope > :not([data-swipe-panel])', + ); + const panel = exit.querySelector( + '[data-swipe-panel="trailing"]', + ); + samples.push({ + // Where its content shows against its own box: carried away by the + // swipe. + offset: + (content?.getBoundingClientRect().left ?? 0) - + exit.getBoundingClientRect().left, + glide, + nested: exit.querySelector('li') != null, + added: [...(list?.children ?? [])].filter( + child => child.tagName !== 'LI', + ).length, + rowLeft: exit.getBoundingClientRect().left, + panelRight: panel?.getBoundingClientRect().right ?? null, + }); + return; + } + requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); + }); + await expect(sent.locator('[data-swipe-panel="trailing"]')).toBeAttached(); + const cdp = await page.context().newCDPSession(page); + const y = box.y + box.height / 2; + const startX = box.x + box.width - 24; + const finger = async (x: number, type: 'touchStart' | 'touchMove') => + cdp.send('Input.dispatchTouchEvent', {touchPoints: [{x, y}], type}); + await finger(startX, 'touchStart'); + for (const fraction of [0.02, 0.05, 0.1, 0.2, 0.35, 0.5, 0.65, 0.8, 0.9]) { + await finger(startX - box.width * fraction, 'touchMove'); + await page.waitForTimeout(40); + } + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [], + type: 'touchEnd', + }); + await expect + .poll(async () => + page.evaluate( + () => (window as unknown as {__samples: unknown[]}).__samples.length, + ), + ) + .toBe(1); + const [sample] = await page.evaluate( + () => + ( + window as unknown as { + __samples: { + offset: number; + glide: number | null; + nested: boolean; + added: number; + rowLeft: number; + panelRight: number | null; + }[]; + } + ).__samples, + ); + // The row itself exits, at its own place: no element added for it. + expect(sample.nested, JSON.stringify(sample)).toBe(false); + expect(sample.added, JSON.stringify(sample)).toBe(0); + expect(sample.rowLeft, JSON.stringify(sample)).toBeCloseTo(box.x, 0); + // It still shows swiped toward the inline start, its action out in its + // place. + expect(sample.offset, JSON.stringify(sample)).toBeLessThan(-box.width / 4); + expect( + sample.panelRight ?? -1e3, + JSON.stringify(sample), + ).toBeGreaterThanOrEqual(box.x + box.width - 2); + // Drafts starts where it was. + expect(sample.glide ?? 0, JSON.stringify(sample)).toBeCloseTo(gap, 0); + await expect(leaving(page)).toHaveCount(0, {timeout: 3000}); +}); + +test('a row a swipe left open, still moving when another row is swiped away, is left as the swipe moves it: the list leaves no transform on it', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'the swipe is driven with Chromium touch events (CDP)', + ); + await open(page, SWIPE_STORY); + const sent = row(page, 'Sent'); + const drafts = row(page, 'Drafts'); + await expect(sent.locator('[data-swipe-panel="trailing"]')).toBeAttached(); + await expect(drafts.locator('[data-swipe-panel="trailing"]')).toBeAttached(); + const cdp = await page.context().newCDPSession(page); + const swipe = async (target: typeof sent, fractions: number[]) => { + const box = await target.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + const y = box.y + box.height / 2; + const startX = box.x + box.width - 24; + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [{x: startX, y}], + type: 'touchStart', + }); + for (const fraction of fractions) { + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [{x: startX - box.width * fraction, y}], + type: 'touchMove', + }); + await page.waitForTimeout(40); + } + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [], + type: 'touchEnd', + }); + }; + // Sent's actions open part of the way; the next swipe closes them, so + // Sent is still translated as Drafts leaves. + await swipe(sent, [0.02, 0.05, 0.1, 0.15, 0.2, 0.25]); + await expect + .poll(async () => + sent.evaluate(el => new DOMMatrix(getComputedStyle(el).transform).m41), + ) + .toBeLessThan(-20); + await swipe(drafts, [0.02, 0.05, 0.1, 0.2, 0.35, 0.5, 0.65, 0.8, 0.9]); + await expect(row(page, 'Drafts')).toHaveCount(0, {timeout: 5000}); + await expect(leaving(page)).toHaveCount(0, {timeout: 3000}); + await expect + .poll(async () => + sent.evaluate(el => el.getAnimations({subtree: true}).length), + ) + .toBe(0); + // Sent rests where its swipe leaves it (open or closed), and its content + // carries no transform the list wrote while Drafts left. + const after = await sent.evaluate(el => { + const content = el.querySelector( + ':scope > :not([data-swipe-panel])', + ); + return { + own: new DOMMatrix(getComputedStyle(el).transform).m41, + inline: content?.style.transform ?? null, + computed: content == null ? null : getComputedStyle(content).transform, + }; + }); + expect(after.inline, JSON.stringify(after)).toBe(''); + expect(after.computed, JSON.stringify(after)).toBe('none'); +}); diff --git a/packages/core/src/List/listLayoutUpdates.test.tsx b/packages/core/src/List/listLayoutUpdates.test.tsx new file mode 100644 index 0000000000000..5a301f3124258 --- /dev/null +++ b/packages/core/src/List/listLayoutUpdates.test.tsx @@ -0,0 +1,632 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file listLayoutUpdates.test.tsx + * @input vitest, List and ListItem, `useAnimatedLayout`, a stubbed layout + * (each row 40 px tall in DOM order) and a recording `Element.animate` + * @output Unit proofs for List's row updates through its `animatedLayout` + * handle. They cover what glides and how far, which row enters, which row + * comes back for its exit, and when the list changes at once. + * @position Unit tests for List/listLayoutUpdates.ts. The motion itself is + * proven in List/__tests__/ListUpdates.interaction.browser.spec.ts. + */ + +import {StrictMode, use, useRef, useState} from 'react'; +import {act, render} from '@testing-library/react'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {List} from './List'; +import {ListItem} from './ListItem'; +import {useAnimatedLayout} from '../hooks/useAnimatedLayout'; +import {ListContext} from './ListContext'; + +interface Played { + readonly element: Element; + readonly keyframes: Keyframe[]; + readonly animation: Animation; +} + +let played: Played[] = []; +const originalAnimate = Element.prototype.animate; +const originalRect = Element.prototype.getBoundingClientRect; +const originalGetAnimations = Element.prototype.getAnimations; +const offsetHeight = Object.getOwnPropertyDescriptor( + HTMLElement.prototype, + 'offsetHeight', +); + +const ROW = 40; + +/** + * A layout where each row is 40 px tall, in the list's current DOM order. A + * row with a negative end margin, an exit giving up its space, keeps its + * place but takes none. + */ +function rectOf(element: Element): DOMRect { + if (element.id === 'area') { + return new DOMRect(0, 0, 400, 600); + } + const list = document.querySelector('ul'); + if (list == null) { + return new DOMRect(0, 0, 0, 0); + } + const takes = (row: Element) => { + const {style} = row as HTMLElement; + return style.position === 'absolute' || style.marginBlockEnd.startsWith('-') + ? 0 + : ROW; + }; + if (element.parentElement === list) { + // The rows before it, summed without copying the list (the linear-work + // case below counts copies). + let top = 0; + for ( + let row = list.firstElementChild; + row != null && row !== element; + row = row.nextElementSibling + ) { + top += takes(row); + } + return new DOMRect(0, top, 400, ROW); + } + if (element !== list && element.id !== 'after') { + return new DOMRect(0, 0, 0, 0); + } + let height = 0; + for ( + let row = list.firstElementChild; + row != null; + row = row.nextElementSibling + ) { + height += takes(row); + } + return element === list + ? new DOMRect(0, 0, 400, height) + : new DOMRect(0, height, 400, ROW); +} + +beforeEach(() => { + played = []; + Element.prototype.animate = function ( + this: Element, + keyframes: Keyframe[] | PropertyIndexedKeyframes | null, + ) { + const animation = { + cancel: () => undefined, + addEventListener: () => undefined, + finished: new Promise(() => undefined), + currentTime: 0, + } as unknown as Animation; + played.push({element: this, keyframes: keyframes as Keyframe[], animation}); + return animation; + }; + Element.prototype.getBoundingClientRect = function (this: Element) { + return rectOf(this); + }; + // The animations played on an element, still running (they never finish + // here). + Element.prototype.getAnimations = function (this: Element) { + return played + .filter(entry => entry.element === this) + .map(entry => entry.animation); + }; + Object.defineProperty(HTMLElement.prototype, 'offsetHeight', { + configurable: true, + get(this: HTMLElement) { + return this.parentElement?.tagName === 'UL' ? ROW : 0; + }, + }); +}); + +afterEach(() => { + Element.prototype.animate = originalAnimate; + Element.prototype.getBoundingClientRect = originalRect; + Element.prototype.getAnimations = originalGetAnimations; + if (offsetHeight != null) { + Object.defineProperty(HTMLElement.prototype, 'offsetHeight', offsetHeight); + } + vi.restoreAllMocks(); +}); + +const flushMicrotasks = async () => { + await act(async () => { + await Promise.resolve(); + await Promise.resolve(); + }); +}; + +/** The vertical start of each glide played, by the row's text or id. */ +function glides(): Map { + const out = new Map(); + for (const entry of played) { + const first = String(entry.keyframes[0]?.translate ?? ''); + const match = /^(-?[\d.e+-]+)px\s+(-?[\d.e+-]+)px/.exec(first); + if (match == null) { + continue; + } + const element = entry.element as HTMLElement; + out.set( + element.id !== '' ? element.id : (element.textContent ?? '').trim(), + Math.round(Number(match[2])), + ); + } + return out; +} + +/** The rows that played an entrance (a reveal), by their text. */ +function entrances(): string[] { + return played + .filter(entry => entry.keyframes[0]?.clipPath != null) + .map(entry => (entry.element.textContent ?? '').trim()); +} + +let setRows: (rows: string[]) => void = () => undefined; + +function Demo({ + initial, + withHandle = true, + keyed = true, + listStyle, +}: { + initial: string[]; + withHandle?: boolean; + keyed?: boolean; + listStyle?: React.CSSProperties; +}) { + const containerRef = useRef(null); + const animatedLayout = useAnimatedLayout({containerRef}); + const [rows, set] = useState(initial); + setRows = set; + return ( +
    + + {rows.map(label => ( + + ))} + +
    After
    +
    + ); +} + +/** Keyed rows, then one row without an itemKey. */ +function Mixed({initial}: {initial: string[]}) { + const containerRef = useRef(null); + const animatedLayout = useAnimatedLayout({containerRef}); + const [rows, set] = useState(initial); + setRows = set; + return ( +
    + + {rows.map(label => ( + + ))} + + +
    + ); +} + +async function change(rows: string[]) { + act(() => setRows(rows)); + await flushMicrotasks(); +} + +describe('List row updates through animatedLayout', () => { + it('inserting a row at the top: the old first row and every row after it glide down from their old places, the content after the list too, and the new row enters', async () => { + render(); + await change(['New', 'Inbox', 'Sent', 'Drafts']); + const moved = glides(); + expect(moved.get('Inbox')).toBe(-ROW); + expect(moved.get('Sent')).toBe(-ROW); + expect(moved.get('Drafts')).toBe(-ROW); + expect(moved.get('after')).toBe(-ROW); + expect(moved.has('New')).toBe(false); + expect(entrances()).toEqual(['New']); + }); + + it('moving the last row first: it glides up from its old place riding above the rows it crosses, and they glide down', async () => { + render(); + await change(['Drafts', 'Inbox', 'Sent']); + const moved = glides(); + expect(moved.get('Drafts')).toBe(2 * ROW); + expect(moved.get('Inbox')).toBe(-ROW); + expect(moved.get('Sent')).toBe(-ROW); + // Nothing after the list moved: its height is the same. + expect(moved.has('after')).toBe(false); + const drafts = [...document.querySelectorAll('li')].find( + row => row.textContent?.trim() === 'Drafts', + ); + expect(drafts).toHaveAttribute('data-astryx-travelling'); + expect(entrances()).toEqual([]); + }); + + it('moving the first row last: it glides down from its old place riding above the rows it crosses, and they glide up', async () => { + render(); + await change(['Sent', 'Drafts', 'Spam', 'Archive', 'Inbox']); + const moved = glides(); + expect(moved.get('Inbox')).toBe(-4 * ROW); + for (const label of ['Sent', 'Drafts', 'Spam', 'Archive']) { + expect(moved.get(label)).toBe(ROW); + } + const raised = [...document.querySelectorAll('li')] + .filter(row => row.hasAttribute('data-astryx-travelling')) + .map(row => row.textContent?.trim()); + expect(raised).toEqual(['Inbox']); + }); + + it('under StrictMode, an inserted row keeps nothing inline when React replays its cleanup, so it shows once its entrance ends', async () => { + const animate = Element.prototype.animate; + // As in a browser, an animation's commitStyles writes what it shows + // inline: here, its first keyframe. + Element.prototype.animate = function ( + this: Element, + keyframes: Keyframe[] | PropertyIndexedKeyframes | null, + options?: number | KeyframeAnimationOptions, + ) { + const animation = animate.call(this, keyframes, options); + const [first = {}] = (keyframes ?? []) as Keyframe[]; + animation.commitStyles = () => { + const {style} = this as HTMLElement; + if (first.opacity != null) { + style.opacity = String(first.opacity); + } + if (first.clipPath != null) { + style.clipPath = String(first.clipPath); + } + }; + return animation; + }; + render( + + + , + ); + await change(['Inbox', 'New', 'Sent']); + expect(entrances()).toEqual(['New']); + const added = [...document.querySelectorAll('li')].find( + row => row.textContent?.trim() === 'New', + ); + expect(added?.style.opacity).toBe(''); + expect(added?.style.clipPath).toBe(''); + }); + + it('a row whose ref changes while rows glide keeps nothing written: React detaches its old ref, but the row stays', async () => { + const animate = Element.prototype.animate; + // As in a browser, an animation's commitStyles writes what it shows + // inline: here, its first keyframe. + Element.prototype.animate = function ( + this: Element, + keyframes: Keyframe[] | PropertyIndexedKeyframes | null, + options?: number | KeyframeAnimationOptions, + ) { + const animation = animate.call(this, keyframes, options); + const [first = {}] = (keyframes ?? []) as Keyframe[]; + animation.commitStyles = () => { + const {style} = this as HTMLElement; + if (first.translate != null) { + style.setProperty('translate', String(first.translate)); + } + if (first.opacity != null) { + style.setProperty('opacity', String(first.opacity)); + } + if (first.clipPath != null) { + style.setProperty('clip-path', String(first.clipPath)); + } + }; + return animation; + }; + let rerender: () => void = () => undefined; + function WithRowRefs({initial}: {initial: string[]}) { + const containerRef = useRef(null); + const animatedLayout = useAnimatedLayout({containerRef}); + const [rows, set] = useState(initial); + const [, setTick] = useState(0); + setRows = set; + rerender = () => setTick(tick => tick + 1); + return ( +
    + + {rows.map(label => ( + // A callback ref written inline is a new ref on each render. + undefined} + /> + ))} + +
    + ); + } + render(); + await change(['Inbox', 'New', 'Sent', 'Drafts']); + // The rows after the insert glide, and the new row enters. + expect(glides().get('Sent')).toBe(-ROW); + expect(entrances()).toEqual(['New']); + // A re-render while they move, with the same rows. + act(() => rerender()); + await flushMicrotasks(); + for (const row of document.querySelectorAll('li')) { + const label = row.textContent?.trim() ?? ''; + expect(row.style.getPropertyValue('translate'), label).toBe(''); + expect(row.style.getPropertyValue('opacity'), label).toBe(''); + expect(row.style.getPropertyValue('clip-path'), label).toBe(''); + } + }); + + it('under StrictMode, a removed row still keeps what its parts showed for its exit', async () => { + // jsdom has no KeyframeEffect, which the module reads off a row's own + // animations. + vi.stubGlobal('KeyframeEffect', class {}); + const animate = Element.prototype.animate; + // As in a browser, an animation's commitStyles writes what it shows + // inline: here, its first keyframe. + Element.prototype.animate = function ( + this: Element, + keyframes: Keyframe[] | PropertyIndexedKeyframes | null, + options?: number | KeyframeAnimationOptions, + ) { + const animation = animate.call(this, keyframes, options); + const [first = {}] = (keyframes ?? []) as Keyframe[]; + animation.commitStyles = () => { + if (first.opacity != null) { + (this as HTMLElement).style.opacity = String(first.opacity); + } + }; + return animation; + }; + render( + + + , + ); + const rowOf = (label: string) => + [...document.querySelectorAll('li')].find( + row => row.textContent?.trim() === label, + ); + // The row runs an animation of its own, as a swipe's travel does. + rowOf('Sent')?.animate([{opacity: 0.5}, {opacity: 0.5}], 1000); + await change(['Inbox', 'Drafts']); + const leaving = rowOf('Sent'); + expect(leaving).toHaveAttribute('aria-hidden', 'true'); + expect(leaving?.style.opacity).toBe('0.5'); + vi.unstubAllGlobals(); + }); + + it('removing a row: it comes back where it was, inert and hidden from assistive technology, while the rows after it and the content after the list glide up into its place', async () => { + render(); + await change(['Inbox', 'Drafts']); + const leaving = [...document.querySelectorAll('li')].find( + row => row.textContent?.trim() === 'Sent', + ); + expect(leaving).toBeDefined(); + expect(leaving).toHaveAttribute('inert'); + expect(leaving).toHaveAttribute('aria-hidden', 'true'); + // It conceals on the shared motion. + expect( + played.some( + entry => entry.element === leaving && entry.keyframes[0]?.clipPath, + ), + ).toBe(true); + const moved = glides(); + expect(moved.get('Drafts')).toBe(ROW); + expect(moved.get('after')).toBe(ROW); + expect(moved.has('Inbox')).toBe(false); + }); + + it("keeps a caller's inline overflow-y, while a removal exits and after it", async () => { + render( + , + ); + const list = () => document.querySelector('ul') as HTMLElement; + expect(list().style.overflowY).toBe('auto'); + await change(['Inbox', 'Drafts']); + // The removed row's exit is under way. + expect(document.querySelector('li[data-astryx-leaving]')).not.toBeNull(); + expect(list().style.overflowY).toBe('auto'); + await change(['New', 'Inbox', 'Drafts']); + expect(list().style.overflowY).toBe('auto'); + }); + + it("puts the handle in List's context for its rows", () => { + let seen: unknown = 'unset'; + function Probe() { + seen = use(ListContext)?.animatedLayout; + return null; + } + let handle: unknown = null; + function WithHandle() { + const containerRef = useRef(null); + const animatedLayout = useAnimatedLayout({containerRef}); + handle = animatedLayout; + return ( +
    + + + +
    + ); + } + render(); + expect(handle).not.toBeNull(); + expect(seen).toBe(handle); + render( + + + , + ); + expect(seen).toBeUndefined(); + }); + + it('removing two adjacent rows: both come back in their places, in order', async () => { + render(); + await change(['Inbox', 'Archive']); + expect( + [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), + ).toEqual(['Inbox', 'Sent', 'Drafts', 'Archive']); + expect( + [...document.querySelectorAll('li[data-astryx-leaving]')].map(row => + row.textContent?.trim(), + ), + ).toEqual(['Sent', 'Drafts']); + }); + + it('measuring a change keeps no list of the later rows per row: linear work in the row count', async () => { + const labels = Array.from({length: 300}, (_, i) => `Row ${i}`); + render(); + // Copies of a 300-row list made while the change is measured and played. + const copies: number[] = []; + const slice = Array.prototype.slice; + const spy = vi.spyOn(Array.prototype, 'slice').mockImplementation(function ( + this: unknown[], + ...args + ) { + if (this.length === labels.length) { + copies.push(this.length); + } + return slice.apply(this, args); + }); + try { + await change(['New', ...labels]); + } finally { + spy.mockRestore(); + } + expect(copies.length).toBeLessThan(3); + }); + + describe('a long list (`architecture:react-component-runtime` INV12)', () => { + /** The places of rows read for one insert near the top of `length` rows. */ + async function rowReads(length: number): Promise { + const labels = Array.from({length}, (_, index) => `Row ${index}`); + const {unmount} = render(); + let reads = 0; + const stub = Element.prototype.getBoundingClientRect; + Element.prototype.getBoundingClientRect = function (this: Element) { + if (this.tagName === 'LI') { + reads += 1; + } + return stub.call(this); + }; + try { + await change([labels[0], 'New', ...labels.slice(1)]); + } finally { + Element.prototype.getBoundingClientRect = stub; + } + unmount(); + return reads; + } + + it('one update reads the places of the rows near the visible part only: as many for 300 rows as for 150', async () => { + const short = await rowReads(150); + const long = await rowReads(300); + expect(short).toBeLessThan(300); + expect(long - short).toBeLessThan(20); + }); + + it('the rows in view below an insert glide from their old places; a row far below does not move', async () => { + const labels = Array.from({length: 300}, (_, index) => `Row ${index}`); + render(); + await change([labels[0], 'New', ...labels.slice(1)]); + const moved = glides(); + expect(moved.get('Row 1')).toBe(-ROW); + expect(moved.get('Row 10')).toBe(-ROW); + expect(moved.has('Row 200')).toBe(false); + expect(entrances()).toEqual(['New']); + }); + + it('a removal near the top finds the rows that cross in one pass, not by comparing every moved row with every other', async () => { + const labels = Array.from({length: 300}, (_, index) => `Row ${index}`); + render(); + // Every check a predicate makes while the change is played. + let checks = 0; + const some = Array.prototype.some; + vi.spyOn(Array.prototype, 'some').mockImplementation(function ( + this: unknown[], + predicate, + thisArg, + ) { + return some.call( + this, + (...args): boolean => { + checks += 1; + return Boolean(predicate.apply(thisArg, args)); + }, + thisArg, + ); + }); + await change(labels.filter(label => label !== 'Row 1')); + vi.restoreAllMocks(); + expect(checks).toBeLessThan(labels.length); + }); + }); + + it('a re-render with the same rows in the same order plays nothing', async () => { + render(); + await change(['Inbox', 'Sent']); + // Present first: both rows, in their order. + expect( + [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), + ).toEqual(['Inbox', 'Sent']); + expect(played).toEqual([]); + }); + + it('without a handle, the list changes at once', async () => { + render(); + await change(['New', 'Inbox', 'Sent', 'Drafts']); + // Present first: the change happened, the new row first. + expect( + [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), + ).toEqual(['New', 'Inbox', 'Sent', 'Drafts']); + expect(played).toEqual([]); + }); + + it('a row without an itemKey changes at once: its insertion plays no entrance and reports nothing', async () => { + render(); + await change(['New', 'Inbox', 'Sent', 'Drafts']); + // Present first: the change happened, the new row first. + expect( + [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), + ).toEqual(['New', 'Inbox', 'Sent', 'Drafts']); + expect(played).toEqual([]); + }); + + it('adding the first row to an empty list: it enters, and the content after the list glides down', async () => { + render(); + await change(['First']); + // Present first: the row is in the list. + expect( + [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), + ).toEqual(['First']); + expect(entrances()).toEqual(['First']); + expect(glides().get('after')).toBe(-ROW); + }); + + it('adding the first keyed row beside a row without one: it enters', async () => { + render(); + await change(['First']); + expect( + [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), + ).toEqual(['First', 'Note']); + expect(entrances()).toEqual(['First']); + }); + + it('beside rows without one, a keyed row still enters and the rows after it glide', async () => { + render(); + await change(['Inbox', 'New', 'Sent']); + expect(entrances()).toEqual(['New']); + const moved = glides(); + // The unkeyed row after it is content like any other: it glides. + expect(moved.get('Sent')).toBe(-ROW); + expect(moved.get('Note')).toBe(-ROW); + }); +}); diff --git a/packages/core/src/List/listLayoutUpdates.ts b/packages/core/src/List/listLayoutUpdates.ts new file mode 100644 index 0000000000000..0af7f3933c1ed --- /dev/null +++ b/packages/core/src/List/listLayoutUpdates.ts @@ -0,0 +1,541 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file listLayoutUpdates.ts + * @input A List's element, its `animatedLayout` handle and the one + * size-change module (motion/animatedLayout.ts) + * @output `useListLayoutUpdates`, which reports each row inserted, removed or + * moved between two renders to the handle, and `keepPresentation`, for a + * row that leaves the list + * @position Internal. List calls it with its `animatedLayout` prop. + * + * SYNC: When modified, update List/List.tsx, List/ListItem.tsx and + * List/__tests__/ListUpdates.interaction.browser.spec.ts. + */ + +// - The module exits only rows it measured, so `measure` reports each row in +// view. It also reports the last row, so content after the list glides when +// no row is in view. +// - The module's walk reads rows only within its band around the visible +// part, so a long list's far rows are never read. With one row in view and +// the last row far from it, an insert above the last row moves it at once. +// - Of two rows that cross, the one with the longer glide rides above. The +// list's surface is behind it, as an opaque UIKit cell passes over its +// neighbors. +// - A row without an `itemKey` has no identity, so its own change lands at +// once. It still glides when a keyed row's change moves it. + +import {useCallback, useRef, type RefObject} from 'react'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +import { + holdLayoutExit, + playLayoutChange, + reportLayoutChange, + type AnimatedLayout, + type LayoutChange, +} from '../motion/animatedLayout'; +import {itemKeyOf} from '../privateAttributes/itemKey.stylex'; +import {isLeaving, markLeaving} from '../privateAttributes/leaving.stylex'; +import {markTravelling} from '../privateAttributes/travelling.stylex'; + +/** + * The rows each list reported for the commit in progress, the only rows that + * can exit. A row that leaves keeps what it showed on screen for its exit + * (`keepPresentation`) only when its list reported it. + */ +const reportedRows = new WeakMap>(); + +/** Whether `row`'s list reported it for the commit in progress. */ +export function isReportedRow(row: Element): boolean { + const list = row.parentElement; + return list != null && (reportedRows.get(list)?.has(row) ?? false); +} + +/** Moves under half a pixel are layout noise, not updates. */ +const MIN_MOVE_PX = 0.5; + +/** What `measure` saw, for the layout effect of the same commit. */ +interface Measured { + /** Every keyed row, by its key, in order. */ + readonly rows: ReadonlyMap; + readonly order: ReadonlyArray; + /** + * Where each row near the visible part was (its top), the indices from + * `near[0]` to `near[1]` of `order`: only those can glide in view. + */ + readonly tops: ReadonlyMap; + readonly near: readonly [number, number] | null; + /** The rows reported to the module, the only ones whose exit it holds. */ + readonly reported: ReadonlySet; + readonly changes: ReadonlyArray; + /** Rows whose translation moved onto their children for the commit. */ + readonly settled: ReadonlyArray; +} + +/** + * The first and last indices of `rows` whose box meets the vertical span from + * `start` to `end`, in viewport pixels, or null when none does. Rows sit in + * order down the list, so halving finds them by reading a few rows' places, + * never every row's. + */ +function rowsMeeting( + rows: ReadonlyArray, + start: number, + end: number, +): readonly [number, number] | null { + let low = 0; + let high = rows.length; + while (low < high) { + const middle = (low + high) >> 1; + if (rows[middle].getBoundingClientRect().bottom > start) { + high = middle; + } else { + low = middle + 1; + } + } + const first = low; + high = rows.length; + while (low < high) { + const middle = (low + high) >> 1; + if (rows[middle].getBoundingClientRect().top < end) { + low = middle + 1; + } else { + high = middle; + } + } + const last = low - 1; + return first <= last ? [first, last] : null; +} + +/** + * The list's rows that have an item key, by it, in order. A row without one + * has no identity to match across renders: its own insertion, removal or + * move is never reported, and changes at once. + */ +function keyedRows(list: HTMLElement): Map { + const rows = new Map(); + for (const child of list.children) { + if (!(child instanceof HTMLElement) || isLeaving(child)) { + continue; + } + const key = itemKeyOf(child); + if (key != null) { + rows.set(key, child); + } + } + return rows; +} + +/** + * The inline styles that a leaving row and its parts showed as they left, + * such as a swipe's travel. `keepPresentation` records them, and the row's + * exit writes them back. + */ +const keptStyles = new WeakMap< + HTMLElement, + ReadonlyArray +>(); + +/** + * Records what the Web Animations running on `row` and its parts present (a + * swipe's travel, on the compositor) as inline styles. A removed row is + * detached from the document, which drops those animations. Its exit puts it + * back and writes the record, so it shows what was on screen when it left. + * ListItem calls it as React detaches the row, while the row is still in the + * document. React also detaches the ref of a row that stays, when the ref + * changes. So nothing stays written. Animations on pseudo-elements, or that + * cannot write their values, are left alone. + */ +export function keepPresentation(row: HTMLElement): void { + if (typeof row.getAnimations !== 'function') { + return; + } + const parts = [row, ...row.querySelectorAll('*')]; + const before = parts.map(part => part.getAttribute('style')); + // commitStyles is the only way to read what an animation presents. It + // writes the values into the target's style, so each part gets its own + // style back once the values are read. + for (const animation of row.getAnimations({subtree: true})) { + try { + animation.commitStyles(); + } catch { + // A pseudo-element's or an unrendered target's animation: nothing to + // keep. + } + } + // The parts' owners clean up after the row does, and may reset its style. + // A swipe gives its row back its own translation. The record keeps it. + const styled: (readonly [HTMLElement | SVGElement, string])[] = []; + parts.forEach((part, index) => { + if (part.style.length > 0) { + styled.push([part, part.style.cssText]); + } + const style = before[index]; + if (part.getAttribute('style') !== style) { + if (style == null) { + part.removeAttribute('style'); + } else { + // Through the CSSOM, which a strict Content Security Policy allows. + part.style.cssText = style; + } + } + }); + keptStyles.set(row, styled); +} + +/** + * Puts a row that left back where it was for its exit, before `anchor`, the + * nearest later row in the list. It shows what it showed as it left. The + * exit makes it inert. Until then it is marked as leaving and hidden from + * assistive technology, so no later commit counts it as a row. + */ +function putBack( + element: HTMLElement, + list: HTMLElement, + anchor: HTMLElement | null, +): void { + markLeaving(element); + element.setAttribute('aria-hidden', 'true'); + list.insertBefore(element, anchor); + // Back in the document, its parts' animations would apply again over what + // they showed as it left: stop them, and show what was on screen. + if (typeof element.getAnimations === 'function') { + for (const animation of element.getAnimations({subtree: true})) { + animation.cancel(); + } + } + for (const [part, cssText] of keptStyles.get(element) ?? []) { + part.style.cssText = cssText; + } + keptStyles.delete(element); +} + +/** A row whose own translation moved onto its children, and what it replaced. */ +interface Settled { + readonly row: HTMLElement; + readonly prior: ReadonlyArray< + readonly [HTMLElement | SVGElement, string, string] + >; +} + +/** + * Moves a row's own translation, such as a swipe's, onto its children. So the + * row's box lies where the row lies in the list, while it shows the same + * thing. This runs for every translated row as a change is measured. After + * the commit it is undone for each row that stays. A row that leaves exits on + * its own box, in view. Its exit's clip keeps the action that the swipe + * uncovered and cuts the content that the swipe carried away. The box is the + * same before and after the commit, so nothing glides it. With the + * translation on the row, a row that a swipe carried out of the list's box + * would lie out of view. Its exit would then clip the action. Only a + * translation moves. Returns what to undo, or null when the row has no + * translation of its own. + */ +function settleTranslation(row: HTMLElement): Settled | null { + const view = row.ownerDocument.defaultView; + if (view == null || typeof view.DOMMatrix !== 'function') { + return null; + } + const transform = view.getComputedStyle(row).transform; + if (transform === '' || transform === 'none') { + return null; + } + const own = new view.DOMMatrix(transform); + if ( + !own.is2D || + own.a !== 1 || + own.b !== 0 || + own.c !== 0 || + own.d !== 1 || + (own.e === 0 && own.f === 0) + ) { + return null; + } + const children = [...row.children].filter( + (child): child is HTMLElement | SVGElement => + child instanceof view.HTMLElement || child instanceof view.SVGElement, + ); + // Every transform is read before any is written. A translation composes + // the same way whatever a child's transform origin. + const transforms = children.map( + child => view.getComputedStyle(child).transform, + ); + const prior = [row, ...children].map( + element => + [ + element, + element.style.getPropertyValue('transform'), + element.style.getPropertyPriority('transform'), + ] as const, + ); + row.style.setProperty('transform', 'none'); + children.forEach((child, index) => { + const current = transforms[index]; + const shift = new view.DOMMatrix().translate(own.e, own.f); + const moved = + current === '' || current === 'none' + ? shift + : shift.multiply(new view.DOMMatrix(current)); + child.style.setProperty('transform', moved.toString()); + }); + return {row, prior}; +} + +/** Puts back what `settleTranslation` replaced on a row that stays. */ +function unsettle({prior}: Settled): void { + for (const [element, value, priority] of prior) { + if (value === '') { + element.style.removeProperty('transform'); + } else { + element.style.setProperty('transform', value, priority); + } + } +} + +/** + * Marks each row that crosses another on the longer of the two glides, for + * the length of its glide, so it rides above. It reads the glides once the + * module has started them, after the commit's layout effects. One pass each + * way over the rows near the visible part, in their old order, finds the rows + * that cross any other. Only those are compared, so a removal or an insert, + * which crosses nothing, costs the two passes. + */ +function markCrossings( + measured: Measured, + now: ReadonlyMap, +): void { + const {near, order, tops} = measured; + if (near == null) { + return; + } + const rows: {element: HTMLElement; from: number; to: number}[] = []; + for (let index = near[0]; index <= near[1]; index++) { + const key = order[index]; + const from = tops.get(key); + const element = now.get(key); + if (from != null && element != null) { + rows.push({element, from, to: element.getBoundingClientRect().top}); + } + } + // A row crosses another when an earlier row ends below it, or a later row + // ends above it. + const crosses = rows.map(() => false); + let lowest = -Infinity; + for (let index = 0; index < rows.length; index++) { + crosses[index] = lowest > rows[index].to; + lowest = Math.max(lowest, rows[index].to); + } + let highest = Infinity; + for (let index = rows.length - 1; index >= 0; index--) { + crosses[index] ||= highest < rows[index].to; + highest = Math.min(highest, rows[index].to); + } + const crossing = rows.filter((_, index) => crosses[index]); + const raised = new Set(); + for (let a = 0; a < crossing.length; a++) { + for (let b = a + 1; b < crossing.length; b++) { + const upper = crossing[a]; + const lower = crossing[b]; + if (upper.to > lower.to) { + // On a tie, the row gliding up rides above. + const rider = + Math.abs(upper.to - upper.from) > Math.abs(lower.to - lower.from) + ? upper + : lower; + if (Math.abs(rider.to - rider.from) >= MIN_MOVE_PX) { + raised.add(rider.element); + } + } + } + } + const travelling = [...raised]; + if (travelling.length === 0) { + return; + } + const unmarks = travelling.map(element => markTravelling(element)); + // After the module's own microtask has started the glides. + queueMicrotask(() => { + travelling.forEach((element, index) => { + const end = unmarks[index]; + const glide = + typeof element.getAnimations === 'function' + ? element.getAnimations().at(-1) + : undefined; + if (glide == null) { + end(); + return; + } + glide.finished.then(end, end); + }); + }); +} + +/** + * Reports the list's row changes to `animatedLayout`. Returns the callback + * that measures them, which LayoutChangeSnapshot calls before each commit. + * Its layout effect plays them after the commit. + */ +export function useListLayoutUpdates( + listRef: RefObject, + animatedLayout: AnimatedLayout | undefined, +): () => void { + const measuredRef = useRef(null); + const measure = useCallback(() => { + measuredRef.current = null; + const list = listRef.current; + if (list == null || animatedLayout == null) { + return; + } + const rows = keyedRows(list); + if (rows.size === 0) { + // No keyed row yet: the list's last child, or the list while it is + // empty, stands in. A first keyed row then enters, and the content + // after the list glides. + const last = list.lastElementChild; + const target = last instanceof HTMLElement ? last : list; + const change = reportLayoutChange(animatedLayout, () => target); + change.measureBefore(); + measuredRef.current = { + rows, + order: [], + tops: new Map(), + near: null, + reported: new Set([target]), + changes: [change], + settled: [], + }; + reportedRows.set(list, measuredRef.current.reported); + return; + } + const order = [...rows.keys()]; + const elements = [...rows.values()]; + const height = list.ownerDocument.defaultView?.innerHeight ?? 0; + // The rows near the visible part (a viewport's height above and below + // it): only they can glide in view, so only their places are read. + const near = rowsMeeting(elements, -height, 2 * height); + const settled: Settled[] = []; + const tops = new Map(); + if (near != null) { + for (let index = near[0]; index <= near[1]; index++) { + const done = settleTranslation(elements[index]); + if (done != null) { + settled.push(done); + } + } + for (let index = near[0]; index <= near[1]; index++) { + tops.set(order[index], elements[index].getBoundingClientRect().top); + } + } + // The module exits only rows it measured, so every row in view is + // reported. The last row is reported too, so content after the list + // glides when no row is in view. + const shown = rowsMeeting(elements, 0, height); + const targets: HTMLElement[] = []; + if (shown != null) { + for (let index = shown[0]; index <= shown[1]; index++) { + targets.push(elements[index]); + } + } + if (shown == null || shown[1] !== elements.length - 1) { + targets.push(elements[elements.length - 1]); + } + const changes = targets.map(target => { + const change = reportLayoutChange(animatedLayout, () => target); + change.measureBefore(); + return change; + }); + measuredRef.current = { + rows, + order, + tops, + near, + reported: new Set(targets), + changes, + settled, + }; + reportedRows.set(list, measuredRef.current.reported); + }, [animatedLayout, listRef]); + + // Syncs with external systems. One is the shared size-change module's batch + // for the handle's area, measured before this commit, which this plays. The + // other is the rows reported for the commit, which a leaving row reads as + // it unmounts, before this runs. + useIsomorphicLayoutEffect(() => { + const measured = measuredRef.current; + measuredRef.current = null; + const list = listRef.current; + if (list != null) { + reportedRows.delete(list); + } + if (measured == null || list == null || animatedLayout == null) { + return; + } + const now = keyedRows(list); + // A row that stays shows its translation on itself again; a row that + // left exits settled (what it kept as it left already holds it). + for (const done of measured.settled) { + if (done.row.parentElement === list) { + unsettle(done); + } + } + const order = [...now.keys()]; + if ( + order.length === measured.order.length && + order.every((key, index) => key === measured.order[index]) + ) { + // The same rows in the same order: nothing to play (the measurement + // is dropped by the next frame). + return; + } + // Each row that left comes back before the nearest later row in the + // list. One pass runs from the end, and a row put back is the next one's + // anchor. + const leaving: HTMLElement[] = []; + let anchor: HTMLElement | null = null; + for (let index = measured.order.length - 1; index >= 0; index--) { + const key = measured.order[index]; + const staying = now.get(key); + if (staying != null) { + anchor = staying; + continue; + } + // Only a row the module measured can exit; any other went with the + // commit (it was out of view). + const element = measured.rows.get(key); + if (element != null && measured.reported.has(element)) { + putBack(element, list, anchor); + leaving.push(element); + anchor = element; + } + } + for (const change of measured.changes) { + change.animate(); + } + for (const element of leaving) { + if (!holdLayoutExit(animatedLayout, element, () => element.remove())) { + // An exit the module does not hold (out of view, Reduce Motion with + // a fine pointer): the row goes now, before this frame paints. + element.remove(); + } + } + // A row that appeared in view enters (the module plays an entrance only + // in view): the rows in view are found by halving again. + const current = [...now.values()]; + const height = list.ownerDocument.defaultView?.innerHeight ?? 0; + const shown = rowsMeeting(current, 0, height); + if (shown != null) { + for (let index = shown[0]; index <= shown[1]; index++) { + const element = current[index]; + const key = itemKeyOf(element); + if (key != null && !measured.rows.has(key)) { + playLayoutChange(animatedLayout, element); + } + } + } + markCrossings(measured, now); + }); + + return measure; +} diff --git a/packages/core/src/motion/animatedLayout.boundary.test.ts b/packages/core/src/motion/animatedLayout.boundary.test.ts index 7e426f5977bcc..baf9771ef79a0 100644 --- a/packages/core/src/motion/animatedLayout.boundary.test.ts +++ b/packages/core/src/motion/animatedLayout.boundary.test.ts @@ -150,6 +150,8 @@ describe('architecture:react-component-runtime INV12 source boundary', () => { expect(users).toEqual([ 'AppShell/AppShell.tsx', 'Collapsible/Collapsible.tsx', + 'List/List.tsx', + 'List/listLayoutUpdates.ts', 'SideNav/railMotion.ts', 'Table/plugins/rowExpansion/useTableRowExpansion.tsx', 'TreeList/TreeList.tsx', diff --git a/packages/core/src/privateAttributes/itemKey.stylex.ts b/packages/core/src/privateAttributes/itemKey.stylex.ts new file mode 100644 index 0000000000000..00edf0aac8508 --- /dev/null +++ b/packages/core/src/privateAttributes/itemKey.stylex.ts @@ -0,0 +1,25 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file privateAttributes/itemKey.stylex.ts + * @input A List row's own `itemKey` + * @output itemKeyProps, which marks a row with its key, and itemKeyOf, which + * reads it + * @position Owner module of the private item-key attribute: the only file + * that writes its name. ListItem marks its row, and List/listLayoutUpdates.ts + * matches rows by it across renders. No package entry exports it. + */ + +const ITEM_KEY = 'data-astryx-item-key'; + +/** Spread on a List row: marks it with its `itemKey`, when it has one. */ +export function itemKeyProps( + itemKey: string | number | undefined, +): Readonly> { + return itemKey == null ? {} : {[ITEM_KEY]: String(itemKey)}; +} + +/** The item key a row carries, or null for a row without one. */ +export function itemKeyOf(row: Element): string | null { + return row.getAttribute(ITEM_KEY); +} diff --git a/packages/core/src/privateAttributes/leaving.stylex.ts b/packages/core/src/privateAttributes/leaving.stylex.ts new file mode 100644 index 0000000000000..37e43789be8dc --- /dev/null +++ b/packages/core/src/privateAttributes/leaving.stylex.ts @@ -0,0 +1,23 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file privateAttributes/leaving.stylex.ts + * @input A List row put back in the document for its exit + * @output markLeaving, which marks such a row, and isLeaving, which reads the + * mark + * @position Owner module of the private leaving attribute: the only file that + * writes its name. List/listLayoutUpdates.ts marks a row it puts back, so no + * later commit counts it as a row. No package entry exports it. + */ + +const LEAVING = 'data-astryx-leaving'; + +/** Marks `row` as put back for its exit: it is not a row any more. */ +export function markLeaving(row: Element): void { + row.setAttribute(LEAVING, ''); +} + +/** Whether `row` was put back for its exit. */ +export function isLeaving(row: Element): boolean { + return row.hasAttribute(LEAVING); +} diff --git a/packages/core/src/privateAttributes/travelling.stylex.ts b/packages/core/src/privateAttributes/travelling.stylex.ts new file mode 100644 index 0000000000000..fa19fd3d8e023 --- /dev/null +++ b/packages/core/src/privateAttributes/travelling.stylex.ts @@ -0,0 +1,63 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file privateAttributes/travelling.stylex.ts + * @input StyleX and the surface color token + * @output `travellingStyles` for a List row that slides across other rows, + * and markTravelling, which marks the row for the length of its slide + * @position Owner module of the private travelling attribute: the only file + * that writes its name. List/listLayoutUpdates.ts marks a row, and ListItem + * composes the styles. No package entry exports it. + */ + +import * as stylex from '@stylexjs/stylex'; +import {colorVars} from '../theme/tokens.stylex'; + +const TRAVELLING = 'data-astryx-travelling'; + +/** + * Marks `row` as sliding across rows that move the other way. Returns the + * call that removes the mark when the slide ends. + */ +export function markTravelling(row: Element): () => void { + row.setAttribute(TRAVELLING, ''); + return () => row.removeAttribute(TRAVELLING); +} + +export const travellingStyles = stylex.create({ + // A row that slides across rows moving the other way rides above them, with + // the surface behind it, for the length of its slide. A UIKit cell passes + // its neighbors opaque and on top, and these rows have no background of + // their own. The surface is an inset shadow across the padding box, under + // the press and the row's content, so the divider and the press stay + // visible. A selected row keeps its own fill. It takes no pseudo-element, + // since under a finger the row's `::after` is its hit layer. Its z-index, 2, + // is above a swipeable row's raise under a finger (1), so it rides above + // the swipeable rows it crosses. + row: { + zIndex: { + default: null, + '[data-astryx-travelling]': 2, + }, + boxShadow: { + default: null, + '[data-astryx-travelling]:not([aria-selected="true"],[aria-current="true"])': `inset 0 0 0 100vmax ${colorVars['--color-background-surface']}`, + }, + }, + // A swipeable row is a stacking context at rest, since Item translates its + // swipe root. So its band's own z-index orders only inside it. Under a + // finger the row itself rises above the rows after it, whose boxes its band + // reaches into. The list isolates, so the row stays below a sticky header. + // StyleX keeps one zIndex per element, so this style also carries the + // travelling raise. Compose it after `row`. + raisedSwipeRow: { + zIndex: { + default: null, + '[data-astryx-travelling]': 2, + '@media (pointer: coarse)': { + default: 1, + '[data-astryx-travelling]': 2, + }, + }, + }, +}); From 898280673a7cabe83735a5d7c3b2b5dbbd6451e6 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 6 Nov 2026 02:42:54 -0800 Subject: [PATCH 02/10] fix(core): the layout glide takes --duration-medium Owner decision, Nov 6 2026 (Cindy): the layout glide takes --duration-medium. The shared glide played over --duration-medium-min; it now plays over --duration-medium: 300 ms in the Neutral theme and 410 ms with no theme, instead of 225 ms and 310 ms, both scaled by tempo. Collapsible, TreeList, Table's row expansion, AppShell's content area and List share it. AST-105 FR4 names the token, and its DEC-3 records the decision. --- .changeset/animated-layout-curve-tokens.md | 2 +- .../stories/ThemeMotionTempo.stories.tsx | 2 +- docs/specs/AST-105-animated-layout/spec.md | 14 +++++++++- ...animatedLayout.interaction.browser.spec.ts | 28 +++++++++---------- .../themeTempo.interaction.browser.spec.ts | 8 +++--- .../core/src/motion/animatedLayout.test.ts | 26 ++++++++--------- packages/core/src/motion/animatedLayout.ts | 4 +-- 7 files changed, 47 insertions(+), 37 deletions(-) diff --git a/.changeset/animated-layout-curve-tokens.md b/.changeset/animated-layout-curve-tokens.md index a199104b8d538..c5e45a67e350d 100644 --- a/.changeset/animated-layout-curve-tokens.md +++ b/.changeset/animated-layout-curve-tokens.md @@ -2,6 +2,6 @@ '@astryxdesign/core': patch --- -[fix] Animated layout: the glide, the in-place swap and the edge reveal play the theme's move curve (`--ease-move`) over `--duration-medium-min` instead of a spring, so they follow the theme's `character` and `tempo` and land with the motion around them. Reduce Motion is unchanged: a cross-fade under a coarse pointer, an immediate change otherwise. The glides of AppShell's content area, Collapsible, Table's row expansion and TreeList change feel: 225 ms in the Neutral theme, 310 ms with no theme, instead of about 735 ms. A theme whose move easing is a `linear()` or `steps()` function glides on it, as the browser plays it. The segmented control's selection, which reads its timing the same way, now plays such an easing too instead of moving at once. +[fix] Animated layout: the glide, the in-place swap and the edge reveal play the theme's move curve (`--ease-move`) over `--duration-medium` instead of a spring, so they follow the theme's `character` and `tempo` and land with the motion around them. Reduce Motion is unchanged: a cross-fade under a coarse pointer, an immediate change otherwise. The glides of AppShell's content area, Collapsible, Table's row expansion and TreeList change feel: 300 ms in the Neutral theme, 410 ms with no theme, instead of about 735 ms. A theme whose move easing is a `linear()` or `steps()` function glides on it, as the browser plays it. The segmented control's selection, which reads its timing the same way, now plays such an easing too instead of moving at once. @vjeux diff --git a/apps/storybook/stories/ThemeMotionTempo.stories.tsx b/apps/storybook/stories/ThemeMotionTempo.stories.tsx index 650161f0453f5..10fdf105747ce 100644 --- a/apps/storybook/stories/ThemeMotionTempo.stories.tsx +++ b/apps/storybook/stories/ThemeMotionTempo.stories.tsx @@ -133,7 +133,7 @@ const durationScaleTheme = defineTheme({ /** * A theme with only a duration scale, nested in a theme at tempo 1.5. Its - * glide plays its own scale's `--duration-medium-min`, which the outer tempo + * glide plays its own scale's `--duration-medium`, which the outer tempo * does not reach. */ export const NestedDurationScale: Story = { diff --git a/docs/specs/AST-105-animated-layout/spec.md b/docs/specs/AST-105-animated-layout/spec.md index 4ecfa071949d3..14c60b474c905 100644 --- a/docs/specs/AST-105-animated-layout/spec.md +++ b/docs/specs/AST-105-animated-layout/spec.md @@ -89,7 +89,7 @@ const animatedLayout = useAnimatedLayout({containerRef: scrollRef}); element plays its own animation, entering, exiting, or resizing, and the content after it moves with it. Both play the same motion, so the timing is governed centrally, never per component: the theme's move curve, - `--ease-move`, over `--duration-medium-min`, which follow the theme's + `--ease-move`, over `--duration-medium`, which follow the theme's `character` and `tempo` (`spec:AST-108` FR1, FR2). The glide is curve tokens, never a spring, and no character or option plays a platform-measured curve for it (`spec:AST-094` FR45). Both start on the same @@ -262,6 +262,18 @@ tokens, never a spring (`spec:AST-094` FR45). Rejected: the measured spring as the glide; a platform-measured opt-in, such as a separate character. +### DEC-3 — The glide takes the medium duration + +**Reference:** `spec:AST-105/DEC-3` +**Decider:** `cixzhang`, `2026-11-06` + +The glide plays over `--duration-medium`, the middle of the theme's medium +durations: 300 ms in the Neutral theme and 410 ms with no theme, both scaled +by `tempo`. Collapsible, TreeList, Table's row expansion, AppShell's content +area and List share it, as one motion. + +Rejected: `--duration-medium-min`. + ## Open questions None. diff --git a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts index 3ee9d7a56ae30..a8f73ace10d66 100644 --- a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts +++ b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts @@ -880,7 +880,7 @@ test.describe('spec:AST-105 Coverage', () => { page, `
    `, - '#area { --duration-medium-min: 1000ms; }', + '#area { --duration-medium: 1000ms; }', ); await change(page); await page.waitForTimeout(100); @@ -1961,11 +1961,11 @@ test.describe('spec:AST-105 FR2–FR4', () => { expect(grow[0].startTime).toBe(follower[0].startTime); expect(grow[0].duration).toBeCloseTo(follower[0].duration, 3); // With no stylesheet, the tokens read core's declared values. - expect(follower[0].duration).toBeCloseTo(310, 3); + expect(follower[0].duration).toBeCloseTo(410, 3); expectOnCurve( await page.evaluate(() => window.curveOf('#a')), [0.24, 1, 0.4, 1], - 310, + 410, ); }); @@ -2349,30 +2349,30 @@ test.describe('spec:AST-105 FR2–FR4', () => { for (const theme of [ { name: 'at tempo 0.75', - style: '--duration-medium-min: 232.5ms', - ms: 232.5, + style: '--duration-medium: 307.5ms', + ms: 307.5, points: [0.24, 1, 0.4, 1], }, { name: 'at tempo 1.5', - style: '--duration-medium-min: 465ms', - ms: 465, + style: '--duration-medium: 615ms', + ms: 615, points: [0.24, 1, 0.4, 1], }, { name: "at character 'crisp'", style: '--ease-move: cubic-bezier(0, 0, 0.2, 1)', - ms: 310, + ms: 410, points: [0, 0, 0.2, 1], }, { name: "at character 'expressive'", style: '--ease-move: cubic-bezier(0.3, 1.2, 0.5, 1)', - ms: 310, + ms: 410, points: [0.3, 1.2, 0.5, 1], }, ] as const) { - test(`a theme ${theme.name}: the glide plays its --ease-move over its --duration-medium-min (FR4)`, async ({ + test(`a theme ${theme.name}: the glide plays its --ease-move over its --duration-medium (FR4)`, async ({ page, }) => { // The tokens a theme with that knob writes on its scope. @@ -2407,11 +2407,11 @@ test.describe('spec:AST-105 FR2–FR4', () => { await change(page); const motions = await page.evaluate(() => window.motionOf('#a')); expect(motions, 'the content after the change glides').toHaveLength(1); - expect(motions[0].duration).toBeCloseTo(310, 3); + expect(motions[0].duration).toBeCloseTo(410, 3); expectOnEase( await page.evaluate(() => window.curveOf('#a')), theme.ease, - 310, + 410, ); }); } @@ -2423,8 +2423,8 @@ test.describe('spec:AST-105 FR2–FR4', () => { await open( page, PAGE, - `#area { --duration-medium-min: 310ms; --ease-move: cubic-bezier(0.24, 1, 0.4, 1); } - #grow { --duration-medium-min: 620ms; --ease-move: cubic-bezier(0, 0, 0.2, 1); }`, + `#area { --duration-medium: 310ms; --ease-move: cubic-bezier(0.24, 1, 0.4, 1); } + #grow { --duration-medium: 620ms; --ease-move: cubic-bezier(0, 0, 0.2, 1); }`, ); await change(page); const [motion] = await page.evaluate(() => window.motionOf('#a')); diff --git a/packages/core/src/motion/__tests__/themeTempo.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/themeTempo.interaction.browser.spec.ts index aaacc179807a3..0a881ff402475 100644 --- a/packages/core/src/motion/__tests__/themeTempo.interaction.browser.spec.ts +++ b/packages/core/src/motion/__tests__/themeTempo.interaction.browser.spec.ts @@ -238,18 +238,18 @@ test('a duration scale nested in a tempo theme glides on its own duration token' page, }) => { await openStory(page, NESTED_STORY, 3); - // Each row's `--duration-medium-min`, in ms, as its theme writes it. + // Each row's `--duration-medium`, in ms, as its theme writes it. const tokenMs = async (row: string) => page.evaluate( selector => Number.parseFloat( getComputedStyle( document.querySelector(selector) as Element, - ).getPropertyValue('--duration-medium-min'), + ).getPropertyValue('--duration-medium'), ), row, ); - // Each row glides on the `--duration-medium-min` of the theme it is in. + // Each row glides on the `--duration-medium` of the theme it is in. for (const row of ['plain', 'outer', 'nested']) { const selector = `section[data-row="${row}"]`; expect(await glideMs(page, selector), row).toBeCloseTo( @@ -260,6 +260,6 @@ test('a duration scale nested in a tempo theme glides on its own duration token' // The nested scale's own value: the outer tempo is not on it. const own = expandMotionScale({fast: 130, medium: 310, ratio: 0.75}); expect(await tokenMs('section[data-row="nested"]')).toBe( - Number.parseFloat(own['--duration-medium-min']), + Number.parseFloat(own['--duration-medium']), ); }); diff --git a/packages/core/src/motion/animatedLayout.test.ts b/packages/core/src/motion/animatedLayout.test.ts index df4c4c063cf24..2f53bf7eb25d2 100644 --- a/packages/core/src/motion/animatedLayout.test.ts +++ b/packages/core/src/motion/animatedLayout.test.ts @@ -361,7 +361,7 @@ describe('one shared motion (spec:AST-105 FR4)', () => { ); } - it("plays the changed element and its followers on the theme's move curve over --duration-medium-min, with one duration", async () => { + it("plays the changed element and its followers on the theme's move curve over --duration-medium, with one duration", async () => { // With no stylesheet, the tokens read core's declared values. await changeOnce(); const follower = played.find(p => (p.element as HTMLElement).id === 'a'); @@ -369,16 +369,16 @@ describe('one shared motion (spec:AST-105 FR4)', () => { expect(follower).toBeDefined(); expect(own).toBeDefined(); expect(own?.options.duration).toBe(follower?.options.duration); - expect(Number(follower?.options.duration)).toBeCloseTo(310, 6); - const remaining = remainingOn([0.24, 1, 0.4, 1], 310); + expect(Number(follower?.options.duration)).toBeCloseTo(410, 6); + const remaining = remainingOn([0.24, 1, 0.4, 1], 410); for (const {t, y} of verticalCurveOf(follower as Played)) { expect(y).toBeCloseTo(-80 * remaining(t), 3); } }); - it('plays the --duration-medium-min and --ease-move of the theme the area is in', async () => { + it('plays the --duration-medium and --ease-move of the theme the area is in', async () => { await changeOnce( - '--duration-medium-min: 200ms; --ease-move: cubic-bezier(0, 0, 1, 1)', + '--duration-medium: 200ms; --ease-move: cubic-bezier(0, 0, 1, 1)', ); const follower = played.find(p => (p.element as HTMLElement).id === 'a'); expect(Number(follower?.options.duration)).toBeCloseTo(200, 6); @@ -389,17 +389,15 @@ describe('one shared motion (spec:AST-105 FR4)', () => { it("follows the theme's tempo through its duration token, never scaled twice (spec:AST-108 FR2)", async () => { // A theme at tempo 1.5 writes the scaled token beside its tempo. - await changeOnce( - '--duration-medium-min: 465ms; --_astryx-motion-tempo: 1.5', - ); + await changeOnce('--duration-medium: 615ms; --_astryx-motion-tempo: 1.5'); const follower = played.find(p => (p.element as HTMLElement).id === 'a'); const own = played.find(p => (p.element as HTMLElement).id === 'changed'); - expect(Number(follower?.options.duration)).toBeCloseTo(465, 6); + expect(Number(follower?.options.duration)).toBeCloseTo(615, 6); expect(own?.options.duration).toBe(follower?.options.duration); }); it('lands at once when the theme sets a zero duration', async () => { - await changeOnce('--duration-medium-min: 0ms'); + await changeOnce('--duration-medium: 0ms'); expect(played).toEqual([]); }); @@ -424,7 +422,7 @@ describe('one shared motion (spec:AST-105 FR4)', () => { it('retargets an element already gliding: one glide, started from where it is on screen', async () => { // A long, even curve, so the first glide still moves fast 100 ms in. const {area, changed, phase} = setUp( - '
    ', + '
    ', ); const a = document.getElementById('a') as HTMLElement; let top = 0; @@ -759,14 +757,14 @@ describe('the indicator transition', () => { expect(chevron.style.getPropertyValue('transition-timing-function')).toBe( 'cubic-bezier(0.24, 1, 0.4, 1)', ); - expect(chevron.style.getPropertyValue('transition-duration')).toBe('310ms'); + expect(chevron.style.getPropertyValue('transition-duration')).toBe('410ms'); applyLayoutChangeTransition(null, chevron); expect(chevron.style.getPropertyValue('transition-duration')).toBe(''); }); it('takes the timing read where the area is, whatever scope sits between them', () => { - document.body.innerHTML = `
    -
    `; + document.body.innerHTML = `
    +
    `; const area = document.getElementById('area') as HTMLElement; const chevron = document.getElementById( 'chevron', diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.ts index 3364d7157eb12..b5813c19ed42b 100644 --- a/packages/core/src/motion/animatedLayout.ts +++ b/packages/core/src/motion/animatedLayout.ts @@ -131,14 +131,14 @@ function matches(element: Element, query: string): boolean { } /** - * The theme's move curve over its shortest medium duration where `area` is: + * The theme's move curve over its medium duration where `area` is: * one value for the glide, the changed element and the indicator. The tokens * carry the theme's `character` and `tempo`. Null when the duration is zero * or the browser plays no such easing, and then the change lands at once. */ function glideProgress(area: Element): GlideProgress | null { const curve = readThemeTiming(area, { - duration: '--duration-medium-min', + duration: '--duration-medium', easing: '--ease-move', }); const easing = readThemeTokenText(area, '--ease-move'); From b79fde9155410daa35aaf0d73b8f53a7dcc82f60 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 6 Nov 2026 04:25:38 -0800 Subject: [PATCH 03/10] fix(List): a change reads every near row before it settles any Settling a swiped row read the next row's transform after writing the row before it, and read every row's place after all the writes. One pass now reads each near row's translation and place, and then the settles are written. A settled row's place is its box less its own translation. --- .../core/src/List/listLayoutUpdates.test.tsx | 86 +++++++++++++++++++ packages/core/src/List/listLayoutUpdates.ts | 62 ++++++++++--- 2 files changed, 134 insertions(+), 14 deletions(-) diff --git a/packages/core/src/List/listLayoutUpdates.test.tsx b/packages/core/src/List/listLayoutUpdates.test.tsx index 5a301f3124258..fdad8754caa55 100644 --- a/packages/core/src/List/listLayoutUpdates.test.tsx +++ b/packages/core/src/List/listLayoutUpdates.test.tsx @@ -570,6 +570,92 @@ describe('List row updates through animatedLayout', () => { }); }); + it('reads every near row before it settles any swiped row: no read between two settles', async () => { + // jsdom has no DOMMatrix: a 2D one, enough for a translation. + class Matrix { + a = 1; + b = 0; + c = 0; + d = 1; + e = 0; + f = 0; + is2D = true; + constructor(init?: string) { + const translate = /translate\(([-\d.]+)px,\s*([-\d.]+)px\)/.exec( + init ?? '', + ); + if (translate != null) { + this.e = Number(translate[1]); + this.f = Number(translate[2]); + } + } + translate(x: number, y: number) { + const next = new Matrix(); + next.e = this.e + x; + next.f = this.f + y; + return next; + } + multiply(other: Matrix) { + return this.translate(other.e, other.f); + } + toString() { + return `matrix(1, 0, 0, 1, ${this.e}, ${this.f})`; + } + } + vi.stubGlobal('DOMMatrix', Matrix); + render(); + // Two rows a swipe left translated, with a row between them. + for (const label of ['Inbox', 'Drafts']) { + const row = [...document.querySelectorAll('li')].find( + li => li.textContent === label, + ); + row?.style.setProperty('transform', 'translate(-40px, 0px)'); + } + const log: string[] = []; + const inRow = (element: Element) => element.closest('li') != null; + const getComputedStyle = window.getComputedStyle.bind(window); + vi.spyOn(window, 'getComputedStyle').mockImplementation( + (element, pseudo) => { + if (inRow(element)) { + log.push('read'); + } + return getComputedStyle(element, pseudo); + }, + ); + const rect = Element.prototype.getBoundingClientRect; + Element.prototype.getBoundingClientRect = function (this: Element) { + if (inRow(this)) { + log.push('read'); + } + return rect.call(this); + }; + const settles = new WeakSet(); + for (const row of document.querySelectorAll('li')) { + settles.add(row.style); + } + const setProperty = CSSStyleDeclaration.prototype.setProperty; + vi.spyOn(CSSStyleDeclaration.prototype, 'setProperty').mockImplementation( + function (this: CSSStyleDeclaration, name, value, priority) { + // A settle turns a row's own translation off. + if (name === 'transform' && value === 'none' && settles.has(this)) { + log.push('settle'); + } + setProperty.call(this, name, value, priority); + }, + ); + try { + await change(['Inbox', 'Sent', 'New', 'Drafts', 'Archive']); + } finally { + Element.prototype.getBoundingClientRect = rect; + vi.unstubAllGlobals(); + } + // The first two settles are the two swiped rows of the one change. + const first = log.indexOf('settle'); + const second = log.indexOf('settle', first + 1); + expect(second, log.join(' ')).toBeGreaterThan(first); + expect(log.slice(first, second), log.join(' ')).not.toContain('read'); + }); + it('a re-render with the same rows in the same order plays nothing', async () => { render(); await change(['Inbox', 'Sent']); diff --git a/packages/core/src/List/listLayoutUpdates.ts b/packages/core/src/List/listLayoutUpdates.ts index 0af7f3933c1ed..1cfc9037698ca 100644 --- a/packages/core/src/List/listLayoutUpdates.ts +++ b/packages/core/src/List/listLayoutUpdates.ts @@ -220,6 +220,16 @@ interface Settled { >; } +/** What `readTranslation` reads off a row, before anything is written. */ +interface Translation { + readonly view: Window & typeof globalThis; + readonly row: HTMLElement; + readonly x: number; + readonly y: number; + readonly children: ReadonlyArray; + readonly transforms: ReadonlyArray; +} + /** * Moves a row's own translation, such as a swipe's, onto its children. So the * row's box lies where the row lies in the list, while it shows the same @@ -230,10 +240,12 @@ interface Settled { * same before and after the commit, so nothing glides it. With the * translation on the row, a row that a swipe carried out of the list's box * would lie out of view. Its exit would then clip the action. Only a - * translation moves. Returns what to undo, or null when the row has no - * translation of its own. + * translation moves. `readTranslation` reads it, and `settleTranslation` + * moves it, so a list reads every row before it writes any. Returns the + * row's translation and its children's transforms, or null when the row has + * no translation of its own. */ -function settleTranslation(row: HTMLElement): Settled | null { +function readTranslation(row: HTMLElement): Translation | null { const view = row.ownerDocument.defaultView; if (view == null || typeof view.DOMMatrix !== 'function') { return null; @@ -257,11 +269,27 @@ function settleTranslation(row: HTMLElement): Settled | null { (child): child is HTMLElement | SVGElement => child instanceof view.HTMLElement || child instanceof view.SVGElement, ); - // Every transform is read before any is written. A translation composes - // the same way whatever a child's transform origin. - const transforms = children.map( - child => view.getComputedStyle(child).transform, - ); + return { + view, + row, + x: own.e, + y: own.f, + children, + // A translation composes the same way whatever a child's transform + // origin. + transforms: children.map(child => view.getComputedStyle(child).transform), + }; +} + +/** Moves a row's own translation onto its children. Returns what to undo. */ +function settleTranslation({ + view, + row, + x, + y, + children, + transforms, +}: Translation): Settled { const prior = [row, ...children].map( element => [ @@ -273,7 +301,7 @@ function settleTranslation(row: HTMLElement): Settled | null { row.style.setProperty('transform', 'none'); children.forEach((child, index) => { const current = transforms[index]; - const shift = new view.DOMMatrix().translate(own.e, own.f); + const shift = new view.DOMMatrix().translate(x, y); const moved = current === '' || current === 'none' ? shift @@ -418,14 +446,20 @@ export function useListLayoutUpdates( const settled: Settled[] = []; const tops = new Map(); if (near != null) { + // One pass reads every near row's translation and place before any + // settle is written. A settled row's place is its box without its own + // translation. + const translations: Translation[] = []; for (let index = near[0]; index <= near[1]; index++) { - const done = settleTranslation(elements[index]); - if (done != null) { - settled.push(done); + const translation = readTranslation(elements[index]); + const {top} = elements[index].getBoundingClientRect(); + tops.set(order[index], top - (translation?.y ?? 0)); + if (translation != null) { + translations.push(translation); } } - for (let index = near[0]; index <= near[1]; index++) { - tops.set(order[index], elements[index].getBoundingClientRect().top); + for (const translation of translations) { + settled.push(settleTranslation(translation)); } } // The module exits only rows it measured, so every row in view is From 1450bb1a70f70145e9051cfc1a2a6eb0f8dd8357 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 6 Nov 2026 08:48:31 -0800 Subject: [PATCH 04/10] docs(AST-105): DEC-3 names List among the glide's adopters This pull request makes List adopt the shared layout glide, so DEC-3 names it with Collapsible, TreeList, Table's row expansion and AppShell's content area. The merge of main took main's side of DEC-3, which lists only the components already on main. --- docs/specs/AST-105-animated-layout/spec.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/specs/AST-105-animated-layout/spec.md b/docs/specs/AST-105-animated-layout/spec.md index beabc58659d27..c632207b3f403 100644 --- a/docs/specs/AST-105-animated-layout/spec.md +++ b/docs/specs/AST-105-animated-layout/spec.md @@ -277,8 +277,8 @@ Rejected: the measured spring as the glide; a platform-measured opt-in, such as The glide plays over `--duration-medium`, the middle of the theme's medium durations: 300 ms in the Neutral theme and 410 ms with no theme, both scaled -by `tempo`. Collapsible, TreeList, Table's row expansion and AppShell's -content area share it, as one motion. +by `tempo`. Collapsible, TreeList, Table's row expansion, AppShell's content +area and List share it, as one motion. Rejected: `--duration-medium-min`. From 06eacd7e5694de56b024212764e7951d3771b658 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 6 Nov 2026 11:55:41 -0800 Subject: [PATCH 05/10] fix(List): measuring a change only reads A row a swipe translated keeps its translation across the commit, so a change with a row swiped open lays the page out as often as one with none. A row that leaves settles after the commit, before any place is read again, so its exit still runs on its own box, in view, at no layout of its own. The glide its old, translated place gives it lands at once. --- .../ListUpdates.interaction.browser.spec.ts | 163 ++++++++++++++++++ .../core/src/List/listLayoutUpdates.test.tsx | 66 +++++-- packages/core/src/List/listLayoutUpdates.ts | 103 +++++------ 3 files changed, 257 insertions(+), 75 deletions(-) diff --git a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts index 902820c79a522..c5810670b91fd 100644 --- a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts +++ b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts @@ -742,6 +742,169 @@ test('a row swiped away with a removal action exits in place as it was on screen await expect(leaving(page)).toHaveCount(0, {timeout: 3000}); }); +test('a change with a row swiped open lays the page out no more often than the same change with none', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'Chromium counts layouts and drives the swipe through CDP', + ); + const layoutsFor = async (isSwiped: boolean) => { + await open(page, SWIPE_STORY); + const cdp = await page.context().newCDPSession(page); + if (isSwiped) { + const sent = row(page, 'Sent'); + await expect( + sent.locator('[data-swipe-panel="trailing"]'), + ).toBeAttached(); + const box = await sent.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + const y = box.y + box.height / 2; + const startX = box.x + box.width - 24; + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [{x: startX, y}], + type: 'touchStart', + }); + for (const fraction of [0.02, 0.05, 0.1, 0.15, 0.2, 0.25]) { + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [{x: startX - box.width * fraction, y}], + type: 'touchMove', + }); + await page.waitForTimeout(40); + } + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [], + type: 'touchEnd', + }); + await expect + .poll(async () => + sent.evaluate( + el => new DOMMatrix(getComputedStyle(el).transform).m41, + ), + ) + .toBeLessThan(-20); + } + await expect + .poll(async () => page.evaluate(() => document.getAnimations().length)) + .toBe(0); + await cdp.send('Performance.enable'); + const layouts = async () => { + const {metrics} = await cdp.send('Performance.getMetrics'); + return metrics.find(metric => metric.name === 'LayoutCount')?.value ?? 0; + }; + const before = await layouts(); + // A click with no pointer, so no swipe closes and no hover restyles. + await page.evaluate(async () => { + const button = [...document.querySelectorAll('button')].find( + element => element.textContent?.trim() === 'Move Archive first', + ); + button?.click(); + await new Promise(resolve => { + requestAnimationFrame(() => requestAnimationFrame(() => resolve())); + }); + }); + const after = await layouts(); + await cdp.detach(); + return after - before; + }; + const none = await layoutsFor(false); + const swiped = await layoutsFor(true); + expect(swiped, `with a row swiped open: ${swiped}; with none: ${none}`).toBe( + none, + ); +}); + +test('a row swiped away lays the page out as often as the same swipe with no translation on the row, and never glides sideways', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'Chromium counts layouts and drives the swipe through CDP', + ); + const swipeAway = async (isTranslated: boolean) => { + await open(page, SWIPE_STORY); + const cdp = await page.context().newCDPSession(page); + const sent = row(page, 'Sent'); + await expect(sent.locator('[data-swipe-panel="trailing"]')).toBeAttached(); + if (!isTranslated) { + // The same gesture and removal, with no translation on the row. + await sent.evaluate(el => { + el.style.setProperty('transform', 'none', 'important'); + }); + } + const box = await sent.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + // From the frame where Sent is put back for its exit: does a glide on it + // move it sideways? + await page.evaluate(() => { + const state = {sideways: -1}; + (window as unknown as {__exit: typeof state}).__exit = state; + const tick = () => { + const exit = document.querySelector( + '#storybook-root li[data-astryx-leaving]', + ); + if (exit != null) { + state.sideways = exit + .getAnimations() + .filter(animation => + (animation.effect as KeyframeEffect | null) + ?.getKeyframes() + .some(frame => 'translate' in frame), + ).length; + return; + } + requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); + }); + const y = box.y + box.height / 2; + const startX = box.x + box.width - 24; + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [{x: startX, y}], + type: 'touchStart', + }); + for (const fraction of [0.02, 0.05, 0.1, 0.2, 0.35, 0.5, 0.65, 0.8, 0.9]) { + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [{x: startX - box.width * fraction, y}], + type: 'touchMove', + }); + await page.waitForTimeout(40); + } + await cdp.send('Performance.enable'); + const layouts = async () => { + const {metrics} = await cdp.send('Performance.getMetrics'); + return metrics.find(metric => metric.name === 'LayoutCount')?.value ?? 0; + }; + const before = await layouts(); + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [], + type: 'touchEnd', + }); + await expect(leaving(page)).toHaveCount(1, {timeout: 3000}); + await expect(leaving(page)).toHaveCount(0, {timeout: 3000}); + const after = await layouts(); + const sideways = await page.evaluate( + () => (window as unknown as {__exit: {sideways: number}}).__exit.sideways, + ); + await cdp.detach(); + return {layouts: after - before, sideways}; + }; + const plain = await swipeAway(false); + const swiped = await swipeAway(true); + // The leaving row exits where it was: nothing glides it sideways. + expect(swiped.sideways, JSON.stringify({plain, swiped})).toBe(0); + // Its settle costs no layout of its own. + expect(swiped.layouts, JSON.stringify({plain, swiped})).toBeLessThanOrEqual( + plain.layouts, + ); +}); + test('a row a swipe left open, still moving when another row is swiped away, is left as the swipe moves it: the list leaves no transform on it', async ({ page, browserName, diff --git a/packages/core/src/List/listLayoutUpdates.test.tsx b/packages/core/src/List/listLayoutUpdates.test.tsx index fdad8754caa55..645cae8cb8e83 100644 --- a/packages/core/src/List/listLayoutUpdates.test.tsx +++ b/packages/core/src/List/listLayoutUpdates.test.tsx @@ -570,7 +570,16 @@ describe('List row updates through animatedLayout', () => { }); }); - it('reads every near row before it settles any swiped row: no read between two settles', async () => { + /** + * Swipes `swiped` 40 px left, then changes the rows to `next`. It logs each + * read of a row's place or style, each settle, and the commit removing a + * row, in order. + */ + async function readsAndSettles( + initial: string[], + swiped: string[], + next: string[], + ): Promise { // jsdom has no DOMMatrix: a 2D one, enough for a translation. class Matrix { a = 1; @@ -603,9 +612,8 @@ describe('List row updates through animatedLayout', () => { } } vi.stubGlobal('DOMMatrix', Matrix); - render(); - // Two rows a swipe left translated, with a row between them. - for (const label of ['Inbox', 'Drafts']) { + render(); + for (const label of swiped) { const row = [...document.querySelectorAll('li')].find( li => li.textContent === label, ); @@ -629,31 +637,63 @@ describe('List row updates through animatedLayout', () => { } return rect.call(this); }; - const settles = new WeakSet(); + const rows = new WeakSet(); for (const row of document.querySelectorAll('li')) { - settles.add(row.style); + rows.add(row.style); } + const removeChild = Node.prototype.removeChild; + vi.spyOn(Node.prototype, 'removeChild').mockImplementation(function < + T extends Node, + >(this: Node, child: T): T { + if ((child as unknown as Element).tagName === 'LI') { + log.push('commit'); + } + return removeChild.call(this, child) as T; + }); const setProperty = CSSStyleDeclaration.prototype.setProperty; vi.spyOn(CSSStyleDeclaration.prototype, 'setProperty').mockImplementation( function (this: CSSStyleDeclaration, name, value, priority) { // A settle turns a row's own translation off. - if (name === 'transform' && value === 'none' && settles.has(this)) { + if (name === 'transform' && value === 'none' && rows.has(this)) { log.push('settle'); } setProperty.call(this, name, value, priority); }, ); try { - await change(['Inbox', 'Sent', 'New', 'Drafts', 'Archive']); + await change(next); } finally { Element.prototype.getBoundingClientRect = rect; vi.unstubAllGlobals(); } - // The first two settles are the two swiped rows of the one change. - const first = log.indexOf('settle'); - const second = log.indexOf('settle', first + 1); - expect(second, log.join(' ')).toBeGreaterThan(first); - expect(log.slice(first, second), log.join(' ')).not.toContain('read'); + return log; + } + + it('measuring a change with swiped rows in view only reads: a row that stays keeps its translation, and nothing is settled', async () => { + const log = await readsAndSettles( + ['Inbox', 'Sent', 'Drafts', 'Archive'], + ['Inbox', 'Drafts'], + ['Inbox', 'Sent', 'New', 'Drafts', 'Archive'], + ); + expect(log, log.join(' ')).toContain('read'); + expect(log, log.join(' ')).not.toContain('settle'); + }); + + it('a swiped row that leaves settles after the commit, before any place is read again, so it costs no layout of its own', async () => { + const log = await readsAndSettles( + ['Inbox', 'Sent', 'Drafts', 'Archive'], + ['Inbox', 'Drafts'], + ['Inbox', 'Sent', 'Archive'], + ); + const commit = log.indexOf('commit'); + const settle = log.indexOf('settle'); + expect(commit, log.join(' ')).toBeGreaterThan(0); + expect(log.slice(0, commit), log.join(' ')).not.toContain('settle'); + expect( + log.filter(entry => entry === 'settle'), + log.join(' '), + ).toHaveLength(1); + expect(log.slice(commit, settle), log.join(' ')).not.toContain('read'); }); it('a re-render with the same rows in the same order plays nothing', async () => { diff --git a/packages/core/src/List/listLayoutUpdates.ts b/packages/core/src/List/listLayoutUpdates.ts index 1cfc9037698ca..08fec09996979 100644 --- a/packages/core/src/List/listLayoutUpdates.ts +++ b/packages/core/src/List/listLayoutUpdates.ts @@ -31,6 +31,7 @@ import {useCallback, useRef, type RefObject} from 'react'; import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import { holdLayoutExit, + landLayoutGlide, playLayoutChange, reportLayoutChange, type AnimatedLayout, @@ -70,8 +71,8 @@ interface Measured { /** The rows reported to the module, the only ones whose exit it holds. */ readonly reported: ReadonlySet; readonly changes: ReadonlyArray; - /** Rows whose translation moved onto their children for the commit. */ - readonly settled: ReadonlyArray; + /** Near rows with a translation of their own, read before the commit. */ + readonly translations: ReadonlyArray; } /** @@ -212,14 +213,6 @@ function putBack( keptStyles.delete(element); } -/** A row whose own translation moved onto its children, and what it replaced. */ -interface Settled { - readonly row: HTMLElement; - readonly prior: ReadonlyArray< - readonly [HTMLElement | SVGElement, string, string] - >; -} - /** What `readTranslation` reads off a row, before anything is written. */ interface Translation { readonly view: Window & typeof globalThis; @@ -231,19 +224,16 @@ interface Translation { } /** - * Moves a row's own translation, such as a swipe's, onto its children. So the - * row's box lies where the row lies in the list, while it shows the same - * thing. This runs for every translated row as a change is measured. After - * the commit it is undone for each row that stays. A row that leaves exits on - * its own box, in view. Its exit's clip keeps the action that the swipe - * uncovered and cuts the content that the swipe carried away. The box is the - * same before and after the commit, so nothing glides it. With the - * translation on the row, a row that a swipe carried out of the list's box - * would lie out of view. Its exit would then clip the action. Only a - * translation moves. `readTranslation` reads it, and `settleTranslation` - * moves it, so a list reads every row before it writes any. Returns the - * row's translation and its children's transforms, or null when the row has - * no translation of its own. + * Reads a row's own translation, such as a swipe's, and its children's + * transforms, as a change is measured. A row that leaves exits on its own + * box, in view. So `settleTranslation` moves its translation onto its + * children before the module reads the new places. Its exit's clip then + * keeps the action that the swipe uncovered and cuts the content that the + * swipe carried away. With the translation on the row, a row that a swipe + * carried out of the list's box would lie out of view. Its exit would then + * clip the action. A row that stays keeps its translation: the module reads + * it on both sides of the commit, so nothing glides it. Returns null when + * the row has no translation of its own. */ function readTranslation(row: HTMLElement): Translation | null { const view = row.ownerDocument.defaultView; @@ -281,7 +271,7 @@ function readTranslation(row: HTMLElement): Translation | null { }; } -/** Moves a row's own translation onto its children. Returns what to undo. */ +/** Moves a row's own translation onto its children. */ function settleTranslation({ view, row, @@ -289,15 +279,7 @@ function settleTranslation({ y, children, transforms, -}: Translation): Settled { - const prior = [row, ...children].map( - element => - [ - element, - element.style.getPropertyValue('transform'), - element.style.getPropertyPriority('transform'), - ] as const, - ); +}: Translation): void { row.style.setProperty('transform', 'none'); children.forEach((child, index) => { const current = transforms[index]; @@ -308,18 +290,6 @@ function settleTranslation({ : shift.multiply(new view.DOMMatrix(current)); child.style.setProperty('transform', moved.toString()); }); - return {row, prior}; -} - -/** Puts back what `settleTranslation` replaced on a row that stays. */ -function unsettle({prior}: Settled): void { - for (const [element, value, priority] of prior) { - if (value === '') { - element.style.removeProperty('transform'); - } else { - element.style.setProperty('transform', value, priority); - } - } } /** @@ -432,7 +402,7 @@ export function useListLayoutUpdates( near: null, reported: new Set([target]), changes: [change], - settled: [], + translations: [], }; reportedRows.set(list, measuredRef.current.reported); return; @@ -443,13 +413,12 @@ export function useListLayoutUpdates( // The rows near the visible part (a viewport's height above and below // it): only they can glide in view, so only their places are read. const near = rowsMeeting(elements, -height, 2 * height); - const settled: Settled[] = []; + const translations: Translation[] = []; const tops = new Map(); if (near != null) { - // One pass reads every near row's translation and place before any - // settle is written. A settled row's place is its box without its own - // translation. - const translations: Translation[] = []; + // One pass reads every near row's translation and place. A row's place + // is its box without its own translation. The measurement writes + // nothing, so no read here lays the page out again. for (let index = near[0]; index <= near[1]; index++) { const translation = readTranslation(elements[index]); const {top} = elements[index].getBoundingClientRect(); @@ -458,9 +427,6 @@ export function useListLayoutUpdates( translations.push(translation); } } - for (const translation of translations) { - settled.push(settleTranslation(translation)); - } } // The module exits only rows it measured, so every row in view is // reported. The last row is reported too, so content after the list @@ -487,7 +453,7 @@ export function useListLayoutUpdates( near, reported: new Set(targets), changes, - settled, + translations, }; reportedRows.set(list, measuredRef.current.reported); }, [animatedLayout, listRef]); @@ -507,13 +473,6 @@ export function useListLayoutUpdates( return; } const now = keyedRows(list); - // A row that stays shows its translation on itself again; a row that - // left exits settled (what it kept as it left already holds it). - for (const done of measured.settled) { - if (done.row.parentElement === list) { - unsettle(done); - } - } const order = [...now.keys()]; if ( order.length === measured.order.length && @@ -547,6 +506,26 @@ export function useListLayoutUpdates( for (const change of measured.changes) { change.animate(); } + // A row that leaves exits on its own box, in view: its translation moves + // onto its children before its exit starts. The commit has already + // changed the layout, so this costs no layout of its own. + const settled: HTMLElement[] = []; + for (const translation of measured.translations) { + if (leaving.includes(translation.row)) { + settleTranslation(translation); + settled.push(translation.row); + } + } + if (settled.length > 0) { + // The module read the row's old place with the translation on it, so + // it glides the row by that translation. The row shows where it + // showed already, so that glide lands before the frame paints. + queueMicrotask(() => { + for (const row of settled) { + landLayoutGlide(row); + } + }); + } for (const element of leaving) { if (!holdLayoutExit(animatedLayout, element, () => element.remove())) { // An exit the module does not hold (out of view, Reduce Motion with From b710232e21f8a4485e902aee03c3a8bd28b920ff Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 6 Nov 2026 12:49:31 -0800 Subject: [PATCH 06/10] fix(List): a leaving swiped row keeps its move in the list The module reads a swiped row's old place with its translation on it, so its glide adds that translation to the row's move in the list. A row that leaves now keeps only the vertical part of that glide, so a row removed by an update that also moves it glides with its neighbours instead of jumping. The swipe-away probe and its comment say what they check. --- .../ListUpdates.interaction.browser.spec.ts | 13 ++- .../core/src/List/listLayoutUpdates.test.tsx | 80 ++++++++++++++++++- packages/core/src/List/listLayoutUpdates.ts | 42 ++++++---- 3 files changed, 113 insertions(+), 22 deletions(-) diff --git a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts index c5810670b91fd..c614e21a6e0be 100644 --- a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts +++ b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts @@ -817,7 +817,7 @@ test('a change with a row swiped open lays the page out no more often than the s ); }); -test('a row swiped away lays the page out as often as the same swipe with no translation on the row, and never glides sideways', async ({ +test('a row swiped away lays the page out no more often than the same swipe with no translation on the row, and never glides sideways', async ({ page, browserName, }) => { @@ -840,8 +840,8 @@ test('a row swiped away lays the page out as often as the same swipe with no tra if (box == null) { throw new Error('no row'); } - // From the frame where Sent is put back for its exit: does a glide on it - // move it sideways? + // From the frame where Sent is put back for its exit, it counts the glides + // that would move it sideways. await page.evaluate(() => { const state = {sideways: -1}; (window as unknown as {__exit: typeof state}).__exit = state; @@ -850,12 +850,17 @@ test('a row swiped away lays the page out as often as the same swipe with no tra '#storybook-root li[data-astryx-leaving]', ); if (exit != null) { + // A glide that moves it in the list keeps x at 0. state.sideways = exit .getAnimations() .filter(animation => (animation.effect as KeyframeEffect | null) ?.getKeyframes() - .some(frame => 'translate' in frame), + .some( + frame => + 'translate' in frame && + !String(frame.translate).startsWith('0px'), + ), ).length; return; } diff --git a/packages/core/src/List/listLayoutUpdates.test.tsx b/packages/core/src/List/listLayoutUpdates.test.tsx index 645cae8cb8e83..96cc800549786 100644 --- a/packages/core/src/List/listLayoutUpdates.test.tsx +++ b/packages/core/src/List/listLayoutUpdates.test.tsx @@ -21,8 +21,9 @@ import {ListContext} from './ListContext'; interface Played { readonly element: Element; - readonly keyframes: Keyframe[]; + keyframes: Keyframe[]; readonly animation: Animation; + isCancelled?: boolean; } let played: Played[] = []; @@ -66,7 +67,11 @@ function rectOf(element: Element): DOMRect { ) { top += takes(row); } - return new DOMRect(0, top, 400, ROW); + // A row's own translation, such as a swipe's, moves its box sideways. + const shift = /translate\((-?[\d.]+)px/.exec( + (element as HTMLElement).style.transform, + ); + return new DOMRect(Number(shift?.[1] ?? 0), top, 400, ROW); } if (element !== list && element.id !== 'after') { return new DOMRect(0, 0, 0, 0); @@ -90,13 +95,25 @@ beforeEach(() => { this: Element, keyframes: Keyframe[] | PropertyIndexedKeyframes | null, ) { + const entry = { + element: this, + keyframes: keyframes as Keyframe[], + } as Played; const animation = { - cancel: () => undefined, + cancel: () => { + entry.isCancelled = true; + }, addEventListener: () => undefined, finished: new Promise(() => undefined), currentTime: 0, + effect: { + getKeyframes: () => entry.keyframes, + setKeyframes: (next: Keyframe[]) => { + entry.keyframes = next; + }, + }, } as unknown as Animation; - played.push({element: this, keyframes: keyframes as Keyframe[], animation}); + played.push(Object.assign(entry, {animation})); return animation; }; Element.prototype.getBoundingClientRect = function (this: Element) { @@ -696,6 +713,61 @@ describe('List row updates through animatedLayout', () => { expect(log.slice(commit, settle), log.join(' ')).not.toContain('read'); }); + it('a swiped row that leaves while the same update moves it down glides down with the rows around it, never sideways', async () => { + // jsdom has no DOMMatrix: a 2D one, enough for a translation. + class Matrix { + a = 1; + b = 0; + c = 0; + d = 1; + e = 0; + f = 0; + is2D = true; + constructor(init?: string) { + const translate = /translate\(([-\d.]+)px,\s*([-\d.]+)px\)/.exec( + init ?? '', + ); + if (translate != null) { + this.e = Number(translate[1]); + this.f = Number(translate[2]); + } + } + translate(x: number, y: number) { + const next = new Matrix(); + next.e = this.e + x; + next.f = this.f + y; + return next; + } + multiply(other: Matrix) { + return this.translate(other.e, other.f); + } + toString() { + return `translate(${this.e}px, ${this.f}px)`; + } + } + vi.stubGlobal('DOMMatrix', Matrix); + try { + render(); + const drafts = [...document.querySelectorAll('li')].find( + li => li.textContent === 'Drafts', + ); + drafts?.style.setProperty('transform', 'translate(-40px, 0px)'); + // Drafts leaves, and a row inserted above it moves it a row down. + await change(['New', 'Inbox', 'Sent', 'Archive']); + const glide = played.find( + entry => + entry.element === drafts && + String(entry.keyframes[0]?.translate ?? '') !== '', + ); + expect(String(glide?.keyframes[0]?.translate)).toBe(`0px ${-ROW}px`); + expect(glide?.isCancelled).not.toBe(true); + // It exits settled: its box in the list, its content still swiped. + expect(drafts?.style.transform).toBe('none'); + } finally { + vi.unstubAllGlobals(); + } + }); + it('a re-render with the same rows in the same order plays nothing', async () => { render(); await change(['Inbox', 'Sent']); diff --git a/packages/core/src/List/listLayoutUpdates.ts b/packages/core/src/List/listLayoutUpdates.ts index 08fec09996979..6feed882dec17 100644 --- a/packages/core/src/List/listLayoutUpdates.ts +++ b/packages/core/src/List/listLayoutUpdates.ts @@ -30,8 +30,8 @@ import {useCallback, useRef, type RefObject} from 'react'; import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import { + glideOf, holdLayoutExit, - landLayoutGlide, playLayoutChange, reportLayoutChange, type AnimatedLayout, @@ -225,15 +225,7 @@ interface Translation { /** * Reads a row's own translation, such as a swipe's, and its children's - * transforms, as a change is measured. A row that leaves exits on its own - * box, in view. So `settleTranslation` moves its translation onto its - * children before the module reads the new places. Its exit's clip then - * keeps the action that the swipe uncovered and cuts the content that the - * swipe carried away. With the translation on the row, a row that a swipe - * carried out of the list's box would lie out of view. Its exit would then - * clip the action. A row that stays keeps its translation: the module reads - * it on both sides of the commit, so nothing glides it. Returns null when - * the row has no translation of its own. + * transforms before the commit. Returns null when the row has none. */ function readTranslation(row: HTMLElement): Translation | null { const view = row.ownerDocument.defaultView; @@ -271,7 +263,14 @@ function readTranslation(row: HTMLElement): Translation | null { }; } -/** Moves a row's own translation onto its children. */ +/** + * Moves a row's own translation onto its children. The row's box then lies + * where the row lies in the list, while it shows the same thing. A row that + * leaves exits on that box, in view. Its exit's clip keeps the action that + * a swipe uncovered and cuts the content that the swipe carried away. With + * the translation on the row, a row that a swipe carried out of the list's + * box would lie out of view. + */ function settleTranslation({ view, row, @@ -292,6 +291,20 @@ function settleTranslation({ }); } +/** Drops the sideways part of `row`'s glide, keeping its vertical move. */ +function keepVerticalGlide(row: HTMLElement): void { + const effect = glideOf(row)?.effect as KeyframeEffect | null | undefined; + if (effect == null || typeof effect.setKeyframes !== 'function') { + return; + } + effect.setKeyframes( + effect.getKeyframes().map(({computedOffset: _, translate, ...frame}) => { + const [, y = '0px'] = String(translate ?? '').split(/\s+/); + return {...frame, translate: `0px ${y}`}; + }), + ); +} + /** * Marks each row that crosses another on the longer of the two glides, for * the length of its glide, so it rides above. It reads the glides once the @@ -518,11 +531,12 @@ export function useListLayoutUpdates( } if (settled.length > 0) { // The module read the row's old place with the translation on it, so - // it glides the row by that translation. The row shows where it - // showed already, so that glide lands before the frame paints. + // its glide adds that translation to the row's move in the list. The + // row already shows where it showed, so before the frame paints, the + // glide keeps only its move in the list. queueMicrotask(() => { for (const row of settled) { - landLayoutGlide(row); + keepVerticalGlide(row); } }); } From f787f4313d6778e05f480b80d3ad2aa54b621bb5 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 6 Nov 2026 14:40:08 -0800 Subject: [PATCH 07/10] fix(List): a leaving row keeps its place and its glide's record A second change while a swiped row exits restarted it sideways, because the List rewrote the glide's frames while the module's record of the glide kept the swipe's offset. The module's landLayoutGlideSideways now changes both together. A reorder while a row exits carried that row to the top of the list, because React moves only its own rows. Each leaving row now stays before the row that came after it, or last. --- .../ListUpdates.interaction.browser.spec.ts | 99 +++++++++++++++++++ .../core/src/List/listLayoutUpdates.test.tsx | 97 ++++++++++++++++-- packages/core/src/List/listLayoutUpdates.ts | 84 +++++++++++++--- .../core/src/motion/animatedLayout.test.ts | 91 +++++++++++++++++ packages/core/src/motion/animatedLayout.ts | 47 ++++++++- 5 files changed, 390 insertions(+), 28 deletions(-) diff --git a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts index c614e21a6e0be..fc6bf7b380fb0 100644 --- a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts +++ b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts @@ -910,6 +910,105 @@ test('a row swiped away lays the page out no more often than the same swipe with ); }); +test('a row swiped away and still exiting glides only down when a row moves above it, and stays before the row after it', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'the swipe is driven with Chromium touch events (CDP)', + ); + await open(page, SWIPE_STORY); + const sent = row(page, 'Sent'); + await expect(sent.locator('[data-swipe-panel="trailing"]')).toBeAttached(); + const box = await sent.boundingBox(); + if (box == null) { + throw new Error('no row'); + } + // From the frame where Sent is put back for its exit, it moves Archive + // first 30 ms later. Then it records Sent's new glide and the rows' order. + await page.evaluate(() => { + (window as unknown as {__second: object | null}).__second = null; + const label = (li: Element) => { + const copy = li.cloneNode(true) as Element; + for (const panel of copy.querySelectorAll('[data-swipe-panel]')) { + panel.remove(); + } + return copy.textContent?.trim() ?? ''; + }; + const tick = () => { + const exit = document.querySelector( + '#storybook-root li[data-astryx-leaving]', + ); + if (exit == null) { + requestAnimationFrame(tick); + return; + } + setTimeout(() => { + [...document.querySelectorAll('button')] + .find(button => button.textContent?.trim() === 'Move Archive first') + ?.click(); + requestAnimationFrame(() => { + (window as unknown as {__second: unknown}).__second = { + starts: exit.getAnimations().flatMap(animation => { + const first = ( + animation.effect as KeyframeEffect | null + )?.getKeyframes()[0]?.translate; + return typeof first === 'string' ? [first] : []; + }), + order: [...document.querySelectorAll('#storybook-root li')].map( + li => + `${li.hasAttribute('data-astryx-leaving') ? 'leaving:' : ''}${label(li)}`, + ), + }; + }); + }, 30); + }; + requestAnimationFrame(tick); + }); + const cdp = await page.context().newCDPSession(page); + const y = box.y + box.height / 2; + const startX = box.x + box.width - 24; + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [{x: startX, y}], + type: 'touchStart', + }); + for (const fraction of [0.02, 0.05, 0.1, 0.2, 0.35, 0.5, 0.65, 0.8, 0.9]) { + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [{x: startX - box.width * fraction, y}], + type: 'touchMove', + }); + await page.waitForTimeout(40); + } + await cdp.send('Input.dispatchTouchEvent', { + touchPoints: [], + type: 'touchEnd', + }); + await expect + .poll(async () => + page.evaluate( + () => (window as unknown as {__second: object | null}).__second != null, + ), + ) + .toBe(true); + const second = await page.evaluate( + () => + (window as unknown as {__second: {starts: string[]; order: string[]}}) + .__second, + ); + // Archive moved above it, so it glides down a row, and nothing sideways. + expect(second.starts.length, JSON.stringify(second)).toBeGreaterThan(0); + for (const start of second.starts) { + expect(start.split(' ')[0], JSON.stringify(second)).toBe('0px'); + } + // It stays before Drafts, the row after it as it left. + const order = second.order; + expect(order.indexOf('leaving:Sent'), JSON.stringify(second)).toBe( + order.indexOf('Drafts') - 1, + ); + await expect(leaving(page)).toHaveCount(0, {timeout: 3000}); +}); + test('a row a swipe left open, still moving when another row is swiped away, is left as the swipe moves it: the list leaves no transform on it', async ({ page, browserName, diff --git a/packages/core/src/List/listLayoutUpdates.test.tsx b/packages/core/src/List/listLayoutUpdates.test.tsx index 96cc800549786..0085b72b987b1 100644 --- a/packages/core/src/List/listLayoutUpdates.test.tsx +++ b/packages/core/src/List/listLayoutUpdates.test.tsx @@ -24,6 +24,7 @@ interface Played { keyframes: Keyframe[]; readonly animation: Animation; isCancelled?: boolean; + finishers?: (() => void)[]; } let played: Played[] = []; @@ -103,7 +104,11 @@ beforeEach(() => { cancel: () => { entry.isCancelled = true; }, - addEventListener: () => undefined, + addEventListener: (type: string, listener: () => void) => { + if (type === 'finish') { + (entry.finishers ??= []).push(listener); + } + }, finished: new Promise(() => undefined), currentTime: 0, effect: { @@ -161,6 +166,11 @@ function glides(): Map { continue; } const element = entry.element as HTMLElement; + // A reveal's parts slide inside their row: only rows and the content + // after the list glide. + if (element.tagName !== 'LI' && element.id === '') { + continue; + } out.set( element.id !== '' ? element.id : (element.textContent ?? '').trim(), Math.round(Number(match[2])), @@ -169,13 +179,54 @@ function glides(): Map { return out; } -/** The rows that played an entrance (a reveal), by their text. */ +/** Ends every motion played so far, as each one's end would. */ +function endMotions(): void { + for (const entry of [...played]) { + for (const finish of entry.finishers ?? []) { + finish(); + } + } +} + +/** Whether parts inside `row` play a slide. */ +function slidesInside(row: Element): boolean { + return played.some( + entry => + entry.element !== row && + row.contains(entry.element) && + entry.keyframes[0]?.translate != null, + ); +} + +/** + * The rows that played an entrance (a reveal), by their text. A reveal moves + * a clip on the row, or fades the row in while its parts slide in. + */ function entrances(): string[] { return played - .filter(entry => entry.keyframes[0]?.clipPath != null) + .filter( + entry => + entry.keyframes[0]?.clipPath != null || + (entry.element.tagName === 'LI' && + Number(entry.keyframes[0]?.opacity) === 0 && + slidesInside(entry.element)), + ) .map(entry => (entry.element.textContent ?? '').trim()); } +/** + * Whether `row` plays a conceal: a clip that moves on it, or a fade out while + * its parts slide out. + */ +function conceals(row: Element | undefined): boolean { + return played.some( + entry => + entry.element === row && + (entry.keyframes[0]?.clipPath != null || + (Number(entry.keyframes.at(-1)?.opacity) === 0 && slidesInside(row))), + ); +} + let setRows: (rows: string[]) => void = () => undefined; function Demo({ @@ -306,6 +357,8 @@ describe('List row updates through animatedLayout', () => { ); await change(['Inbox', 'New', 'Sent']); expect(entrances()).toEqual(['New']); + // Once its entrance ends, nothing it showed stays written on it. + act(() => endMotions()); const added = [...document.querySelectorAll('li')].find( row => row.textContent?.trim() === 'New', ); @@ -367,9 +420,11 @@ describe('List row updates through animatedLayout', () => { // The rows after the insert glide, and the new row enters. expect(glides().get('Sent')).toBe(-ROW); expect(entrances()).toEqual(['New']); - // A re-render while they move, with the same rows. + // A re-render while they move, with the same rows. Once the motions end, + // nothing they showed stays written on a row. act(() => rerender()); await flushMicrotasks(); + act(() => endMotions()); for (const row of document.querySelectorAll('li')) { const label = row.textContent?.trim() ?? ''; expect(row.style.getPropertyValue('translate'), label).toBe(''); @@ -427,11 +482,7 @@ describe('List row updates through animatedLayout', () => { expect(leaving).toHaveAttribute('inert'); expect(leaving).toHaveAttribute('aria-hidden', 'true'); // It conceals on the shared motion. - expect( - played.some( - entry => entry.element === leaving && entry.keyframes[0]?.clipPath, - ), - ).toBe(true); + expect(conceals(leaving)).toBe(true); const moved = glides(); expect(moved.get('Drafts')).toBe(ROW); expect(moved.get('after')).toBe(ROW); @@ -498,6 +549,34 @@ describe('List row updates through animatedLayout', () => { ).toEqual(['Sent', 'Drafts']); }); + it('a reorder while a removed row still exits keeps that row where it was, beside the row after it', async () => { + render(); + await change(['Inbox', 'Drafts', 'Archive', 'Spam']); + // Sent still exits, before Drafts. + expect(document.querySelector('li[data-astryx-leaving]')?.textContent).toBe( + 'Sent', + ); + // React moves only its own rows, so moving Spam first would leave Sent at + // the top of the list. + await change(['Spam', 'Inbox', 'Drafts', 'Archive']); + expect( + [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), + ).toEqual(['Spam', 'Inbox', 'Sent', 'Drafts', 'Archive']); + }); + + it('a removed last row that still exits stays last when the rows before it move, and new rows still land after it', async () => { + render(); + await change(['Inbox', 'Sent']); + await change(['Sent', 'Inbox']); + expect( + [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), + ).toEqual(['Sent', 'Inbox', 'Drafts']); + await change(['Sent', 'Inbox', 'New']); + expect( + [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), + ).toEqual(['Sent', 'Inbox', 'Drafts', 'New']); + }); + it('measuring a change keeps no list of the later rows per row: linear work in the row count', async () => { const labels = Array.from({length: 300}, (_, i) => `Row ${i}`); render(); diff --git a/packages/core/src/List/listLayoutUpdates.ts b/packages/core/src/List/listLayoutUpdates.ts index 6feed882dec17..158cc86663925 100644 --- a/packages/core/src/List/listLayoutUpdates.ts +++ b/packages/core/src/List/listLayoutUpdates.ts @@ -30,8 +30,8 @@ import {useCallback, useRef, type RefObject} from 'react'; import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import { - glideOf, holdLayoutExit, + landLayoutGlideSideways, playLayoutChange, reportLayoutChange, type AnimatedLayout, @@ -192,6 +192,15 @@ export function keepPresentation(row: HTMLElement): void { * exit makes it inert. Until then it is marked as leaving and hidden from * assistive technology, so no later commit counts it as a row. */ +/** + * Where each leaving row came back: before the nearest later row as it left. + * A row that left at the list's end stays after the rows the list had then. + */ +const leavingPlaces = new WeakMap< + HTMLElement, + {readonly before: Element | null; readonly after: ReadonlySet} +>(); + function putBack( element: HTMLElement, list: HTMLElement, @@ -200,6 +209,10 @@ function putBack( markLeaving(element); element.setAttribute('aria-hidden', 'true'); list.insertBefore(element, anchor); + leavingPlaces.set(element, { + before: anchor, + after: new Set(anchor == null ? list.children : []), + }); // Back in the document, its parts' animations would apply again over what // they showed as it left: stop them, and show what was on screen. if (typeof element.getAnimations === 'function') { @@ -213,6 +226,53 @@ function putBack( keptStyles.delete(element); } +/** + * Puts each leaving row back where it came back. React moves only its own + * rows. So a commit that moves rows can carry a leaving row away from its + * place, such as to the top of the list. + */ +function keepLeavingInPlace(list: HTMLElement): void { + const rows = [...list.children].filter( + (child): child is HTMLElement => + child instanceof HTMLElement && isLeaving(child), + ); + // A row can come back beside another leaving row, which a pass may move + // first: one pass per row is enough. + for (let pass = 0; pass < rows.length; pass++) { + let isMoved = false; + for (const row of rows) { + const place = leavingPlaces.get(row); + if (place == null) { + continue; + } + if (place.before != null) { + if ( + place.before.parentElement === list && + row.nextElementSibling !== place.before + ) { + list.insertBefore(row, place.before); + isMoved = true; + } + continue; + } + // At the end: after the last row the list had as it left. + let last: Element | null = null; + for (const child of list.children) { + if (child !== row && place.after.has(child)) { + last = child; + } + } + if (last != null && row.previousElementSibling !== last) { + list.insertBefore(row, last.nextElementSibling); + isMoved = true; + } + } + if (!isMoved) { + break; + } + } +} + /** What `readTranslation` reads off a row, before anything is written. */ interface Translation { readonly view: Window & typeof globalThis; @@ -291,20 +351,6 @@ function settleTranslation({ }); } -/** Drops the sideways part of `row`'s glide, keeping its vertical move. */ -function keepVerticalGlide(row: HTMLElement): void { - const effect = glideOf(row)?.effect as KeyframeEffect | null | undefined; - if (effect == null || typeof effect.setKeyframes !== 'function') { - return; - } - effect.setKeyframes( - effect.getKeyframes().map(({computedOffset: _, translate, ...frame}) => { - const [, y = '0px'] = String(translate ?? '').split(/\s+/); - return {...frame, translate: `0px ${y}`}; - }), - ); -} - /** * Marks each row that crosses another on the longer of the two glides, for * the length of its glide, so it rides above. It reads the glides once the @@ -485,6 +531,7 @@ export function useListLayoutUpdates( if (measured == null || list == null || animatedLayout == null) { return; } + keepLeavingInPlace(list); const now = keyedRows(list); const order = [...now.keys()]; if ( @@ -516,6 +563,11 @@ export function useListLayoutUpdates( anchor = element; } } + // A row that left now may be one an earlier leaving row came back + // before. + if (leaving.length > 0) { + keepLeavingInPlace(list); + } for (const change of measured.changes) { change.animate(); } @@ -536,7 +588,7 @@ export function useListLayoutUpdates( // glide keeps only its move in the list. queueMicrotask(() => { for (const row of settled) { - keepVerticalGlide(row); + landLayoutGlideSideways(row); } }); } diff --git a/packages/core/src/motion/animatedLayout.test.ts b/packages/core/src/motion/animatedLayout.test.ts index 2f53bf7eb25d2..2323f2a2f4592 100644 --- a/packages/core/src/motion/animatedLayout.test.ts +++ b/packages/core/src/motion/animatedLayout.test.ts @@ -16,7 +16,9 @@ import {cubicBezier} from './bezier'; import { applyLayoutChangeTransition, createAnimatedLayout, + glideOf, holdLayoutExit, + landLayoutGlideSideways, playLayoutChange, releaseLayoutExit, reportLayoutChange, @@ -1210,3 +1212,92 @@ describe('the walk reaches what the changes can move (spec:AST-105 FR3)', () => expect(translateOf(glide!).y).toBeCloseTo(-80); }); }); + +describe('landLayoutGlideSideways', () => { + /** The glides here also expose their frames, as a browser's do. */ + function withFrames() { + const animate = Element.prototype.animate; + Element.prototype.animate = function ( + this: Element, + ...args: Parameters + ) { + const animation = animate.apply(this, args); + const entry = played[played.length - 1]; + return Object.assign(animation, { + effect: { + getKeyframes: () => entry.keyframes, + setKeyframes: (next: Keyframe[]) => { + entry.keyframes = next; + }, + }, + }); + }; + } + + /** A row that showed 40 px to the left as the change was read. */ + async function glidingRow() { + withFrames(); + const {area, changed, phase} = setUp( + '

    Row

    ', + ); + const row = document.getElementById('row') as HTMLElement; + placeAt(row, {before: [-40, 0, 400, 40], after: [0, 80, 400, 40]}, phase); + const layout = createAnimatedLayout(() => area); + const change = reportLayoutChange(layout, () => changed); + change.measureBefore(); + phase.current = 'after'; + change.animate(); + await flushMicrotasks(); + const glide = played.find(entry => entry.element === row); + if (glide == null) { + throw new Error('no glide'); + } + return {area, changed, row, layout, glide}; + } + + it("lands a glide's sideways part in its frames and keeps its vertical move and its animation", async () => { + const {row, glide} = await glidingRow(); + expect(translateOf(glide)).toEqual({x: -40, y: -80}); + const animation = glideOf(row); + landLayoutGlideSideways(row); + expect( + glide.keyframes.every(frame => + String(frame.translate).startsWith('0px '), + ), + ).toBe(true); + expect(translateOf(glide)).toEqual({x: 0, y: -80}); + expect(glideOf(row)).toBe(animation); + }); + + it('a later change carries only the vertical move', async () => { + const {changed, row, layout, glide} = await glidingRow(); + landLayoutGlideSideways(row); + // The change grows again, and the row moves 40 px lower. + const second = {current: 'before' as 'before' | 'after'}; + placeAt( + changed, + {before: [0, 0, 400, 80], after: [0, 0, 400, 120]}, + second, + ); + placeAt(row, {before: [0, 80, 400, 40], after: [0, 120, 400, 40]}, second); + const change = reportLayoutChange(layout, () => changed); + change.measureBefore(); + second.current = 'after'; + change.animate(); + await flushMicrotasks(); + const next = played.filter(entry => entry.element === row).at(-1); + expect(next).not.toBe(glide); + expect( + next?.keyframes.every(frame => + String(frame.translate).startsWith('0px '), + ), + ).toBe(true); + }); + + it('forgets the glide when it ends', async () => { + const {row, glide} = await glidingRow(); + landLayoutGlideSideways(row); + glide.finish?.(); + expect(glideOf(row)).toBeNull(); + }); +}); diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.ts index 88b5a29854e68..08217b76223fe 100644 --- a/packages/core/src/motion/animatedLayout.ts +++ b/packages/core/src/motion/animatedLayout.ts @@ -10,9 +10,10 @@ * 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) + * and `applyLayoutChangeTransition`. It exports `glideOf` and the glide + * landings (`landLayoutGlide`, `landLayoutGlideSideways`) too. 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. @@ -3277,6 +3278,46 @@ export function landLayoutGlide(element: Element): void { } } +/** + * Lands the sideways part of `element`'s running glide at once and keeps its + * vertical move. It changes the glide's frames, and what a later change + * carries from it, together. It is for an adopter that moves the element's + * own sideways translation onto its children between the two reads. A list + * row that a swipe left open is one. + */ +export function landLayoutGlideSideways(element: Element): void { + const glide = glides.get(element); + const effect = glide?.animation.effect as KeyframeEffect | null | undefined; + if ( + glide == null || + effect == null || + typeof effect.setKeyframes !== 'function' + ) { + return; + } + effect.setKeyframes( + effect.getKeyframes().map(({computedOffset: _, translate, ...frame}) => { + const [, y = '0px'] = String(translate ?? '').split(/\s+/); + return {...frame, translate: `0px ${y}`}; + }), + ); + const vertical: Glide = { + animation: glide.animation, + offsetAt: t => ({x: 0, y: glide.offsetAt(t).y}), + get durationMs() { + return glide.durationMs; + }, + shownBefore: {x: 0, y: glide.shownBefore.y}, + scale: glide.scale, + }; + glides.set(element, vertical); + glide.animation.addEventListener?.('finish', () => { + if (glides.get(element) === vertical) { + glides.delete(element); + } + }); +} + /** * @internal The motion a change in `area` plays, for tests and for SideNav's * rail motion, which plays on the same clock (`component:SideNav` FR6). From b3c5245d8b98dca8fc5a1507cd70658ff32a0dad Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 6 Nov 2026 15:36:47 -0800 Subject: [PATCH 08/10] fix(List): a leaving row keeps its old index among the staying rows A removed row still exiting travelled with the row that came after it as it left, when that row moved. Each row that leaves, and each row still leaving, now goes after as many staying rows as came before it, so it stays where it showed whichever rows move around it. One pass over the rows replaces the put-back anchor and the later correction. --- .../ListUpdates.interaction.browser.spec.ts | 182 ++++++++++++------ .../core/src/List/listLayoutUpdates.test.tsx | 35 +++- packages/core/src/List/listLayoutUpdates.ts | 154 +++++++-------- 3 files changed, 218 insertions(+), 153 deletions(-) diff --git a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts index fc6bf7b380fb0..2e1b9b067c198 100644 --- a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts +++ b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts @@ -910,62 +910,73 @@ test('a row swiped away lays the page out no more often than the same swipe with ); }); -test('a row swiped away and still exiting glides only down when a row moves above it, and stays before the row after it', async ({ - page, - browserName, -}) => { - test.skip( - browserName !== 'chromium', - 'the swipe is driven with Chromium touch events (CDP)', - ); +/** + * Swipes `label` away, and 30 ms into its exit presses `button`. In the frame + * after the press, it reads the rows' order and the leaving row's glides and + * top. It also returns the row's top as its exit started. + */ +async function secondChangeDuringExit( + page: Page, + label: string, + button: string, +): Promise<{ + starts: string[]; + order: string[]; + topBefore: number; + topAfter: number; +}> { await open(page, SWIPE_STORY); - const sent = row(page, 'Sent'); - await expect(sent.locator('[data-swipe-panel="trailing"]')).toBeAttached(); - const box = await sent.boundingBox(); + const target = row(page, label); + await expect(target.locator('[data-swipe-panel="trailing"]')).toBeAttached(); + const box = await target.boundingBox(); if (box == null) { throw new Error('no row'); } - // From the frame where Sent is put back for its exit, it moves Archive - // first 30 ms later. Then it records Sent's new glide and the rows' order. - await page.evaluate(() => { - (window as unknown as {__second: object | null}).__second = null; - const label = (li: Element) => { - const copy = li.cloneNode(true) as Element; - for (const panel of copy.querySelectorAll('[data-swipe-panel]')) { - panel.remove(); - } - return copy.textContent?.trim() ?? ''; - }; - const tick = () => { - const exit = document.querySelector( - '#storybook-root li[data-astryx-leaving]', - ); - if (exit == null) { - requestAnimationFrame(tick); - return; - } - setTimeout(() => { - [...document.querySelectorAll('button')] - .find(button => button.textContent?.trim() === 'Move Archive first') - ?.click(); - requestAnimationFrame(() => { - (window as unknown as {__second: unknown}).__second = { - starts: exit.getAnimations().flatMap(animation => { - const first = ( - animation.effect as KeyframeEffect | null - )?.getKeyframes()[0]?.translate; - return typeof first === 'string' ? [first] : []; - }), - order: [...document.querySelectorAll('#storybook-root li')].map( - li => - `${li.hasAttribute('data-astryx-leaving') ? 'leaving:' : ''}${label(li)}`, - ), - }; - }); - }, 30); - }; - requestAnimationFrame(tick); - }); + await page.evaluate( + ({button}) => { + (window as unknown as {__second: object | null}).__second = null; + const labelOf = (li: Element) => { + const copy = li.cloneNode(true) as Element; + for (const panel of copy.querySelectorAll('[data-swipe-panel]')) { + panel.remove(); + } + return copy.textContent?.trim() ?? ''; + }; + const tick = () => { + const exit = document.querySelector( + '#storybook-root li[data-astryx-leaving]', + ); + if (exit == null) { + requestAnimationFrame(tick); + return; + } + const topBefore = exit.getBoundingClientRect().top; + setTimeout(() => { + [...document.querySelectorAll('button')] + .find(element => element.textContent?.trim() === button) + ?.click(); + requestAnimationFrame(() => { + (window as unknown as {__second: object}).__second = { + starts: exit.getAnimations().flatMap(animation => { + const first = ( + animation.effect as KeyframeEffect | null + )?.getKeyframes()[0]?.translate; + return typeof first === 'string' ? [first] : []; + }), + order: [...document.querySelectorAll('#storybook-root li')].map( + li => + `${li.hasAttribute('data-astryx-leaving') ? 'leaving:' : ''}${labelOf(li)}`, + ), + topBefore, + topAfter: exit.getBoundingClientRect().top, + }; + }); + }, 30); + }; + requestAnimationFrame(tick); + }, + {button}, + ); const cdp = await page.context().newCDPSession(page); const y = box.y + box.height / 2; const startX = box.x + box.width - 24; @@ -991,20 +1002,69 @@ test('a row swiped away and still exiting glides only down when a row moves abov ), ) .toBe(true); - const second = await page.evaluate( + return page.evaluate( () => - (window as unknown as {__second: {starts: string[]; order: string[]}}) - .__second, + ( + window as unknown as { + __second: { + starts: string[]; + order: string[]; + topBefore: number; + topAfter: number; + }; + } + ).__second, + ); +} + +test('a row swiped away and still exiting stays in its place when a row moves above it, and no glide moves it sideways', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'the swipe is driven with Chromium touch events (CDP)', + ); + const second = await secondChangeDuringExit( + page, + 'Sent', + 'Move Archive first', ); - // Archive moved above it, so it glides down a row, and nothing sideways. - expect(second.starts.length, JSON.stringify(second)).toBeGreaterThan(0); for (const start of second.starts) { expect(start.split(' ')[0], JSON.stringify(second)).toBe('0px'); } - // It stays before Drafts, the row after it as it left. - const order = second.order; - expect(order.indexOf('leaving:Sent'), JSON.stringify(second)).toBe( - order.indexOf('Drafts') - 1, + // One staying row came before it, so it stays second, where it showed. + expect(second.order.indexOf('leaving:Sent'), JSON.stringify(second)).toBe(1); + expect(second.topAfter, JSON.stringify(second)).toBeCloseTo( + second.topBefore, + 0, + ); + await expect(leaving(page)).toHaveCount(0, {timeout: 3000}); +}); + +test('a row swiped away and still exiting stays in its place when the row after it moves', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'the swipe is driven with Chromium touch events (CDP)', + ); + const second = await secondChangeDuringExit( + page, + 'Drafts', + 'Move Archive first', + ); + expect(second.order, JSON.stringify(second)).toEqual([ + 'Archive', + 'Inbox', + 'leaving:Drafts', + 'Sent', + 'Notes', + ]); + expect(second.topAfter, JSON.stringify(second)).toBeCloseTo( + second.topBefore, + 0, ); await expect(leaving(page)).toHaveCount(0, {timeout: 3000}); }); diff --git a/packages/core/src/List/listLayoutUpdates.test.tsx b/packages/core/src/List/listLayoutUpdates.test.tsx index 0085b72b987b1..c72e8512e3c87 100644 --- a/packages/core/src/List/listLayoutUpdates.test.tsx +++ b/packages/core/src/List/listLayoutUpdates.test.tsx @@ -549,7 +549,7 @@ describe('List row updates through animatedLayout', () => { ).toEqual(['Sent', 'Drafts']); }); - it('a reorder while a removed row still exits keeps that row where it was, beside the row after it', async () => { + it('a reorder while a removed row still exits keeps that row at its place among the rows that stay', async () => { render(); await change(['Inbox', 'Drafts', 'Archive', 'Spam']); // Sent still exits, before Drafts. @@ -557,11 +557,32 @@ describe('List row updates through animatedLayout', () => { 'Sent', ); // React moves only its own rows, so moving Spam first would leave Sent at - // the top of the list. + // the top of the list. One staying row came before it, so it stays second. await change(['Spam', 'Inbox', 'Drafts', 'Archive']); expect( [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), - ).toEqual(['Spam', 'Inbox', 'Sent', 'Drafts', 'Archive']); + ).toEqual(['Spam', 'Sent', 'Inbox', 'Drafts', 'Archive']); + }); + + it('a removed row that still exits stays in its place when the row after it moves, or the row before it', async () => { + render(); + await change(['Inbox', 'Drafts', 'Archive', 'Spam']); + await change(['Drafts', 'Inbox', 'Archive', 'Spam']); + expect( + [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), + ).toEqual(['Drafts', 'Sent', 'Inbox', 'Archive', 'Spam']); + await change(['Inbox', 'Archive', 'Spam', 'Drafts']); + expect( + [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), + ).toEqual(['Inbox', 'Sent', 'Archive', 'Spam', 'Drafts']); + }); + + it('a removal and a move in one update: the removed row comes back at its place among the rows that stay', async () => { + render(); + await change(['Drafts', 'Inbox']); + expect( + [...document.querySelectorAll('li')].map(row => row.textContent?.trim()), + ).toEqual(['Drafts', 'Sent', 'Inbox']); }); it('a removed last row that still exits stays last when the rows before it move, and new rows still land after it', async () => { @@ -792,7 +813,7 @@ describe('List row updates through animatedLayout', () => { expect(log.slice(commit, settle), log.join(' ')).not.toContain('read'); }); - it('a swiped row that leaves while the same update moves it down glides down with the rows around it, never sideways', async () => { + it('a swiped row that leaves while the same update moves it up glides up with the rows around it, never sideways', async () => { // jsdom has no DOMMatrix: a 2D one, enough for a translation. class Matrix { a = 1; @@ -831,14 +852,14 @@ describe('List row updates through animatedLayout', () => { li => li.textContent === 'Drafts', ); drafts?.style.setProperty('transform', 'translate(-40px, 0px)'); - // Drafts leaves, and a row inserted above it moves it a row down. - await change(['New', 'Inbox', 'Sent', 'Archive']); + // Drafts leaves, and Inbox above it leaves too, so it moves a row up. + await change(['Sent', 'Archive']); const glide = played.find( entry => entry.element === drafts && String(entry.keyframes[0]?.translate ?? '') !== '', ); - expect(String(glide?.keyframes[0]?.translate)).toBe(`0px ${-ROW}px`); + expect(String(glide?.keyframes[0]?.translate)).toBe(`0px ${ROW}px`); expect(glide?.isCancelled).not.toBe(true); // It exits settled: its box in the list, its content still swiped. expect(drafts?.style.transform).toBe('none'); diff --git a/packages/core/src/List/listLayoutUpdates.ts b/packages/core/src/List/listLayoutUpdates.ts index 158cc86663925..df3f8d2f6af1a 100644 --- a/packages/core/src/List/listLayoutUpdates.ts +++ b/packages/core/src/List/listLayoutUpdates.ts @@ -73,6 +73,8 @@ interface Measured { readonly changes: ReadonlyArray; /** Near rows with a translation of their own, read before the commit. */ readonly translations: ReadonlyArray; + /** The list's keyed and leaving rows before the commit, in order. */ + readonly sequence: ReadonlyArray; } /** @@ -187,34 +189,37 @@ export function keepPresentation(row: HTMLElement): void { } /** - * Puts a row that left back where it was for its exit, before `anchor`, the - * nearest later row in the list. It shows what it showed as it left. The - * exit makes it inert. Until then it is marked as leaving and hidden from - * assistive technology, so no later commit counts it as a row. + * The rows of `list` in order: its keyed rows and the rows still leaving. Each + * leaving row's place is counted against the keyed rows around it. */ +function rowSequence(list: HTMLElement): HTMLElement[] { + const rows: HTMLElement[] = []; + for (const child of list.children) { + if ( + child instanceof HTMLElement && + (isLeaving(child) || itemKeyOf(child) != null) + ) { + rows.push(child); + } + } + return rows; +} + /** - * Where each leaving row came back: before the nearest later row as it left. - * A row that left at the list's end stays after the rows the list had then. + * Marks a row that left as leaving. The exit makes it inert. Until then it is + * hidden from assistive technology, so no later commit counts it as a row. */ -const leavingPlaces = new WeakMap< - HTMLElement, - {readonly before: Element | null; readonly after: ReadonlySet} ->(); - -function putBack( - element: HTMLElement, - list: HTMLElement, - anchor: HTMLElement | null, -): void { +function markLeavingRow(element: HTMLElement): void { markLeaving(element); element.setAttribute('aria-hidden', 'true'); - list.insertBefore(element, anchor); - leavingPlaces.set(element, { - before: anchor, - after: new Set(anchor == null ? list.children : []), - }); - // Back in the document, its parts' animations would apply again over what - // they showed as it left: stop them, and show what was on screen. +} + +/** + * After a row that left is back in the document, its parts' animations would + * apply again over what they showed as it left. This stops them, so it shows + * what was on screen. + */ +function showAsItLeft(element: HTMLElement): void { if (typeof element.getAnimations === 'function') { for (const animation of element.getAnimations({subtree: true})) { animation.cancel(); @@ -227,49 +232,23 @@ function putBack( } /** - * Puts each leaving row back where it came back. React moves only its own - * rows. So a commit that moves rows can carry a leaving row away from its - * place, such as to the top of the list. + * Puts `rows` right before `anchor`, or at the list's end when it is null, in + * their order. A row already in its place stays where it is. */ -function keepLeavingInPlace(list: HTMLElement): void { - const rows = [...list.children].filter( - (child): child is HTMLElement => - child instanceof HTMLElement && isLeaving(child), - ); - // A row can come back beside another leaving row, which a pass may move - // first: one pass per row is enough. - for (let pass = 0; pass < rows.length; pass++) { - let isMoved = false; - for (const row of rows) { - const place = leavingPlaces.get(row); - if (place == null) { - continue; - } - if (place.before != null) { - if ( - place.before.parentElement === list && - row.nextElementSibling !== place.before - ) { - list.insertBefore(row, place.before); - isMoved = true; - } - continue; - } - // At the end: after the last row the list had as it left. - let last: Element | null = null; - for (const child of list.children) { - if (child !== row && place.after.has(child)) { - last = child; - } - } - if (last != null && row.previousElementSibling !== last) { - list.insertBefore(row, last.nextElementSibling); - isMoved = true; - } - } - if (!isMoved) { - break; +function placeBefore( + list: HTMLElement, + rows: ReadonlyArray, + anchor: HTMLElement | null, +): void { + let next = anchor; + for (let index = rows.length - 1; index >= 0; index--) { + const row = rows[index]; + const before = + next == null ? list.lastElementChild : next.previousElementSibling; + if (before !== row) { + list.insertBefore(row, next); } + next = row; } } @@ -462,6 +441,7 @@ export function useListLayoutUpdates( reported: new Set([target]), changes: [change], translations: [], + sequence: rowSequence(list), }; reportedRows.set(list, measuredRef.current.reported); return; @@ -513,6 +493,7 @@ export function useListLayoutUpdates( reported: new Set(targets), changes, translations, + sequence: rowSequence(list), }; reportedRows.set(list, measuredRef.current.reported); }, [animatedLayout, listRef]); @@ -531,7 +512,6 @@ export function useListLayoutUpdates( if (measured == null || list == null || animatedLayout == null) { return; } - keepLeavingInPlace(list); const now = keyedRows(list); const order = [...now.keys()]; if ( @@ -542,31 +522,36 @@ export function useListLayoutUpdates( // is dropped by the next frame). return; } - // Each row that left comes back before the nearest later row in the - // list. One pass runs from the end, and a row put back is the next one's - // anchor. + // Each row that left, and each row still leaving, keeps its place: after + // as many staying rows as came before it. React moves only its own rows, + // so this also keeps a leaving row in place when the rows around it move. + const current = [...now.values()]; + const staying = new Set(current); + const places = new Map(); const leaving: HTMLElement[] = []; - let anchor: HTMLElement | null = null; - for (let index = measured.order.length - 1; index >= 0; index--) { - const key = measured.order[index]; - const staying = now.get(key); - if (staying != null) { - anchor = staying; + let before = 0; + for (const element of measured.sequence) { + if (staying.has(element)) { + before += 1; continue; } - // Only a row the module measured can exit; any other went with the - // commit (it was out of view). - const element = measured.rows.get(key); - if (element != null && measured.reported.has(element)) { - putBack(element, list, anchor); + if (!isLeaving(element)) { + // Only a row the module measured can exit; any other went with the + // commit (it was out of view). + if (!measured.reported.has(element)) { + continue; + } + markLeavingRow(element); leaving.push(element); - anchor = element; } + const anchor = current[before] ?? null; + places.set(anchor, [...(places.get(anchor) ?? []), element]); + } + for (const [anchor, rows] of places) { + placeBefore(list, rows, anchor); } - // A row that left now may be one an earlier leaving row came back - // before. - if (leaving.length > 0) { - keepLeavingInPlace(list); + for (const element of leaving) { + showAsItLeft(element); } for (const change of measured.changes) { change.animate(); @@ -601,7 +586,6 @@ export function useListLayoutUpdates( } // A row that appeared in view enters (the module plays an entrance only // in view): the rows in view are found by halving again. - const current = [...now.values()]; const height = list.ownerDocument.defaultView?.innerHeight ?? 0; const shown = rowsMeeting(current, 0, height); if (shown != null) { From 69b0b44b621fd88f820336296f95e162c75970c5 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 6 Nov 2026 16:44:23 -0800 Subject: [PATCH 09/10] fix(List): a crossing row is marked after the module reads the layout markCrossings set the travelling mark between the list's row reads and the module's batched read, so a reorder with a crossing row restyled and laid out the page again in its commit. It now sets the marks in the microtask it already queues, after the module's read and before the frame paints, and marks only a row that has a glide. A mark's end clears only its own mark, so a second reorder while a row rides keeps the new mark until the new glide ends. --- .../ListUpdates.interaction.browser.spec.ts | 70 +++++++++++++++++++ .../core/src/List/listLayoutUpdates.test.tsx | 69 ++++++++++++++++++ packages/core/src/List/listLayoutUpdates.ts | 19 +++-- .../privateAttributes/travelling.stylex.ts | 18 ++++- 4 files changed, 164 insertions(+), 12 deletions(-) diff --git a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts index 2e1b9b067c198..6730a8f181474 100644 --- a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts +++ b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts @@ -742,6 +742,76 @@ test('a row swiped away with a removal action exits in place as it was on screen await expect(leaving(page)).toHaveCount(0, {timeout: 3000}); }); +/** + * Presses `button` with a click that has no pointer. It counts the style + * recalculations and layouts in that task: the click, React's commit and the + * microtasks after it, before the next frame. With `isMarkSkipped`, no row is + * marked to ride above others. It also says whether a row rides then. + */ +async function workInPress( + page: Page, + button: string, + isMarkSkipped: boolean, +): Promise<{work: number; isRiding: boolean}> { + let press = {from: 0, to: 0, isRiding: false}; + const trace = await traceRendering(page, async () => { + press = await page.evaluate( + async ({name, skip}) => { + const target = [...document.querySelectorAll('button')].find( + element => element.textContent?.trim() === name, + ); + const setAttribute = Element.prototype.setAttribute; + if (skip) { + Element.prototype.setAttribute = function (key, value) { + if (key !== 'data-astryx-travelling') { + setAttribute.call(this, key, value); + } + }; + } + const from = performance.timeOrigin + performance.now(); + target?.click(); + // Resolved promises keep the task open, so no frame runs meanwhile. + for (let hop = 0; hop < 8; hop++) { + await Promise.resolve(); + } + const to = performance.timeOrigin + performance.now(); + Element.prototype.setAttribute = setAttribute; + return { + from, + to, + isRiding: + document.querySelector( + '#storybook-root li[data-astryx-travelling]', + ) != null, + }; + }, + {name: button, skip: isMarkSkipped}, + ); + }); + const counts = countBetween(trace, press.from, press.to); + return { + work: (counts.UpdateLayoutTree ?? 0) + (counts.Layout ?? 0), + isRiding: press.isRiding, + }; +} + +test('a reorder with a row riding across others restyles and lays out the page in its commit no more often than with no row marked to ride', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'Chromium traces layouts through CDP'); + await open(page); + const skipped = await workInPress(page, 'Move the last row first', true); + await open(page); + const marked = await workInPress(page, 'Move the last row first', false); + expect(skipped.isRiding).toBe(false); + expect(marked.isRiding).toBe(true); + expect( + marked.work, + `with the row marked: ${marked.work}; with no mark: ${skipped.work}`, + ).toBe(skipped.work); +}); + test('a change with a row swiped open lays the page out no more often than the same change with none', async ({ page, browserName, diff --git a/packages/core/src/List/listLayoutUpdates.test.tsx b/packages/core/src/List/listLayoutUpdates.test.tsx index c72e8512e3c87..49cc5e49d8b80 100644 --- a/packages/core/src/List/listLayoutUpdates.test.tsx +++ b/packages/core/src/List/listLayoutUpdates.test.tsx @@ -314,6 +314,75 @@ describe('List row updates through animatedLayout', () => { expect(entrances()).toEqual([]); }); + it('a crossing row is marked only after the module has read the layout of the commit', async () => { + render(); + const marked = () => + document.querySelector('li[data-astryx-travelling]') != null; + const readsWhileMarked: string[] = []; + const rect = Element.prototype.getBoundingClientRect; + Element.prototype.getBoundingClientRect = function (this: Element) { + if (marked()) { + readsWhileMarked.push(this.textContent?.trim() ?? this.tagName); + } + return rect.call(this); + }; + try { + await change(['Drafts', 'Inbox', 'Sent']); + } finally { + Element.prototype.getBoundingClientRect = rect; + } + expect(readsWhileMarked).toEqual([]); + expect(marked()).toBe(true); + }); + + it('a second reorder while a row rides keeps it marked until its new glide ends', async () => { + // As in a browser, a cancelled animation rejects its finished promise. + const animate = Element.prototype.animate; + const finishes = new Map void>(); + Element.prototype.animate = function ( + this: Element, + ...args: Parameters + ) { + const animation = animate.apply(this, args); + const cancel = animation.cancel.bind(animation); + let settle = (_isCancelled: boolean) => {}; + const finished = new Promise((resolve, reject) => { + settle = isCancelled => + isCancelled ? reject(new Error('cancelled')) : resolve(animation); + }); + finished.catch(() => undefined); + Object.assign(animation, { + finished, + cancel: () => { + cancel(); + settle(true); + }, + }); + finishes.set(animation, () => settle(false)); + return animation; + }; + try { + render(); + const drafts = () => + [...document.querySelectorAll('li')].find( + row => row.textContent?.trim() === 'Drafts', + ); + await change(['Drafts', 'Inbox', 'Sent']); + expect(drafts()).toHaveAttribute('data-astryx-travelling'); + // Drafts crosses the same rows again, back down, while it still rides. + await change(['Inbox', 'Sent', 'Drafts']); + expect(drafts()).toHaveAttribute('data-astryx-travelling'); + const glide = drafts()?.getAnimations().at(-1); + if (glide != null) { + finishes.get(glide)?.(); + } + await flushMicrotasks(); + expect(drafts()).not.toHaveAttribute('data-astryx-travelling'); + } finally { + Element.prototype.animate = animate; + } + }); + it('moving the first row last: it glides down from its old place riding above the rows it crosses, and they glide up', async () => { render(); await change(['Sent', 'Drafts', 'Spam', 'Archive', 'Inbox']); diff --git a/packages/core/src/List/listLayoutUpdates.ts b/packages/core/src/List/listLayoutUpdates.ts index df3f8d2f6af1a..4faadcbc332a8 100644 --- a/packages/core/src/List/listLayoutUpdates.ts +++ b/packages/core/src/List/listLayoutUpdates.ts @@ -333,7 +333,8 @@ function settleTranslation({ /** * Marks each row that crosses another on the longer of the two glides, for * the length of its glide, so it rides above. It reads the glides once the - * module has started them, after the commit's layout effects. One pass each + * module has started them, after the commit's layout effects. It marks the + * rows then too, after the module has read the commit's layout. One pass each * way over the rows near the visible part, in their old order, finds the rows * that cross any other. Only those are compared, so a removal or an insert, * which crosses nothing, costs the two passes. @@ -390,21 +391,19 @@ function markCrossings( if (travelling.length === 0) { return; } - const unmarks = travelling.map(element => markTravelling(element)); - // After the module's own microtask has started the glides. + // After the module's own microtask has read the layout and started the + // glides. A mark set before that read would make it lay the page out again. queueMicrotask(() => { - travelling.forEach((element, index) => { - const end = unmarks[index]; + for (const element of travelling) { const glide = typeof element.getAnimations === 'function' ? element.getAnimations().at(-1) : undefined; - if (glide == null) { - end(); - return; + if (glide != null) { + const end = markTravelling(element); + glide.finished.then(end, end); } - glide.finished.then(end, end); - }); + } }); } diff --git a/packages/core/src/privateAttributes/travelling.stylex.ts b/packages/core/src/privateAttributes/travelling.stylex.ts index fa19fd3d8e023..47d988a2e9a23 100644 --- a/packages/core/src/privateAttributes/travelling.stylex.ts +++ b/packages/core/src/privateAttributes/travelling.stylex.ts @@ -15,13 +15,27 @@ import {colorVars} from '../theme/tokens.stylex'; const TRAVELLING = 'data-astryx-travelling'; +/** + * Each row's latest mark, so the end of an earlier slide leaves a later + * mark in place. + */ +const marks = new WeakMap(); + /** * Marks `row` as sliding across rows that move the other way. Returns the - * call that removes the mark when the slide ends. + * call that removes the mark when the slide ends. A later mark on the row + * stays when that call runs. */ export function markTravelling(row: Element): () => void { + const mark = {}; + marks.set(row, mark); row.setAttribute(TRAVELLING, ''); - return () => row.removeAttribute(TRAVELLING); + return () => { + if (marks.get(row) === mark) { + marks.delete(row); + row.removeAttribute(TRAVELLING); + } + }; } export const travellingStyles = stylex.create({ From 31e1ce3b7dcaf5ce5e315f484aae7af4b7fbd30b Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Fri, 6 Nov 2026 17:28:04 -0800 Subject: [PATCH 10/10] fix(List): a travelling row keeps its surface in a list with dividers The press layer's overDividers, composed after the travelling style, also sets box-shadow, so a travelling row in a list with dividers and pressable rows lost its surface, and its label drew over the rows it crossed. The travelling style now also sets the surface as a private custom property, and overDividers keeps it in each of its shadows. Every other row resets the property, so a nested row never inherits it. --- .../ListUpdates.interaction.browser.spec.ts | 4 +++ .../src/privateAttributes/press.stylex.ts | 26 ++++++++++++++----- .../privateAttributes/travelling.stylex.ts | 11 ++++++++ 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts index 6730a8f181474..f359543ff462d 100644 --- a/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts +++ b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts @@ -272,6 +272,10 @@ test('a reorder: the row moved to the top glides up from its old place riding ab ); expect(glides.Spam, JSON.stringify(glides)).toBeCloseTo(4 * gap, 0); expect(travelling).toBe(true); + // It rides on the list's surface, in this list with dividers too. + expect(await spam.evaluate(el => getComputedStyle(el).boxShadow)).toContain( + 'inset', + ); for (const label of ['Inbox', 'Sent', 'Drafts', 'Archive']) { expect(glides[label], `${label} ${JSON.stringify(glides)}`).toBeCloseTo( -gap, diff --git a/packages/core/src/privateAttributes/press.stylex.ts b/packages/core/src/privateAttributes/press.stylex.ts index 50d45701e2d2a..2248159b2c583 100644 --- a/packages/core/src/privateAttributes/press.stylex.ts +++ b/packages/core/src/privateAttributes/press.stylex.ts @@ -81,8 +81,19 @@ const RELEASE_EASE = easeVars['--ease-exit']; const DIVIDER_WIDTH = borderVars['--border-width']; /** How far a highlighted row's tint reaches past its edge: one divider. */ const PAST_DIVIDER = `calc(-1 * ${DIVIDER_WIDTH})`; -/** A tint one divider tall, just above the row: over the row before's divider. */ -const tintAbove = (tint: string) => `0 ${PAST_DIVIDER} 0 0 ${tint}`; +/** + * The surface a travelling List row rides on (travelling.stylex.ts sets it). + * A row of a List with dividers adds it to its own shadows. + */ +const TRAVELLING_SURFACE = 'var(--_travelling-surface, none)'; +/** The same surface as one shadow in a list of them. */ +const TRAVELLING_SURFACE_LAYER = 'var(--_travelling-surface, 0 0 transparent)'; +/** + * A tint one divider tall, just above the row: over the row before's divider. + * A travelling row keeps its surface under the tint. + */ +const tintAbove = (tint: string) => + `0 ${PAST_DIVIDER} 0 0 ${tint}, ${TRAVELLING_SURFACE_LAYER}`; export const rowPressLayerStyles = stylex.create({ /** @@ -213,18 +224,19 @@ export const rowPressLayerStyles = stylex.create({ * tint. The tint also covers the divider above it, as a shadow, under a * mouse or a finger. Under a coarse pointer, the press layer covers both * dividers, so they fade with it on the release. The tint is translucent, - * so a divider under it reads as it does at rest. + * so a divider under it reads as it does at rest. Each shadow here keeps a + * travelling row's surface, which this shadow replaces otherwise. */ overDividers: { boxShadow: { - default: null, + default: TRAVELLING_SURFACE, [ENABLED]: { default: null, ':not(:first-child)': { default: null, ':active': { default: tintAbove(colorVars['--color-overlay-pressed']), - [COARSE]: 'none', + [COARSE]: TRAVELLING_SURFACE, }, [HOVER_HOVER]: { default: null, @@ -236,11 +248,11 @@ export const rowPressLayerStyles = stylex.create({ // row's own press paint, which follows the release's strength. [PRESSED_ON]: { default: tintAbove('var(--_press-paint)'), - [COARSE]: 'none', + [COARSE]: TRAVELLING_SURFACE, }, [PRESSED_FADING]: { default: tintAbove('var(--_press-paint)'), - [COARSE]: 'none', + [COARSE]: TRAVELLING_SURFACE, }, }, }, diff --git a/packages/core/src/privateAttributes/travelling.stylex.ts b/packages/core/src/privateAttributes/travelling.stylex.ts index 47d988a2e9a23..29383563123e0 100644 --- a/packages/core/src/privateAttributes/travelling.stylex.ts +++ b/packages/core/src/privateAttributes/travelling.stylex.ts @@ -57,6 +57,17 @@ export const travellingStyles = stylex.create({ default: null, '[data-astryx-travelling]:not([aria-selected="true"],[aria-current="true"])': `inset 0 0 0 100vmax ${colorVars['--color-background-surface']}`, }, + // A row of a List with dividers takes its shadow from the press layer's + // `overDividers`, composed later, which wins over the one above. So the + // surface is also a custom property, which `overDividers` adds to its own + // shadows. Every other row resets it, so a row inside a travelling row + // does not inherit it. + '--_travelling-surface': { + default: null, + '[data-astryx-travelling]:not([aria-selected="true"],[aria-current="true"])': `inset 0 0 0 100vmax ${colorVars['--color-background-surface']}`, + ':not([data-astryx-travelling]:not([aria-selected="true"],[aria-current="true"]))': + 'initial', + }, }, // A swipeable row is a stacking context at rest, since Item translates its // swipe root. So its band's own z-index orders only inside it. Under a