An open source design system that's fully customizable and agent ready
TypeScript
feat(List): animate row inserts, removals and moves through the animatedLayout handle (#8106)
Christopher Chedeau36929ac92728
diff --git a/.changeset/list-animated-layout.md b/.changeset/list-animated-layout.mdnew file mode 100644index 0000000000..f42b0aaab8--- /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.++@vjeuxdiff --git a/apps/storybook/stories/List.stories.tsx b/apps/storybook/stories/List.stories.tsxindex 8d40fa6715..34a26bdbff 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<HTMLDivElement>(null);+ const animatedLayout = useAnimatedLayout({containerRef});+ return (+ <div ref={containerRef}>+ <VStack gap={4}>+ <List animatedLayout={animatedLayout} hasDividers>+ {rows.map(label => (+ <ListItem+ key={label}+ itemKey={label}+ label={label}+ onClick={() => {}}+ />+ ))}+ </List>+ <Text data-testid="after-list">{`${rows.length} folders`}</Text>+ <Button+ label="Insert a row second"+ onClick={() => {+ setRows(current => [+ current[0],+ `Folder ${next}`,+ ...current.slice(1),+ ]);+ setNext(n => n + 1);+ }}+ />+ <Button+ label="Remove the second row"+ onClick={() =>+ setRows(current => current.filter((_, index) => index !== 1))+ }+ />+ <Button+ label="Move the last row first"+ onClick={() =>+ setRows(current => [+ current[current.length - 1],+ ...current.slice(0, -1),+ ])+ }+ />+ </VStack>+ </div>+ );+}++export const AnimatedChanges: Story = {+ render: () => <AnimatedChangesDemo />,+ 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<HTMLDivElement>(null);+ const animatedLayout = useAnimatedLayout({containerRef});+ const moveFirst = (label: string) =>+ setRows(current =>+ current.includes(label)+ ? [label, ...current.filter(row => row !== label)]+ : current,+ );+ return (+ <div ref={containerRef}>+ <List animatedLayout={animatedLayout} hasDividers>+ {rows.map(label => (+ <ListItem+ key={label}+ itemKey={label}+ label={label}+ onClick={() => {}}+ swipeActions={+ label === PLAIN_ROW+ ? undefined+ : {+ trailing: [+ {+ label: 'Delete',+ variant: 'destructive',+ hasRemoval: true,+ onActivate: () =>+ setRows(current =>+ current.filter(row => row !== label),+ ),+ },+ ],+ }+ }+ />+ ))}+ </List>+ <Button+ label="Move Archive first"+ variant="secondary"+ onClick={() => moveFirst('Archive')}+ />+ <Button+ label="Move Notes first"+ variant="secondary"+ onClick={() => moveFirst(PLAIN_ROW)}+ />+ </div>+ );+}++export const AnimatedChangesSwipe: Story = {+ render: () => <AnimatedChangesSwipeDemo />,+ 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/AST-105-animated-layout/spec.md b/docs/specs/AST-105-animated-layout/spec.mdindex b9330b3fa2..b2056314d8 100644--- a/docs/specs/AST-105-animated-layout/spec.md+++ b/docs/specs/AST-105-animated-layout/spec.md@@ -282,8 +282,8 @@ Rejected: the measured spring as the glide; a platform-measured opt-in, such asThe glide plays over `--duration-medium`, the middle of the theme's mediumdurations: 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`.diff --git a/docs/specs/components/List/List.spec.md b/docs/specs/components/List/List.spec.mdindex 21e244b949..5f9e3ce2db 100644--- a/docs/specs/components/List/List.spec.md+++ b/docs/specs/components/List/List.spec.md@@ -17,6 +17,8 @@ verified_by:packages/core/src/List/ListItem.hitArea.test.tsx,packages/core/src/List/__tests__/ListTouchHitArea.interaction.browser.spec.ts,packages/core/src/List/__tests__/ListDividers.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,@@ -52,7 +54,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 `<li>` 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), and every pointer keeps a highlighted row's dividers visible (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.mdindex 7f99b78f3f..8ab0bb88cd 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 `<li>` 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 `<li>`, 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 thanan 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, sodiff --git a/packages/core/api-report.md b/packages/core/api-report.mdindex a491733ceb..434b368dea 100644--- a/packages/core/api-report.md+++ b/packages/core/api-report.md@@ -1511,6 +1511,7 @@ component LinkProvider(props: LinkProviderProps)prop children: ReactNodeprop component: LinkComponentTypecomponent List(props: ListProps)+ prop animatedLayout?: AnimatedLayoutprop children: ReactNodeprop data-testid?: stringprop density?: ListDensity = 'balanced'@@ -1531,6 +1532,7 @@ component ListItem(props: ListItemProps)prop interactiveRef?: React.RefObject<HTMLElement | null>prop isDisabled?: boolean = falseprop isSelected?: boolean = false+ prop itemKey?: string | numberprop label: ReactNodeprop onClick?: (e: React.MouseEvent) => voidprop ref?: React.Ref<HTMLLIElement>diff --git a/packages/core/src/List/List.doc.mjs b/packages/core/src/List/List.doc.mjsindex dd41c8fce1..70075ff3fc 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.tsxindex 0cbcdbaf9a..8568cfa85a 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<HTMLDivElement | null>(null);+ const animatedLayout = useAnimatedLayout({containerRef});+ return (+ <div ref={containerRef}>+ <List animatedLayout={animatedLayout}>+ <ListItem label="A" itemKey="a" onClick={() => {}} />+ </List>+ </div>+ );+ }+ render(<Animated />);+ 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(<List>@@ -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.tsxindex 359d8738c2..68c4ffebff 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<HTMLUListElement & HTMLOListElement>(null);+ const measureRows = useListLayoutUpdates(listRef, animatedLayout);+ const mergedRef = useMergedRefs(+ listRef,+ ref as React.Ref<HTMLUListElement & HTMLOListElement>,+ );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 = (<Tag- ref={ref as React.Ref<HTMLUListElement & HTMLOListElement>}+ 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({</Tag>);+ // Every change of the rows is measured before it lands. LayoutChangeSnapshot+ // calls this in the commit, before the DOM changes.+ const snapshot =+ animatedLayout != null ? (+ <LayoutChangeSnapshot value={children} onBeforeChange={measureRows} />+ ) : null;+if (header == null) {- return <ListContext value={contextValue}>{listElement}</ListContext>;+ return (+ <ListContext value={contextValue}>+ {snapshot}+ {listElement}+ </ListContext>+ );}return (<ListContext value={contextValue}>+ {snapshot}<div {...stylex.props(styles.root)}><div id={headerId} {...stylex.props(styles.header)}>{header}diff --git a/packages/core/src/List/ListContext.tsx b/packages/core/src/List/ListContext.tsxindex f90cd1dfad..8f32232e4c 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<ListContextValue | null>(null);diff --git a/packages/core/src/List/ListItem.doc.mjs b/packages/core/src/List/ListItem.doc.mjsindex 74b23fd4b9..52a2267180 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.tsxindex 60a04b670f..1b10d8586b 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@@ -49,6 +51,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 '../internal/touchHitArea.stylex';@@ -141,6 +146,14 @@ export interface ListItemProps extends BaseProps<HTMLLIElement> {*/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`@@ -212,13 +225,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',@@ -374,6 +380,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.*@@ -400,6 +425,7 @@ export function ListItem({rel,isDisabled = false,isSelected = false,+ itemKey,align,xstyle,className,@@ -416,7 +442,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 `<li>`, never a link.@@ -503,12 +529,13 @@ export function ListItem({[listStyle === 'decimal' && styles.numberColumns,hasMarkers && styles.withCounter,+ travellingStyles.row,hasDividers && styles.withDivider,hasDividers && embeddedStyles.noRadius,hasDividers && isTouchTarget && rowPressLayerStyles.overDividers,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,@@ -516,6 +543,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.tsnew file mode 100644index 0000000000..f359543ff4--- /dev/null+++ b/packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts@@ -0,0 +1,1213 @@+// 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<Record<string, unknown>[][]>> {+ await page.evaluate(() => {+ const w = window as unknown as {+ __madeAnimations?: Record<string, unknown>[][];+ };+ w.__madeAnimations = [];+ const animate = Element.prototype.animate;+ Element.prototype.animate = function (+ this: Element,+ ...args: Parameters<Element['animate']>+ ) {+ 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<string, unknown>[][]})+ .__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<string, number>; 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<string, number> = {};+ 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<number[]> {+ 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<number> {+ 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<T>(+ browser: Browser,+ run: (page: Page) => Promise<T>,+): Promise<T> {+ 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);+ // 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,+ 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<HTMLElement>(+ '#storybook-root li[data-astryx-leaving]',+ );+ const after = document.querySelector<HTMLElement>('#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<HTMLElement>(+ '#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<HTMLElement>(+ ':scope > :not([data-swipe-panel])',+ );+ const panel = exit.querySelector<HTMLElement>(+ '[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});+});++/**+ * 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,+}) => {+ 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<void>(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 no more often than 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, 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;+ const tick = () => {+ const exit = document.querySelector(+ '#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 &&+ !String(frame.translate).startsWith('0px'),+ ),+ ).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,+ );+});++/**+ * 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 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');+ }+ 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;+ 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);+ return page.evaluate(+ () =>+ (+ 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',+ );+ for (const start of second.starts) {+ expect(start.split(' ')[0], JSON.stringify(second)).toBe('0px');+ }+ // 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});+});++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<HTMLElement>(+ ':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.tsxnew file mode 100644index 0000000000..49cc5e49d8--- /dev/null+++ b/packages/core/src/List/listLayoutUpdates.test.tsx@@ -0,0 +1,999 @@+// 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;+ keyframes: Keyframe[];+ readonly animation: Animation;+ isCancelled?: boolean;+ finishers?: (() => void)[];+}++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);+ }+ // 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);+ }+ 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 entry = {+ element: this,+ keyframes: keyframes as Keyframe[],+ } as Played;+ const animation = {+ cancel: () => {+ entry.isCancelled = true;+ },+ addEventListener: (type: string, listener: () => void) => {+ if (type === 'finish') {+ (entry.finishers ??= []).push(listener);+ }+ },+ finished: new Promise(() => undefined),+ currentTime: 0,+ effect: {+ getKeyframes: () => entry.keyframes,+ setKeyframes: (next: Keyframe[]) => {+ entry.keyframes = next;+ },+ },+ } as unknown as Animation;+ played.push(Object.assign(entry, {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<string, number> {+ const out = new Map<string, number>();+ 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;+ // 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])),+ );+ }+ return out;+}++/** 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 ||+ (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({+ initial,+ withHandle = true,+ keyed = true,+ listStyle,+}: {+ initial: string[];+ withHandle?: boolean;+ keyed?: boolean;+ listStyle?: React.CSSProperties;+}) {+ const containerRef = useRef<HTMLDivElement>(null);+ const animatedLayout = useAnimatedLayout({containerRef});+ const [rows, set] = useState(initial);+ setRows = set;+ return (+ <div id="area" ref={containerRef}>+ <List+ animatedLayout={withHandle ? animatedLayout : undefined}+ style={listStyle}>+ {rows.map(label => (+ <ListItem+ key={label}+ itemKey={keyed ? label : undefined}+ label={label}+ />+ ))}+ </List>+ <div id="after">After</div>+ </div>+ );+}++/** Keyed rows, then one row without an itemKey. */+function Mixed({initial}: {initial: string[]}) {+ const containerRef = useRef<HTMLDivElement>(null);+ const animatedLayout = useAnimatedLayout({containerRef});+ const [rows, set] = useState(initial);+ setRows = set;+ return (+ <div id="area" ref={containerRef}>+ <List animatedLayout={animatedLayout}>+ {rows.map(label => (+ <ListItem key={label} itemKey={label} label={label} />+ ))}+ <ListItem key="note" label="Note" />+ </List>+ </div>+ );+}++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(<Demo initial={['Inbox', 'Sent', 'Drafts']} />);+ 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(<Demo initial={['Inbox', 'Sent', 'Drafts']} />);+ 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('a crossing row is marked only after the module has read the layout of the commit', async () => {+ render(<Demo initial={['Inbox', 'Sent', 'Drafts']} />);+ 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<Animation, () => void>();+ Element.prototype.animate = function (+ this: Element,+ ...args: Parameters<Element['animate']>+ ) {+ const animation = animate.apply(this, args);+ const cancel = animation.cancel.bind(animation);+ let settle = (_isCancelled: boolean) => {};+ const finished = new Promise<Animation>((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(<Demo initial={['Inbox', 'Sent', 'Drafts']} />);+ 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(<Demo initial={['Inbox', 'Sent', 'Drafts', 'Spam', 'Archive']} />);+ 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(+ <StrictMode>+ <Demo initial={['Inbox', 'Sent']} />+ </StrictMode>,+ );+ 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',+ );+ 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<HTMLDivElement>(null);+ const animatedLayout = useAnimatedLayout({containerRef});+ const [rows, set] = useState(initial);+ const [, setTick] = useState(0);+ setRows = set;+ rerender = () => setTick(tick => tick + 1);+ return (+ <div id="area" ref={containerRef}>+ <List animatedLayout={animatedLayout}>+ {rows.map(label => (+ // A callback ref written inline is a new ref on each render.+ <ListItem+ key={label}+ itemKey={label}+ label={label}+ ref={() => undefined}+ />+ ))}+ </List>+ </div>+ );+ }+ render(<WithRowRefs initial={['Inbox', 'Sent', 'Drafts']} />);+ 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. 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('');+ 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(+ <StrictMode>+ <Demo initial={['Inbox', 'Sent', 'Drafts']} />+ </StrictMode>,+ );+ 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(<Demo initial={['Inbox', 'Sent', 'Drafts']} />);+ 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(conceals(leaving)).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(+ <Demo+ initial={['Inbox', 'Sent', 'Drafts']}+ listStyle={{overflowY: 'auto'}}+ />,+ );+ 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<HTMLDivElement>(null);+ const animatedLayout = useAnimatedLayout({containerRef});+ handle = animatedLayout;+ return (+ <div ref={containerRef}>+ <List animatedLayout={animatedLayout}>+ <Probe />+ </List>+ </div>+ );+ }+ render(<WithHandle />);+ expect(handle).not.toBeNull();+ expect(seen).toBe(handle);+ render(+ <List>+ <Probe />+ </List>,+ );+ expect(seen).toBeUndefined();+ });++ it('removing two adjacent rows: both come back in their places, in order', async () => {+ render(<Demo initial={['Inbox', 'Sent', 'Drafts', 'Archive']} />);+ 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('a reorder while a removed row still exits keeps that row at its place among the rows that stay', async () => {+ render(<Demo initial={['Inbox', 'Sent', 'Drafts', 'Archive', 'Spam']} />);+ 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. 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', '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(<Demo initial={['Inbox', 'Sent', 'Drafts', 'Archive', 'Spam']} />);+ 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(<Demo initial={['Inbox', 'Sent', 'Drafts']} />);+ 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 () => {+ render(<Demo initial={['Inbox', 'Sent', 'Drafts']} />);+ 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(<Demo initial={labels} />);+ // 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<number> {+ const labels = Array.from({length}, (_, index) => `Row ${index}`);+ const {unmount} = render(<Demo initial={labels} />);+ 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(<Demo initial={labels} />);+ 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(<Demo initial={labels} />);+ // 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);+ });+ });++ /**+ * 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<string[]> {+ // 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(<Demo initial={initial} />);+ for (const label of swiped) {+ 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 rows = new WeakSet<CSSStyleDeclaration>();+ for (const row of document.querySelectorAll('li')) {+ 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' && rows.has(this)) {+ log.push('settle');+ }+ setProperty.call(this, name, value, priority);+ },+ );+ try {+ await change(next);+ } finally {+ Element.prototype.getBoundingClientRect = rect;+ vi.unstubAllGlobals();+ }+ 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 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;+ 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(<Demo initial={['Inbox', 'Sent', 'Drafts', 'Archive']} />);+ const drafts = [...document.querySelectorAll('li')].find(+ li => li.textContent === 'Drafts',+ );+ drafts?.style.setProperty('transform', 'translate(-40px, 0px)');+ // 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(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(<Demo initial={['Inbox', 'Sent']} />);+ 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(<Demo initial={['Inbox', 'Sent', 'Drafts']} withHandle={false} />);+ 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(<Demo initial={['Inbox', 'Sent', 'Drafts']} keyed={false} />);+ 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(<Demo initial={[]} />);+ 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(<Mixed initial={[]} />);+ 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(<Mixed initial={['Inbox', 'Sent']} />);+ 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.tsnew file mode 100644index 0000000000..4faadcbc33--- /dev/null+++ b/packages/core/src/List/listLayoutUpdates.ts@@ -0,0 +1,603 @@+// 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,+ landLayoutGlideSideways,+ 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<Element, ReadonlySet<Element>>();++/** 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<string, HTMLElement>;+ readonly order: ReadonlyArray<string>;+ /**+ * 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<string, number>;+ readonly near: readonly [number, number] | null;+ /** The rows reported to the module, the only ones whose exit it holds. */+ readonly reported: ReadonlySet<HTMLElement>;+ readonly changes: ReadonlyArray<LayoutChange>;+ /** Near rows with a translation of their own, read before the commit. */+ readonly translations: ReadonlyArray<Translation>;+ /** The list's keyed and leaving rows before the commit, in order. */+ readonly sequence: ReadonlyArray<HTMLElement>;+}++/**+ * 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<HTMLElement>,+ 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<string, HTMLElement> {+ const rows = new Map<string, HTMLElement>();+ 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<readonly [HTMLElement | SVGElement, string]>+>();++/**+ * 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<HTMLElement | SVGElement>('*')];+ 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);+}++/**+ * 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;+}++/**+ * 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.+ */+function markLeavingRow(element: HTMLElement): void {+ markLeaving(element);+ element.setAttribute('aria-hidden', 'true');+}++/**+ * 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();+ }+ }+ for (const [part, cssText] of keptStyles.get(element) ?? []) {+ part.style.cssText = cssText;+ }+ keptStyles.delete(element);+}++/**+ * 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 placeBefore(+ list: HTMLElement,+ rows: ReadonlyArray<HTMLElement>,+ 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;+ }+}++/** 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<HTMLElement | SVGElement>;+ readonly transforms: ReadonlyArray<string>;+}++/**+ * Reads a row's own translation, such as a swipe's, and its children's+ * transforms before the commit. Returns null when the row has none.+ */+function readTranslation(row: HTMLElement): Translation | 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,+ );+ 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. 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,+ x,+ y,+ children,+ transforms,+}: Translation): void {+ row.style.setProperty('transform', 'none');+ children.forEach((child, index) => {+ const current = transforms[index];+ const shift = new view.DOMMatrix().translate(x, y);+ const moved =+ current === '' || current === 'none'+ ? shift+ : shift.multiply(new view.DOMMatrix(current));+ child.style.setProperty('transform', moved.toString());+ });+}++/**+ * 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. 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.+ */+function markCrossings(+ measured: Measured,+ now: ReadonlyMap<string, HTMLElement>,+): 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<HTMLElement>();+ 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;+ }+ // 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(() => {+ for (const element of travelling) {+ const glide =+ typeof element.getAnimations === 'function'+ ? element.getAnimations().at(-1)+ : undefined;+ if (glide != null) {+ const end = markTravelling(element);+ 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<HTMLElement | null>,+ animatedLayout: AnimatedLayout | undefined,+): () => void {+ const measuredRef = useRef<Measured | null>(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],+ translations: [],+ sequence: rowSequence(list),+ };+ 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 translations: Translation[] = [];+ const tops = new Map<string, number>();+ if (near != null) {+ // 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();+ tops.set(order[index], top - (translation?.y ?? 0));+ if (translation != null) {+ translations.push(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+ // 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,+ translations,+ sequence: rowSequence(list),+ };+ 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);+ 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, 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<HTMLElement | null, HTMLElement[]>();+ const leaving: HTMLElement[] = [];+ let before = 0;+ for (const element of measured.sequence) {+ if (staying.has(element)) {+ before += 1;+ continue;+ }+ 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);+ }+ const anchor = current[before] ?? null;+ places.set(anchor, [...(places.get(anchor) ?? []), element]);+ }+ for (const [anchor, rows] of places) {+ placeBefore(list, rows, anchor);+ }+ for (const element of leaving) {+ showAsItLeft(element);+ }+ 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+ // 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) {+ landLayoutGlideSideways(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+ // 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 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.tsindex 4c06e979f8..040c11428b 100644--- a/packages/core/src/motion/animatedLayout.boundary.test.ts+++ b/packages/core/src/motion/animatedLayout.boundary.test.ts@@ -160,6 +160,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/motion/animatedLayout.test.ts b/packages/core/src/motion/animatedLayout.test.tsindex 2f53bf7eb2..2323f2a2f4 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<Element['animate']>+ ) {+ 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(+ '<div id="area"><div id="changed"></div><p id="row">Row</p></div>',+ );+ 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.tsindex 03c4360ad3..56198c48a4 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.@@ -3636,6 +3637,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).diff --git a/packages/core/src/privateAttributes/itemKey.stylex.ts b/packages/core/src/privateAttributes/itemKey.stylex.tsnew file mode 100644index 0000000000..00edf0aac8--- /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<Record<string, string>> {+ 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.tsnew file mode 100644index 0000000000..37e43789be--- /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/press.stylex.ts b/packages/core/src/privateAttributes/press.stylex.tsindex 50d45701e2..2248159b2c 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.tsnew file mode 100644index 0000000000..2938356312--- /dev/null+++ b/packages/core/src/privateAttributes/travelling.stylex.ts@@ -0,0 +1,88 @@+// 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';++/**+ * Each row's latest mark, so the end of an earlier slide leaves a later+ * mark in place.+ */+const marks = new WeakMap<Element, object>();++/**+ * Marks `row` as sliding across rows that move the other way. Returns the+ * 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 () => {+ if (marks.get(row) === mark) {+ marks.delete(row);+ 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 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+ // 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,+ },+ },+ },+});