An open source design system that's fully customizable and agent ready
TypeScript
feat(core): the animated-layout glide moves the siblings before a change too, and its walk stops near the visible part (#8634)
Cindy Zhang0418c4705b24
diff --git a/.changeset/animated-layout-adopters.md b/.changeset/animated-layout-adopters.mdindex 0c8e9ef99d..86d0e6ac1b 100644--- a/.changeset/animated-layout-adopters.md+++ b/.changeset/animated-layout-adopters.md@@ -2,6 +2,6 @@'@astryxdesign/core': patch----[feature] `useAnimatedLayout({containerRef})` returns a handle that Collapsible and TreeList take as their new `animatedLayout` prop (`spec:AST-105`). When one of them opens or closes, the content after it inside that container glides to its new place instead of jumping, the revealed content reveals, closing content conceals before it hides, and the chevron turns, all on one shared motion, under every pointer, a mouse included. Fixed and stuck sticky elements stay put, the glide never scrolls the container, and under Reduce Motion the change cross-fades on touch and happens at once with a mouse. A single-mode CollapsibleGroup glides every item it changes. Without the prop, nothing changes.+[feature] `useAnimatedLayout({containerRef})` returns a handle that Collapsible and TreeList take as their new `animatedLayout` prop (`spec:AST-105`). When one of them opens or closes, the content around it inside that container (after it, and before it where the layout centers or end-aligns it) glides to its new place instead of jumping, the revealed content reveals, closing content conceals before it hides, and the chevron turns, all on one shared motion, under every pointer, a mouse included. Fixed and stuck sticky elements stay put, the glide never scrolls the container, and under Reduce Motion the change cross-fades on touch and happens at once with a mouse. A single-mode CollapsibleGroup glides every item it changes. Without the prop, nothing changes.@cixzhangdiff --git a/.changeset/animated-layout-earlier-siblings.md b/.changeset/animated-layout-earlier-siblings.mdnew file mode 100644index 0000000000..a16e6bca2b--- /dev/null+++ b/.changeset/animated-layout-earlier-siblings.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] With an `animatedLayout` handle, content before a Collapsible or TreeList change glides too where the layout moves it: an item before the change in a centered, end-aligned or space-between row, a sibling `order` places after it, and the card around a change in a centered column. Inside a positioned, stuck sticky or top-layer ancestor of the change, only the content after the change moves: that ancestor, the wrappers inside it and the content before the change take their final place at once.++@cixzhangdiff --git a/apps/storybook/stories/AnimatedLayout.stories.tsx b/apps/storybook/stories/AnimatedLayout.stories.tsxindex f6f00bae3b..994f1cbe07 100644--- a/apps/storybook/stories/AnimatedLayout.stories.tsx+++ b/apps/storybook/stories/AnimatedLayout.stories.tsx@@ -267,3 +267,47 @@ export const BeforeAndAfter: Story = {</div>),};++/**+ * Content before the change moves too when the layout centers it: in a+ * vertically centered column, opening the Collapsible moves the card above it+ * up as much as the card below it moves down.+ */+function CenteredDemo() {+ const containerRef = useRef<HTMLDivElement>(null);+ const animatedLayout = useAnimatedLayout({containerRef});+ return (+ <div style={{maxWidth: 520}}>+ <ScrollableArea ref={containerRef} height={420} label="Centered column">+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ justifyContent: 'center',+ minHeight: 400,+ padding: 12,+ boxSizing: 'border-box',+ }}>+ <div style={plain}>Before the change (moves up)</div>+ <div style={card}>+ <Collapsible+ trigger="Shipping details"+ defaultIsOpen={false}+ animatedLayout={animatedLayout}>+ <p style={{margin: '4px 0'}}>Ships in 2 business days.</p>+ <p style={{margin: '4px 0'}}>Free returns for 30 days.</p>+ <p style={{margin: '4px 0'}}>Tracking arrives by email.</p>+ </Collapsible>+ </div>+ <div style={plain}>After the change (moves down)</div>+ </div>+ </ScrollableArea>+ </div>+ );+}++/** A centered column: the content before the change glides too. */+export const CenteredColumn: Story = {+ name: 'Centered column',+ render: () => <CenteredDemo />,+};diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.mdindex 415d9f4abb..edded584f6 100644--- a/docs/architecture/react-component-runtime.md+++ b/docs/architecture/react-component-runtime.md@@ -174,10 +174,20 @@ those contracts.through the shared rectangle morph (`architecture:layer-runtime` INV15;`spec:AST-094` FR5) once Core has that morph; until then, the module playsits own compositor translate. It never animates height. Its walk visits only- the following element siblings at each ancestor level up to the area, through- `parentElement` and `nextElementSibling`, descending only into an element- with `display: contents`, so its cost grows with depth plus following- siblings. Changes in one area in the same frame are measured together. A+ the changed element's ancestors up to the area and the element siblings on+ either side at each of their levels, through `parentElement`,+ `nextElementSibling` and `previousElementSibling`, descending only into an+ element with `display: contents`, and each level's walk stops at the first+ sibling outside the band the changes in a frame can bring into view (the+ area's visible part plus one viewport, or the changed elements' summed size+ if larger, above and below), so its cost grows with depth plus the+ siblings near the visible part, never with the length of a list. Where the+ scroll container opts out of scroll anchoring, a change above the band+ walks forward to the band; that cost grows with the distance. In a+ container whose children run across the block direction (multi-column, a+ wrapping column flex box, or a column-flow grid), the walk runs through+ that level, a cost that grows with its children. Changes in+ one area in the same frame are measured together. Acomponent reports a change through an internal, non-exported function thattakes the `useAnimatedLayout` handle, so the handle stays member-free, andeach moving element is one the page already renders, except a swap's onediff --git a/docs/specs/AST-105-animated-layout/spec.md b/docs/specs/AST-105-animated-layout/spec.mdindex 63af9edc81..e15e1de56d 100644--- a/docs/specs/AST-105-animated-layout/spec.md+++ b/docs/specs/AST-105-animated-layout/spec.md@@ -73,9 +73,11 @@ const animatedLayout = useAnimatedLayout({containerRef: scrollRef});- **FR3 — The content after a change glides within the area.** For any changea component holding the handle reports, such as a disclosure opening,content loading in, a message appearing, or an item inserted or removed,- the content after it inside the area moves from its old place to its new- one instead of jumping, at every ancestor level up to the area and never- past it. An element moves only when its layout rectangle changed and it is+ the content it shifts inside the area moves from its old place to its new+ one instead of jumping: the siblings after it, and the siblings before it+ that its layout moves (a centered, end-aligned or space-between row, or+ `order`), and its own ancestors where the layout moves them (a centered+ column), at every ancestor level up to the area and never past it. An element moves only when its layout rectangle changed and it isin the area's visible part. Which elements move is listed under Coverage.Shifted content may mix Astryx components and plain app elements, and noneof it opts in. Several changes in one area, nested or not, compose: each@@ -123,29 +125,29 @@ const animatedLayout = useAnimatedLayout({containerRef: scrollRef});What moves inside an area, each case with its test:-| Case | Behavior | Test |-| ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- |-| Normal-flow block siblings after the changed element, at each ancestor level up to the area | Moves when its rectangle changed | Nested changed element with block siblings at three levels |-| An element with `display: contents` | Has no box; its children are taken in its place | A following `display: contents` wrapper with two children |-| Absolutely positioned or fixed elements | Skipped and take their final place; an absolute child of a moving element rides with it | One of each, plus an absolute badge on a moving row |-| Sticky elements | In flow while unstuck, so moves when its rectangle changed; a stuck element takes its final place | A sticky header above and below its stuck point |-| Floats | Moves when its rectangle changed | A float after the changed element |-| Flex and grid items after the changed element, including wrap and row direction | Moves when its rectangle changed | A wrapping flex row and a row-direction neighbor that does not shift |-| Hidden, `display: none`, or zero-size elements | Skipped | One of each after the changed element |-| Changed elements outside the area's visible part | Take their final place without animation | A long list with changed rows above and below the fold |-| Elements under a scaled or transformed ancestor | Moves by its layout change, corrected for the ancestor's scale | A moving row inside a scaled panel |-| Portals and top-layer content | Never moved | A popover open from a following row |-| Elements already moving | Keep their running motion and add the new move to it | Two changes 100 ms apart |-| Nested areas | Motion stops at the area of the handle the changed component holds; an inner area moves as one unit within an outer one | An area inside an area, changed in the inner one |-| Table rows after an opening or closing detail row | The rows glide; a closing detail row hides at once, and its space is held while the rows after it glide up. A table that draws column lines (`component:Table` FR15) does not glide: it and the content after it take their final places at once | A detail row opening and closing in a table with a pinned column, and in a table with column lines |+| Case | Behavior | Test |+| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |+| Normal-flow block siblings after the changed element, at each ancestor level up to the area | Moves when its rectangle changed | Nested changed element with block siblings at three levels |+| An element with `display: contents` | Has no box; its children are taken in its place | A following `display: contents` wrapper with two children |+| Absolutely positioned or fixed elements | Skipped and take their final place; an absolute child of a moving element rides with it | One of each, plus an absolute badge on a moving row |+| Content inside an absolutely positioned, fixed, stuck sticky or top-layer ancestor of the change | Only the content after the change moves; that ancestor, the ancestors inside it and the siblings before the change take their final place | A header above a card around the change in a bottom-docked panel, and a bottom-stuck sticky footer around the change |+| Sticky elements | In flow while unstuck, so moves when its rectangle changed; a stuck element takes its final place | A sticky header above and below its stuck point |+| Floats | Moves when its rectangle changed | A float after the changed element |+| Flex and grid items after the changed element, including wrap and row direction | Moves when its rectangle changed | A wrapping flex row and a row-direction neighbor that does not shift |+| Siblings before the changed element, and its ancestors, at each level | Moves when its rectangle changed: a centered, end-aligned or space-between row, a centered column, or `order` among the siblings near the visible part moves them | A centered row, a space-between row, an end-aligned row, a centered column and an `order`-placed sibling |+| Hidden, `display: none`, or zero-size elements | Skipped | One of each after the changed element |+| Changed elements outside the area's visible part | Take their final place without animation | A long list with changed rows above and below the fold |+| Elements under a scaled or transformed ancestor | Moves by its layout change, corrected for the ancestor's scale | A moving row inside a scaled panel |+| Portals and top-layer content | Never moved | A popover open from a following row |+| Elements already moving | Keep their running motion and add the new move to it | Two changes 100 ms apart |+| Nested areas | Motion stops at the area of the handle the changed component holds; an inner area moves as one unit within an outer one | An area inside an area, changed in the inner one |+| Table rows after an opening or closing detail row | The rows glide; a closing detail row hides at once, and its space is held while the rows after it glide up. A table that draws column lines (`component:Table` FR15) does not glide: it and the content after it take their final places at once | A detail row opening and closing in a table with a pinned column, and in a table with column lines |Out of coverage, each taking its final place at once:- content outside the area, and content in another document or an iframe;- inline text and other non-replaced inline content, which cannot take atransform;-- flex or grid items earlier in the DOM that `order` places after the change,- since only content after the change in the DOM moves;- text reflowing inside a paragraph beside a float;- elements the app moves itself with its own transforms;- a closing element whose space no end margin frees (a grid item whose@@ -153,7 +155,11 @@ Out of coverage, each taking its final place at once:height): it hides at once, without its exit, and the content after ittakes its final place at once, other than a table detail row (Coverage);- an anchored popover tied to a moving element, which layer anchoring keeps- in place (`architecture:layer-runtime`).+ in place (`architecture:layer-runtime`);+- an item that `order`, or a grid placement (`grid-row`, `grid-column`, a+ named area or dense packing), brings into view from beyond the area's+ visible part plus one viewport (or the changes' size, if larger) in+ document order, which the walk does not reach.## Current-state impactdiff --git a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.tsindex 69ff68f166..c7870455d8 100644--- a/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts+++ b/packages/core/src/motion/__tests__/animatedLayout.interaction.browser.spec.ts@@ -622,6 +622,472 @@ test.describe('spec:AST-105 FR2–FR4', () => {expect(startOffset(after.first).y).toBeCloseTo(-160, 0);});+ for (const row of [+ {+ name: 'a centered row',+ justify: 'center',+ items: ['before', 'changed', 'after'],+ // The row grows by 80 px: an item before moves left by half of it.+ expectX: 40,+ },+ {+ name: 'a space-between row',+ justify: 'space-between',+ items: ['first', 'before', 'changed', 'last'],+ // Four items: the gaps shrink by a third of the growth each.+ expectX: 80 / 3,+ },+ {+ name: 'an end-aligned row',+ justify: 'flex-end',+ items: ['before', 'changed'],+ expectX: 80,+ },+ ]) {+ test(`an earlier sibling ${row.name} moves glides from its old place (spec:AST-105 Coverage)`, async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area"><div style="display: flex; justify-content: ${row.justify}; gap: 8px">+ ${row.items+ .map(+ id =>+ `<div id="${id}" style="width: 60px; height: 24px; flex: none; background: #ddd"></div>`,+ )+ .join('')}+ </div></div>`,+ );+ await change(page, {+ changed: '#changed',+ mutate: `document.querySelector('#changed').style.width = '140px'`,+ });+ const [motion] = await page.evaluate(() => window.motionOf('#before'));+ expect(motion).toBeDefined();+ expect(startOffset(motion.first).x).toBeCloseTo(row.expectX, 0);+ });+ }++ test('an earlier sibling that order places after the change glides from its old place (spec:AST-105 Coverage)', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area"><div style="display: flex; gap: 8px">+ <div id="ordered" style="order: 1; width: 60px; height: 24px; flex: none; background: #ddd"></div>+ <div id="changed" style="width: 60px; height: 24px; flex: none; background: #ddd"></div>+ </div></div>`,+ );+ await change(page, {+ changed: '#changed',+ mutate: `document.querySelector('#changed').style.width = '140px'`,+ });+ const [motion] = await page.evaluate(() => window.motionOf('#ordered'));+ expect(motion).toBeDefined();+ // First in the DOM, laid out after the change: it starts 80 px back.+ expect(startOffset(motion.first).x).toBeCloseTo(-80, 0);+ });++ for (const position of ['absolute', 'fixed']) {+ test(`a ${position} ancestor of the change takes its final place (spec:AST-105 Coverage)`, async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area">+ <div id="anchored" style="position: ${position}; left: 0; bottom: 0; width: 300px">+ <div id="grow" class="grow"></div><div class="row"></div>+ </div>+ </div>`,+ );+ await change(page);+ // Anchored at its bottom, it grows upward: its top moves, yet it never+ // glides.+ expect(await page.evaluate(() => window.motionOf('#anchored'))).toEqual(+ [],+ );+ });+ }++ test('inside a positioned ancestor only the content after the change moves: the header before it and the card around it take their final place (spec:AST-105 Coverage)', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area">+ <div style="position: absolute; left: 0; right: 0; bottom: 0">+ <div id="header" class="row"></div>+ <div id="card" style="padding: 8px; background: #eee"><div id="trigger" class="row"></div><div id="grow" class="grow"></div></div>+ <div id="footer" class="row"></div>+ </div>+ </div>`,+ );+ await change(page);+ // Docked at the bottom, the panel rises as the content opens, and+ // everything around the change takes its place at once with it, so no+ // gap opens and the revealing content never covers what is above it.+ for (const id of ['#header', '#card', '#trigger']) {+ expect(await page.evaluate(s => window.motionOf(s), id), id).toEqual([]);+ }+ });++ test('a stuck sticky footer around the change stays at the area edge (spec:AST-105 Coverage, FR7)', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area">${Array.from(+ {length: 30},+ () => '<div class="row"></div>',+ ).join(+ '',+ )}<div id="footer" style="position: sticky; bottom: 0; background: #ccc"><div id="grow" class="grow"></div><div class="row"></div></div></div>`,+ );+ await change(page);+ expect(await page.evaluate(() => window.motionOf('#footer'))).toEqual([]);+ });++ for (const reduce of [false, true]) {+ test(`a change above the visible part inside a wrapper: with scroll anchoring the rows in view and their wrapper stay put${reduce ? ' under Reduce Motion' : ''} (FR3)`, async ({+ page,+ }) => {+ if (reduce) {+ await page.emulateMedia({reducedMotion: 'reduce'});+ }+ await open(+ page,+ `<div id="area" class="area"><div id="wrapper"><div id="grow" class="grow"></div>${Array.from(+ {length: 1000},+ (_, i) => `<div id="r${i}" class="row"></div>`,+ ).join('')}</div></div>`,+ );+ const result = await page.evaluate(async () => {+ const area = document.querySelector('#area') as HTMLElement;+ area.scrollTop = 4200;+ const inView = document.querySelector('#r95') as HTMLElement;+ const before = inView.getBoundingClientRect().top;+ await window.change({+ changed: '#grow',+ mutate: `document.querySelector('#grow').classList.add('open')`,+ });+ const wrapper = document.querySelector('#wrapper') as HTMLElement;+ const moving = [wrapper, ...wrapper.children].filter(+ element => element.getAnimations().length > 0,+ ).length;+ const shown = inView.getBoundingClientRect().top;+ document.getAnimations().forEach(animation => animation.finish());+ return {moving, before, shown};+ });+ // The browser keeps the rows in view where they were; nothing glides+ // or fades, the wrapper around them included.+ expect(result.moving).toBe(0);+ expect(Math.abs(result.shown - result.before)).toBeLessThan(1);+ });+ }++ test('a change above the view in a panel the page scrolls: with the page anchoring its scroll, the rows in view and their wrapper stay put (FR3)', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area"><div id="wrapper"><div id="grow" class="grow"></div>${Array.from(+ {length: 1000},+ (_, i) => `<div id="r${i}" class="row"></div>`,+ ).join('')}</div></div>`,+ );+ const result = await page.evaluate(async () => {+ window.scrollTo(0, 4200);+ const inView = document.querySelector('#r95') as HTMLElement;+ const before = inView.getBoundingClientRect().top;+ await window.change({+ changed: '#grow',+ mutate: `document.querySelector('#grow').classList.add('open')`,+ });+ const wrapper = document.querySelector('#wrapper') as HTMLElement;+ const moving = [wrapper, ...wrapper.children].filter(+ element => element.getAnimations().length > 0,+ ).length;+ const shown = inView.getBoundingClientRect().top;+ document.getAnimations().forEach(animation => animation.finish());+ return {moving, before, shown};+ });+ expect(result.moving).toBe(0);+ expect(Math.abs(result.shown - result.before)).toBeLessThan(1);+ });++ test('a sticky footer stuck to the viewport in a panel the page scrolls stays at the edge (FR7)', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area">${Array.from(+ {length: 60},+ () => '<div class="row"></div>',+ ).join(+ '',+ )}<div id="footer" style="position: sticky; bottom: 0; background: #ccc"><div id="grow" class="grow"></div><div class="row"></div></div>${Array.from(+ {length: 60},+ () => '<div class="row"></div>',+ ).join('')}</div>`,+ );+ await page.evaluate(() => window.scrollTo(0, 200));+ await change(page);+ expect(await page.evaluate(() => window.motionOf('#footer'))).toEqual([]);+ });++ test('in a multi-column list the rows of a later column glide too (spec:AST-105 Coverage)', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area"><div id="list" style="columns: 2; column-gap: 8px">${[+ '<div id="grow" class="grow"></div>',+ ...Array.from(+ {length: 120},+ (_, i) =>+ `<div id="c${i}" class="row" style="break-inside: avoid"></div>`,+ ),+ ].join('')}</div></div>`,+ );+ await change(page);+ const moving = await page.evaluate(+ () =>+ [...document.querySelectorAll('#list > .row')].filter(+ row => row.getAnimations().length > 0,+ ).length,+ );+ // Every row shifts one slot along the columns; the rows in view glide,+ // the second column's included, though they come past the band in DOM+ // order.+ expect(moving).toBeGreaterThanOrEqual(20);+ });++ test('in a dialog re-centered as it grows, the header and trigger before the change stay with their card (FR3)', async ({+ page,+ }) => {+ await open(+ page,+ `<div style="position: fixed; inset: 0; display: flex; align-items: center; justify-content: center">+ <div id="area" style="width: 320px; background: #fff; border: 1px solid #999">+ <div id="header" class="row"></div>+ <div id="card" style="padding: 8px; background: #eee"><div id="trigger" class="row"></div><div id="grow" class="grow"></div></div>+ </div>+ </div>`,+ );+ await change(page);+ // The dialog rises by half the opening at once; what is before the+ // change in it rises with it, never over the opening content.+ for (const id of ['#header', '#card', '#trigger']) {+ expect(await page.evaluate(s => window.motionOf(s), id), id).toEqual([]);+ }+ });++ test('a sticky footer stuck to the viewport stays at the edge when the body sets an overflow (FR7)', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area">${Array.from(+ {length: 60},+ () => '<div class="row"></div>',+ ).join(+ '',+ )}<div id="footer" style="position: sticky; bottom: 0; background: #ccc"><div id="grow" class="grow"></div><div class="row"></div></div>${Array.from(+ {length: 60},+ () => '<div class="row"></div>',+ ).join('')}</div>`,+ 'body { overflow-x: hidden; }',+ );+ await page.evaluate(() => window.scrollTo(0, 200));+ await change(page);+ expect(await page.evaluate(() => window.motionOf('#footer'))).toEqual([]);+ });++ test('closing an item above the view while opening one in view, in one frame: the rows the browser keeps in place stay put (FR3)', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area"><div id="shut" style="height: 344px; overflow: hidden; background: #fd9"></div>${Array.from(+ {length: 30},+ (_, i) =>+ i === 14+ ? '<div id="grow" class="grow"></div>'+ : `<div id="q${i}" class="row"></div>`,+ ).join('')}</div>`,+ );+ const result = await page.evaluate(async () => {+ const area = document.querySelector('#area') as HTMLElement;+ area.scrollTop = 395;+ const layout = window.AnimatedLayout.createAnimatedLayout(() => area);+ const shut = window.AnimatedLayout.reportLayoutChange(layout, () =>+ document.querySelector('#shut'),+ );+ const grow = window.AnimatedLayout.reportLayoutChange(layout, () =>+ document.querySelector('#grow'),+ );+ shut.measureBefore();+ grow.measureBefore();+ (document.querySelector('#shut') as HTMLElement).style.height = '0px';+ document.querySelector('#grow')?.classList.add('open');+ shut.animate();+ grow.animate();+ await new Promise<void>(resolve => {+ queueMicrotask(resolve);+ });+ // The rows in view before the opening one: anchoring keeps them still.+ return [5, 6, 7, 8, 9].map(+ i => document.querySelector(`#q${i}`)?.getAnimations().length ?? -1,+ );+ });+ expect(result).toEqual([0, 0, 0, 0, 0]);+ });++ for (const anchoring of ['auto', 'none']) {+ test(`a change above the band with scroll anchoring ${anchoring === 'auto' ? 'on' : 'off'}: ${anchoring === 'auto' ? 'the rows in view stay put and the walk stops' : 'the rows in view glide'} (FR3)`, async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area" style="overflow-anchor: ${anchoring}"><div id="grow" class="grow"></div>${Array.from(+ {length: 1000},+ (_, i) => `<div id="r${i}" class="row"></div>`,+ ).join('')}</div>`,+ );+ const result = await page.evaluate(async () => {+ const area = document.querySelector('#area') as HTMLElement;+ area.scrollTop = 3600 + 600;+ const firstInView = document.querySelector('#r95') as HTMLElement;+ const before = firstInView.getBoundingClientRect().top;+ await window.change({+ changed: '#grow',+ mutate: `document.querySelector('#grow').classList.add('open')`,+ });+ const moving = [...area.children].filter(+ row => row.getAnimations().length > 0,+ ).length;+ document.getAnimations().forEach(animation => animation.finish());+ return {moving, before, after: firstInView.getBoundingClientRect().top};+ });+ if (anchoring === 'auto') {+ // The browser keeps the rows in view where they were: nothing moves.+ expect(result.moving).toBe(0);+ expect(Math.abs(result.after - result.before)).toBeLessThan(1);+ } else {+ // They shift down 80 px, and glide there.+ expect(result.moving).toBeGreaterThanOrEqual(12);+ }+ });+ }++ test('in a centered column an unstuck sticky card around the change glides with the content before it (spec:AST-105 Coverage)', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area"><div style="display: flex; flex-direction: column; justify-content: center; min-height: 400px">+ <div id="above" class="row"></div>+ <div id="card" style="position: sticky; top: 0; background: #eee"><div id="grow" class="grow"></div><div class="row"></div></div>+ <div class="row"></div>+ </div></div>`,+ );+ await change(page);+ const [above] = await page.evaluate(() => window.motionOf('#above'));+ const [card] = await page.evaluate(() => window.motionOf('#card'));+ // Not stuck, the card is in flow: it rises with the row above it, so+ // that row never crosses it.+ expect(above).toBeDefined();+ expect(card).toBeDefined();+ expect(startOffset(card.first).y).toBeCloseTo(+ startOffset(above.first).y,+ 0,+ );+ });++ test('in a centered column the card around the change glides with the content before it, so nothing slides over the opening content (spec:AST-105 Coverage)', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area"><div style="display: flex; flex-direction: column; justify-content: center; min-height: 400px">+ <div id="before" class="row" style="margin: 0"></div>+ <div id="card" style="padding: 8px; background: #eef"><div id="title" style="height: 24px">Title</div><div id="changed" style="height: 0"></div></div>+ <div id="after" class="row" style="margin: 0"></div></div></div>`,+ );+ await change(page, {+ changed: '#changed',+ mutate: `document.querySelector('#changed').style.height = '120px'`,+ });+ const card = await page.evaluate(() => window.motionOf('#card'));+ const before = await page.evaluate(() => window.motionOf('#before'));+ const title = await page.evaluate(() => window.motionOf('#title'));+ // The card and the row above it glide up together from their old place;+ // the title inside the card rides with it.+ expect(startOffset(card[0].first).y).toBeCloseTo(60, 0);+ expect(startOffset(before[0].first).y).toBeCloseTo(60, 0);+ expect(title).toEqual([]);+ });++ test('in a long list the walk reads only the rows near the visible part, and rows a tall collapse pulls up into view glide in (FR3)', async ({+ page,+ }) => {+ await open(+ page,+ `<div id="area" class="area" style="overflow-anchor: none">+ ${'<div class="row" style="margin: 0"></div>'.repeat(1000)}+ <div id="tall" style="height: 1200px; background: #fd9"></div>+ ${Array.from({length: 1000}, (_, i) => `<div id="r${i}" class="row" style="margin: 0"></div>`).join('')}+ </div>`,+ );+ const result = await page.evaluate(async () => {+ const area = document.querySelector('#area') as HTMLElement;+ const tall = document.querySelector('#tall') as HTMLElement;+ // The tall item's bottom part in view.+ area.scrollTop = tall.offsetTop + 1000 - area.clientHeight / 2;+ const prototype = Element.prototype;+ const original = prototype.getBoundingClientRect;+ let reads = 0;+ prototype.getBoundingClientRect = function getBoundingClientRect(+ this: Element,+ ) {+ reads += 1;+ return original.call(this);+ };+ const layout = window.AnimatedLayout.createAnimatedLayout(() => area);+ const report = window.AnimatedLayout.reportLayoutChange(+ layout,+ () => tall,+ );+ report.measureBefore();+ tall.style.height = '0px';+ report.animate();+ await new Promise<void>(resolve => {+ queueMicrotask(resolve);+ });+ prototype.getBoundingClientRect = original;+ // Rows now in view that were below the area's visible part plus one+ // viewport before the collapse: the band reached them because the+ // collapsing item is taller than a viewport.+ const areaRect = area.getBoundingClientRect();+ const inView = [+ ...area.querySelectorAll<HTMLElement>('[id^="r"]'),+ ].filter(row => {+ const rect = row.getBoundingClientRect();+ return rect.bottom > areaRect.top && rect.top < areaRect.bottom;+ });+ const lowest = inView.at(-1);+ return {+ reads,+ rows: inView.length,+ lowestGlides: lowest?.getAnimations().length ?? 0,+ };+ });+ // Two thousand rows, but only those near the visible part are read.+ expect(result.reads).toBeLessThan(200);+ expect(result.rows).toBeGreaterThan(0);+ expect(result.lowestGlides).toBe(1);+ });+test('the glide never scrolls the area (FR3)', async ({page}) => {// The same change with and without a handle, from the same scroll// position: the area's scroll (the browser's own scroll anchoringdiff --git a/packages/core/src/motion/animatedLayout.boundary.test.ts b/packages/core/src/motion/animatedLayout.boundary.test.tsindex f02e6f0dd3..5a57a0608e 100644--- a/packages/core/src/motion/animatedLayout.boundary.test.ts+++ b/packages/core/src/motion/animatedLayout.boundary.test.ts@@ -6,8 +6,9 @@* every core source file that imports the module* @output The source boundary check `architecture:react-component-runtime`* INV12 asks for: the module animates no layout property, its walk reaches- * elements only through parentElement / nextElementSibling (and- * firstElementChild under `display: contents`), the reporting functions are+ * elements only through parentElement and the element siblings on either+ * side (and firstElementChild under `display: contents`), stopping at the+ * band around the visible part, the reporting functions are* not public, and only the hook and the adopting components use it* @position Testing; the real-browser half of INV12's verification is in* __tests__/animatedLayout.interaction.browser.spec.ts@@ -64,7 +65,7 @@ describe('architecture:react-component-runtime INV12 source boundary', () => {]);});- it('walks only through parentElement and nextElementSibling, entering display: contents alone', () => {+ it('walks only through parentElement and the element siblings on either side, entering display: contents alone, and stops at the band', () => {const body = code(moduleSource);for (const forbidden of ['TreeWalker',@@ -73,20 +74,25 @@ describe('architecture:react-component-runtime INV12 source boundary', () => {'getElementsBy','.children','childNodes',- 'lastElementChild',- 'previousElementSibling',]) {expect(body, forbidden).not.toContain(forbidden);}- // Every descent is a `display: contents` branch: the follower walk's and- // the exit's search for the next box.- const descents = body.match(/firstElementChild/g) ?? [];- expect(descents).toHaveLength(2);+ // Every descent is a `display: contents` branch: the walk's (in its own+ // direction, first child or last) and the exit's search for the next box.+ const descents = body.match(/(first|last)ElementChild/g) ?? [];+ expect(descents).toHaveLength(3);const contentsDescents =body.match(- /display === 'contents'\)\s*\{\s*for\s*\(\s*let child = \w+\.firstElementChild/g,+ /(?:display|part) === 'contents'\)\s*\{\s*for\s*\(\s*let child =[^;]*\.(first|last)ElementChild/g,) ?? [];expect(contentsDescents).toHaveLength(2);+ // Each level's sibling walk ends at the first sibling past the band.+ expect(body).toMatch(+ /sibling != null && take\(sibling, true\);\s*sibling = sibling\.nextElementSibling/,+ );+ expect(body).toMatch(+ /sibling != null && take\(sibling, false\);\s*sibling = sibling\.previousElementSibling/,+ );});it('keeps the reporting functions out of every public entry point', () => {diff --git a/packages/core/src/motion/animatedLayout.test.ts b/packages/core/src/motion/animatedLayout.test.tsindex bddff357ba..07551008b4 100644--- a/packages/core/src/motion/animatedLayout.test.ts+++ b/packages/core/src/motion/animatedLayout.test.ts@@ -712,3 +712,254 @@ describe('elements the app moves itself (spec:AST-105 Coverage)', () => {expect(moved).toEqual(['plain']);});});++describe('siblings before the change (spec:AST-105 FR3, Coverage)', () => {+ it('moves an earlier sibling a centered row shifts when a later item grows', async () => {+ const {area, changed, phase} = setUp(+ '<div id="area"><div id="row"><div id="first"></div><div id="changed"></div></div></div>',+ );+ // A centered row: the item before the growing one moves left by half.+ placeAt(+ document.getElementById('first') as HTMLElement,+ {before: [160, 0, 40, 24], after: [120, 0, 40, 24]},+ phase,+ );+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ const moves = played.filter(+ p =>+ (p.element as HTMLElement).id === 'first' &&+ p.keyframes[0].translate != null,+ );+ expect(moves).toHaveLength(1);+ expect(translateOf(moves[0]).x).toBeCloseTo(40);+ });++ it('leaves an earlier sibling whose rectangle did not change', async () => {+ const {area, changed, phase} = setUp(+ '<div id="area"><div id="first"></div><div id="changed"></div></div>',+ );+ placeAt(+ document.getElementById('first') as HTMLElement,+ {before: [0, 0, 400, 40]},+ phase,+ );+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ expect(+ played.filter(p => (p.element as HTMLElement).id === 'first'),+ ).toEqual([]);+ });+});++describe('the walk stops at the band a change can bring into view', () => {+ it('reads no sibling past the band, after or before the change', async () => {+ // A 600 px area: the band runs a viewport above and below it.+ const rows = Array.from({length: 40}, (_, i) => `<div id="r${i}"></div>`);+ const {area, changed, phase} = setUp(+ `<div id="area">${rows.slice(0, 20).join('')}<div id="changed"></div>${rows.slice(20).join('')}</div>`,+ );+ const reads = new Map<string, number>();+ rows.forEach((_, i) => {+ const row = document.getElementById(`r${i}`) as HTMLElement;+ // Rows 100 px apart, the changed element between rows 19 and 20 at+ // 1000 px: 20 rows above it reach -1000 px, 20 below reach 3000 px.+ const top = i < 20 ? (i - 20) * 100 + 1000 : (i - 20) * 100 + 1100;+ vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => {+ reads.set(row.id, (reads.get(row.id) ?? 0) + 1);+ const shift = phase.current === 'after' && i >= 20 ? 80 : 0;+ return new DOMRect(0, top - 1000 + shift, 400, 100);+ });+ });+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ // The band is -600..1200 px: rows past it are never read.+ expect(reads.get('r39')).toBeUndefined();+ expect(reads.get('r0')).toBeUndefined();+ expect(reads.get('r20')).toBeGreaterThan(0);+ expect(reads.get('r19')).toBeGreaterThan(0);+ });+});++describe('the walk reaches what the changes can move (spec:AST-105 FR3)', () => {+ it("glides the change's ancestor that a centered column moves, and the content inside it moves only with it", async () => {+ const {area, changed, phase} = setUp(+ '<div id="area"><div id="column"><div id="above"></div><div id="card"><div id="title"></div><div id="changed"></div></div></div></div>',+ );+ // The column centers its content: opening the change moves the card and+ // the content above it up by half the growth.+ placeAt(+ document.getElementById('above') as HTMLElement,+ {before: [0, 100, 400, 40], after: [0, 60, 400, 40]},+ phase,+ );+ placeAt(+ document.getElementById('card') as HTMLElement,+ {before: [0, 140, 400, 60], after: [0, 100, 400, 140]},+ phase,+ );+ placeAt(+ document.getElementById('title') as HTMLElement,+ {before: [0, 140, 400, 20], after: [0, 100, 400, 20]},+ phase,+ );+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ const glides = new Map(+ played+ .filter(p => p.keyframes[0].translate != null)+ .map(p => [(p.element as HTMLElement).id, translateOf(p).y]),+ );+ expect(glides.get('card')).toBeCloseTo(40);+ expect(glides.get('above')).toBeCloseTo(40);+ // The title rides with its card: it moved by nothing of its own.+ expect(glides.has('title')).toBe(false);+ });++ it('reaches the band that all the changes in one frame can pull into view', () => {+ const rows = Array.from({length: 30}, (_, i) => `<div id="r${i}"></div>`);+ document.body.innerHTML = `<div id="area"><div id="a"></div><div id="b"></div>${rows.join('')}</div>`;+ const area = document.getElementById('area') as HTMLElement;+ vi.spyOn(area, 'getBoundingClientRect').mockReturnValue(+ new DOMRect(0, 0, 400, 560),+ );+ // Two 500 px groups closing at once: the rows below them come up 1,000 px.+ for (const [id, y] of [+ ['a', 0],+ ['b', 500],+ ] as const) {+ vi.spyOn(+ document.getElementById(id) as HTMLElement,+ 'getBoundingClientRect',+ ).mockReturnValue(new DOMRect(0, y, 400, 500));+ }+ const reads = new Set<string>();+ rows.forEach((_, i) => {+ const row = document.getElementById(`r${i}`) as HTMLElement;+ vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => {+ reads.add(row.id);+ return new DOMRect(0, 1000 + i * 100, 400, 100);+ });+ });+ const layout = createAnimatedLayout(() => area);+ reportLayoutChange(layout, () =>+ document.getElementById('a'),+ ).measureBefore();+ reportLayoutChange(layout, () =>+ document.getElementById('b'),+ ).measureBefore();+ // One group's band ends at 560 + 560; both together reach 560 + 1,000.+ expect(reads.has('r5')).toBe(true);+ expect(reads.has('r20')).toBe(false);+ });++ it('reads each element once however many changes report in one frame', () => {+ const rows = Array.from({length: 200}, (_, i) => `<div id="r${i}"></div>`);+ document.body.innerHTML = `<div id="area">${rows.join('')}</div>`;+ const area = document.getElementById('area') as HTMLElement;+ vi.spyOn(area, 'getBoundingClientRect').mockReturnValue(+ new DOMRect(0, 0, 400, 6000),+ );+ let reads = 0;+ rows.forEach((_, i) => {+ vi.spyOn(+ document.getElementById(`r${i}`) as HTMLElement,+ 'getBoundingClientRect',+ ).mockImplementation(() => {+ reads += 1;+ return new DOMRect(0, i * 30, 400, 30);+ });+ });+ const layout = createAnimatedLayout(() => area);+ // A tree collapsing 100 rows in one update reports 100 changes.+ for (let i = 0; i < 100; i += 1) {+ reportLayoutChange(layout, () =>+ document.getElementById(`r${i}`),+ ).measureBefore();+ }+ expect(reads).toBeLessThanOrEqual(rows.length);+ });++ it('walks no further than the first sibling outside the band from a change outside it', () => {+ const rows = Array.from({length: 1000}, (_, i) => `<div id="r${i}"></div>`);+ document.body.innerHTML = `<div id="area">${rows.join('')}</div>`;+ const area = document.getElementById('area') as HTMLElement;+ vi.spyOn(area, 'getBoundingClientRect').mockReturnValue(+ new DOMRect(0, 0, 400, 600),+ );+ const reads = new Set<string>();+ rows.forEach((_, i) => {+ const row = document.getElementById(`r${i}`) as HTMLElement;+ vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => {+ reads.add(row.id);+ return new DOMRect(0, i * 100, 400, 100);+ });+ });+ reportLayoutChange(+ createAnimatedLayout(() => area),+ () => document.getElementById('r900'),+ ).measureBefore();+ // The change itself, and one sibling on each side, which lie outside.+ expect(reads.size).toBeLessThanOrEqual(3);+ });++ it('stops inside a display: contents wrapper at the band too', () => {+ const rows = Array.from({length: 40}, (_, i) => `<div id="c${i}"></div>`);+ const {area, changed} = setUp(+ `<div id="area"><div id="changed"></div><div style="display: contents">${rows.join('')}</div></div>`,+ );+ void area;+ const reads = new Set<string>();+ rows.forEach((_, i) => {+ const row = document.getElementById(`c${i}`) as HTMLElement;+ vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => {+ reads.add(row.id);+ return new DOMRect(0, i * 100, 400, 100);+ });+ });+ reportLayoutChange(+ createAnimatedLayout(() => area),+ () => changed,+ ).measureBefore();+ // The band ends a viewport below the 600 px area.+ expect(reads.has('c12')).toBe(true);+ expect(reads.has('c30')).toBe(false);+ });++ it('moves an earlier sibling that order places after the change, near the visible part', async () => {+ const {area, changed, phase} = setUp(+ '<div id="area"><div id="ordered" style="order: 1"></div><div id="changed"></div></div>',+ );+ // First in the DOM, laid out after the change: it moves down when the+ // change grows.+ placeAt(+ document.getElementById('ordered') as HTMLElement,+ {before: [0, 0, 400, 40], after: [0, 80, 400, 40]},+ phase,+ );+ await runChange(+ createAnimatedLayout(() => area),+ changed,+ phase,+ );+ const glide = played.find(+ p =>+ (p.element as HTMLElement).id === 'ordered' &&+ p.keyframes[0].translate != null,+ );+ expect(glide).toBeDefined();+ expect(translateOf(glide!).y).toBeCloseTo(-80);+ });+});diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.tsindex 947d726f3b..eb352ea370 100644--- a/packages/core/src/motion/animatedLayout.ts+++ b/packages/core/src/motion/animatedLayout.ts@@ -18,9 +18,15 @@* How it works:* - `measureBefore()` runs before the change commits: from the changed* element it walks up to the handle's container and, at each level,- * records the rectangle of every following element sibling, through- * `parentElement` and `nextElementSibling`, descending only into an element- * with `display: contents` (it has no box).+ * records the rectangles of the element siblings after it and before it (a+ * centered, end-aligned or space-between row, or `order`, moves those too),+ * through `parentElement`, `nextElementSibling` and+ * `previousElementSibling`, descending only into an element with+ * `display: contents` (it has no box). Each level's walk stops at the first+ * sibling outside the band a change can move content into view from: the+ * area's visible part plus one viewport, or the changed element's size if+ * larger, above and below. So its cost grows with depth plus the siblings+ * near the visible part, never with a list's length.* - `animate()` runs after the commit (a layout effect). Every change in the* same area reported in one frame is measured together after the commit,* once, in a microtask, so each element moves once, by its total change.@@ -315,43 +321,256 @@ function takesPart(element: Element, style: CSSStyleDeclaration): boolean {}/**- * The elements that can shift when `changed` changes size: at each ancestor- * level up to `area`, every following element sibling. `display: contents` is- * replaced by its children.+ * The band of the page a change can move content into or out of view: the+ * area's visible part, extended above and below by one viewport or by the+ * size of every element changing in the frame, whichever is larger (a+ * collapse pulls content up by at most its size, and changes in one frame+ * add up). Content outside it before the change stays outside it, so the+ * walk stops there.*/-function collectFollowers(changed: Element, area: Element): Element[] {- const view = changed.ownerDocument.defaultView;- const out: Element[] = [];- const take = (element: Element) => {- const style = view?.getComputedStyle(element);- if (style == null) {- return;+interface Band {+ /** Its top edge, in client px. */+ readonly start: number;+ /** Its bottom edge, in client px. */+ readonly end: number;+}++function bandFor(visible: DOMRect, reach: number): Band {+ return {start: visible.top - reach, end: visible.bottom + reach};+}++/**+ * What one frame's walks read, kept so a level two changes share, or a walk+ * repeated when the band grows, reads each element once.+ */+interface WalkCache {+ readonly rects: Map<Element, DOMRect>;+ /** Whether the element takes part, or `contents` for a boxless element. */+ readonly parts: Map<Element, boolean | 'contents'>;+}++function partOf(element: Element, cache: WalkCache): boolean | 'contents' {+ let part = cache.parts.get(element);+ if (part === undefined) {+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);+ part =+ style == null+ ? false+ : style.display === 'contents'+ ? 'contents'+ : takesPart(element, style);+ cache.parts.set(element, part);+ }+ return part;+}++/**+ * Whether a container lays its children out across the block direction, so+ * DOM order does not run down the page: multi-column, a wrapping column flex+ * box, or a grid that flows by column. The band says nothing about where its+ * later children sit, so a walk there runs through the level.+ */+function flowsAcross(container: Element | null): boolean {+ if (container == null) {+ return false;+ }+ const style =+ container.ownerDocument.defaultView?.getComputedStyle(container);+ if (style == null) {+ return false;+ }+ const count = style.getPropertyValue('column-count');+ const width = style.getPropertyValue('column-width');+ return (+ (count !== '' && count !== 'auto') ||+ (width !== '' && width !== 'auto') ||+ (style.display.includes('flex') &&+ style.flexDirection.startsWith('column') &&+ style.flexWrap.startsWith('wrap')) ||+ (style.display.includes('grid') &&+ style.getPropertyValue('grid-auto-flow').startsWith('column'))+ );+}++/**+ * The box a sticky element sticks to: its nearest scrolling ancestor's, or+ * the viewport.+ */+function scrollportOf(element: Element): {start: number; end: number} {+ const view = element.ownerDocument.defaultView;+ for (+ let node = element.parentElement;+ node != null && node !== element.ownerDocument.documentElement;+ node = node.parentElement+ ) {+ const overflow = view?.getComputedStyle(node).overflowY ?? 'visible';+ if (+ node === element.ownerDocument.body &&+ view?.getComputedStyle(element.ownerDocument.documentElement)+ .overflowY === 'visible'+ ) {+ // The body's overflow applies to the viewport while the root's is+ // visible: the body is no scroller of its own.+ continue;}- if (style.display === 'contents') {+ if (overflow !== 'visible' && overflow !== 'clip') {+ const box = node.getBoundingClientRect();+ return {+ start: box.top + node.clientTop,+ end: box.top + node.clientTop + node.clientHeight,+ };+ }+ }+ return {start: 0, end: view?.innerHeight ?? 0};+}++/**+ * Whether a sticky element is stuck: resting against its scrollport's edge+ * at its inset. A stuck element takes its final place; an unstuck one is in+ * flow.+ */+function isStuck(element: Element, cache: WalkCache): boolean {+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);+ if (style?.position !== 'sticky') {+ return false;+ }+ const rect = rectOf(element, cache);+ const edge = scrollportOf(element);+ const top = Number.parseFloat(style.top);+ const bottom = Number.parseFloat(style.bottom);+ return (+ (Number.isFinite(top) && Math.abs(rect.top - (edge.start + top)) < 1) ||+ (Number.isFinite(bottom) && Math.abs(rect.bottom - (edge.end - bottom)) < 1)+ );+}++function rectOf(element: Element, cache: WalkCache): DOMRect {+ let rect = cache.rects.get(element);+ if (rect === undefined) {+ rect = element.getBoundingClientRect();+ cache.rects.set(element, rect);+ }+ return rect;+}++/**+ * The elements a change can move, each with its rectangle before the change:+ * the changed element's ancestors up to the area (a centered column moves+ * the card around the change), and at each of their levels the siblings+ * after and before (a centered, end-aligned or space-between row, or+ * `order`, moves those too). A `display: contents` element has no box: its+ * children stand in its place, walked in the same direction. At each level+ * the walk stops at the first sibling outside `band`, so its cost grows with+ * depth plus the siblings near the visible part, never with the length of a+ * list; where the area opts out of scroll anchoring (`walksToBand`), the walk+ * after a change above the band goes on to the band, a cost that grows with+ * that distance. Inside a positioned, stuck sticky or top-layer ancestor only the+ * content after the change is taken.+ */+function collectCandidates(+ changed: Element,+ area: Element,+ band: Band,+ cache: WalkCache,+ walksToBand: boolean,+ ancestors: Set<Element>,+ befores: Set<Element>,+): Map<Element, DOMRect> {+ const out = new Map<Element, DOMRect>();+ /** Takes `element`; returns false once it lies outside the band. */+ /** The current level runs through its siblings, ignoring the band. */+ let runsThrough = false;+ const take = (element: Element, isAfter: boolean): boolean => {+ const part = partOf(element, cache);+ if (part === 'contents') {for (- let child = element.firstElementChild;+ let child = isAfter+ ? element.firstElementChild+ : element.lastElementChild;child != null;- child = child.nextElementSibling+ child = isAfter+ ? child.nextElementSibling+ : child.previousElementSibling) {- take(child);+ if (!take(child, isAfter)) {+ return false;+ }}- return;+ return true;}- if (takesPart(element, style)) {- out.push(element);+ if (!part) {+ return true;}+ const rect = rectOf(element, cache);+ if (runsThrough) {+ out.set(element, rect);+ return true;+ }+ if (rect.top > band.end) {+ return false;+ }+ if (rect.bottom < band.start) {+ // Above the band. Where the scroller opts out of scroll anchoring, the+ // content after a change above the band shifts the rows in view, so+ // the walk after it goes on to the band; with anchoring, it stops.+ return isAfter && walksToBand;+ }+ out.set(element, rect);+ if (!isAfter) {+ befores.add(element);+ }+ return true;};+ // The change's chain up to the area, and from where it is inside a+ // positioned, stuck sticky or top-layer ancestor: that ancestor takes its final+ // place, so inside it only the content after the change moves; the+ // ancestors and the siblings before the change stay with it.+ const chain: Element[] = [];for (let node: Element | null = changed;node != null && node !== area;node = node.parentElement) {+ chain.push(node);+ }+ // The levels below this index are inside a positioned ancestor.+ let positionedFrom = 0;+ for (let index = chain.length - 1; index > 0; index -= 1) {+ if (partOf(chain[index], cache) === false || isStuck(chain[index], cache)) {+ positionedFrom = index;+ break;+ }+ }+ for (const [level, node] of chain.entries()) {+ runsThrough = flowsAcross(node.parentElement);+ if (+ node !== changed &&+ level > positionedFrom &&+ partOf(node, cache) === true+ ) {+ // An ancestor of the change in flow: where its layout moves it (a+ // centered column), it glides, and what is inside moves only by its own+ // change. A positioned, stuck sticky or top-layer ancestor, and every+ // ancestor inside it, takes its final place.+ out.set(node, rectOf(node, cache));+ ancestors.add(node);+ }for (let sibling = node.nextElementSibling;- sibling != null;+ sibling != null && take(sibling, true);sibling = sibling.nextElementSibling) {- take(sibling);+ // The siblings after it, until one lies past the band.+ }+ if (level < positionedFrom) {+ continue;+ }+ for (+ let sibling = node.previousElementSibling;+ sibling != null && take(sibling, false);+ sibling = sibling.previousElementSibling+ ) {+ // The siblings before it, until one lies before the band.}}return out;@@ -365,6 +584,27 @@ interface Batch {readonly area: Element;readonly changed: Set<Element>;readonly before: Map<Element, DOMRect>;+ /** What each changed element's walk found, so a dropped change moves none. */+ readonly candidates: Map<Element, Element[]>;+ /** The changed elements' sizes before the change, added up. */+ changedSize: number;+ /** How far past the visible part the walks reach (0 before the first). */+ reach: number;+ /** The area's visible part, read once per frame. */+ visible: DOMRect | null;+ /** Whether the area opts out of scroll anchoring, read once per frame. */+ walksToBand: boolean | null;+ /** The change's ancestors among the candidates. */+ readonly ancestors: Set<Element>;+ /** The siblings before the change among the candidates. */+ readonly befores: Set<Element>;+ /**+ * Where the area's content sat before the change, read once per frame: the+ * area's place in view less its scroll offset, so a scroll of the area, an+ * outer scroller or the page shows up as a change of it.+ */+ originBefore: {readonly x: number; readonly y: number} | null;+ readonly cache: WalkCache;scheduled: boolean;}@@ -377,6 +617,15 @@ function batchFor(area: Element): Batch {area,changed: new Set(),before: new Map(),+ candidates: new Map(),+ changedSize: 0,+ reach: 0,+ visible: null,+ walksToBand: null,+ ancestors: new Set(),+ befores: new Set(),+ originBefore: null,+ cache: {rects: new Map(), parts: new Map()},scheduled: false,};batches.set(area, created);@@ -411,6 +660,12 @@ function intersects(a: DOMRect, b: DOMRect): boolean {}/** The part of the area the person can see: its box within the viewport. */+/** Where the area's scrolled content starts, in client px. */+function originOf(area: Element): {x: number; y: number} {+ const box = area.getBoundingClientRect();+ return {x: box.left - area.scrollLeft, y: box.top - area.scrollTop};+}+function visibleRect(area: Element): DOMRect {const box = area.getBoundingClientRect();const view = area.ownerDocument.defaultView;@@ -445,13 +700,14 @@ function scaleOf(element: Element, rect: DOMRect): {x: number; y: number} {function flush(batch: Batch): void {batches.delete(batch.area);+ // What each change's walk measured before it: an element added by the+ // change has no old place, and one it removed is gone.const followers = new Set<Element>();for (const changed of batch.changed) {- if (!changed.isConnected) {- continue;- }- for (const element of collectFollowers(changed, batch.area)) {- followers.add(element);+ for (const element of batch.candidates.get(changed) ?? []) {+ if (element.isConnected) {+ followers.add(element);+ }}}if (followers.size === 0) {@@ -501,10 +757,28 @@ function flush(batch: Batch): void {entries.push({element, before, carried, carriedMs});}const byElement = new Map<Element, (typeof entries)[number]>();+ // An ancestor of the change, and a sibling before it, move by their layout+ // change alone: when scroll anchoring re-scrolls the area, an outer+ // scroller or the page (a change above the visible part), or the area+ // itself moves as its content grows (a dialog re-centered), their place in+ // view shifts by that while their place in the area stays.+ const origin = originOf(batch.area);+ const scrolledX = origin.x - (batch.originBefore?.x ?? origin.x);+ const scrolledY = origin.y - (batch.originBefore?.y ?? origin.y);+ // Netted only where that makes the move smaller: an element the browser+ // kept in place (scroll anchoring for another change in the same frame)+ // stays where it is.+ const nearer = (raw: number, shift: number) =>+ Math.abs(raw + shift) < Math.abs(raw) ? raw + shift : raw;for (const entry of entries) {entry.after = entry.element.getBoundingClientRect();- entry.rawX = entry.before.left - entry.after.left;- entry.rawY = entry.before.top - entry.after.top;+ const rawX = entry.before.left - entry.after.left;+ const rawY = entry.before.top - entry.after.top;+ // The siblings before the change stay with the ancestors around them.+ const isAncestor =+ batch.ancestors.has(entry.element) || batch.befores.has(entry.element);+ entry.rawX = isAncestor ? nearer(rawX, scrolledX) : rawX;+ entry.rawY = isAncestor ? nearer(rawY, scrolledY) : rawY;byElement.set(entry.element, entry);}for (const entry of entries) {@@ -618,11 +892,44 @@ export function reportLayoutChange(return;}const batch = batchFor(area);+ if (batch.changed.has(element)) {+ return;+ }batch.changed.add(element);- for (const follower of collectFollowers(element, area)) {- if (!batch.before.has(follower)) {- batch.before.set(follower, follower.getBoundingClientRect());+ batch.changedSize += rectOf(element, batch.cache).height;+ batch.visible ??= visibleRect(area);+ batch.originBefore ??= originOf(area);+ batch.walksToBand ??=+ area.ownerDocument.defaultView+ ?.getComputedStyle(area)+ .getPropertyValue('overflow-anchor') === 'none';+ // Changes in one frame add up: every change's walk reaches the band+ // their summed size can pull into view. When that outgrows the band+ // walked so far, the band at least doubles and every change is walked+ // again (from the cache), so a frame of many changes re-walks a few+ // times, not once per change.+ const needed = Math.max(batch.visible.height, batch.changedSize);+ const walks = needed > batch.reach ? [...batch.changed] : [element];+ if (needed > batch.reach) {+ batch.reach = Math.max(needed, batch.reach * 2);+ }+ const band = bandFor(batch.visible, batch.reach);+ for (const changed of walks) {+ const candidates = collectCandidates(+ changed,+ area,+ band,+ batch.cache,+ batch.walksToBand,+ batch.ancestors,+ batch.befores,+ );+ for (const [candidate, rect] of candidates) {+ if (!batch.before.has(candidate)) {+ batch.before.set(candidate, rect);+ }}+ batch.candidates.set(changed, [...candidates.keys()]);}},animate() {