Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(Carousel): under snap paging, scroll calls move through the paging (#10384)

Christopher Chedeau78df0c20b1bc
diff --git a/.changeset/carousel-snap-buttons-page.md b/.changeset/carousel-snap-buttons-page.md
new file mode 100644
index 0000000000..c543b2b614
--- /dev/null
+++ b/.changeset/carousel-snap-buttons-page.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Under snap paging (`hasSnap={useSnapPaging()}`), Carousel's edge buttons and `handleRef`'s `scrollNext`, `scrollPrev` and `scrollTo` move the row through the paging, also from rest. A touch that catches such a move now leaves the row on a page, as a flick's settle does. On iOS a still touch used to stop the browser's smooth scroll between two items.
+
+@vjeux
diff --git a/.github/scripts/ci-interaction-webkit.test.mjs b/.github/scripts/ci-interaction-webkit.test.mjs
index 0e44dcfd0d..3bc7b96624 100644
--- a/.github/scripts/ci-interaction-webkit.test.mjs
+++ b/.github/scripts/ci-interaction-webkit.test.mjs
@@ -289,6 +289,7 @@ describe('WebKit interaction proof routing', () => {
expect(proofs(['packages/core/src/Carousel/useCarouselPaging.ts'])).toEqual(
[
'packages/core/src/Carousel/__tests__/Carousel.interaction.browser.spec.ts',
+ 'packages/core/src/Carousel/__tests__/CarouselSnapPagingButtons.interaction.browser.spec.ts',
'packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.ts',
],
);
diff --git a/docs/specs/components/Carousel/Carousel.spec.md b/docs/specs/components/Carousel/Carousel.spec.md
index 726f3e42c6..ebc25c7e09 100644
--- a/docs/specs/components/Carousel/Carousel.spec.md
+++ b/docs/specs/components/Carousel/Carousel.spec.md
@@ -14,6 +14,8 @@ verified_by:
[
packages/core/src/Carousel/Carousel.test.tsx,
packages/core/src/Carousel/__tests__/Carousel.a11y.chromium.spec.ts,
+ packages/core/src/Carousel/__tests__/CarouselSnapPagingButtons.interaction.browser.spec.ts,
+ packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.ts,
packages/core/src/SnapPaging/SnapPaging.test.tsx,
packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts,
scripts/snap-paging-bundle.test.mjs,
@@ -86,8 +88,9 @@ Consumer migration instructions belong in consumer docs and release notes.
- Scroll area keyboard access and naming — `spec:AST-025`.
- Disabled control semantics in general — `spec:AST-085`.
- Button naming, sizing, and activation — `family:buttons`.
-- Looping, mouse-drag paging, autoplay, dots, edge fades, and slide semantics —
+- Looping, mouse-drag paging, autoplay, dots, and slide semantics —
uncontracted.
+- Edge fades — the fades' look is uncontracted; their state follows FR8.
## Public concepts
@@ -110,7 +113,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR5 | `hasSnap` takes `boolean \| SnapPaging`. Omitted or `false`: the scroll area does not snap. `true` (written `hasSnap`): native snap, FR6, exactly as released, with no gesture code. A `SnapPaging` value, made only by `useSnapPaging`: snap paging, FR7; the carousel snaps on native snap's per-item stops and the pager settles on those same stops. `true` never pages. A new `SnapPaging` value on a later render does not restart a settle or attach the gesture again. The third state is a known deviation from `architecture:public-component-api` INV3, which keeps a `has…` boolean to a true on/off (DEC-2). | DEC-2 | settled |
| FR6 | Native snap uses CSS scroll snap only: mandatory snap along the row on the scroll area, each direct child snapping at its start edge, and scroll padding matching the carousel's padding. Every item is a stop, also when several items show at once, and the platform's own momentum picks where a swipe rests. The current page reported is the page snapped into view when scrolling settles, and edge-button availability follows every scroll, momentum and programmatic included, and every resize. Native snap adds no gesture code. It does not depend on `::scroll-button()`, `::scroll-marker`, `:target-current`, scroll-state container queries, snap events, or `interactivity: inert`; one of these MAY be added under `@supports` only where it changes no behavior, name, role, or focus order. | DEC-2 | settled |
| FR7 | Snap paging uses native snap's stops (FR6): each direct child's start edge, measured from the inline start and mirrored in right-to-left layout, with the last stops clamped where the row ends so no empty space shows. A gap sits between stops and is never a stop. Under a finger, and on a trackpad swipe under every pointer (`spec:AST-094` FR43), a release picks its rest page by `spec:AST-094` FR3's paging rule: at most one page from the page the drag started on. The settle starts as `spec:AST-094` FR6's paging paragraph says. With the paging config, a flick moves one view by default: the release settles on the item start edge nearest one viewport on in the flick's direction, and the last page rests where the row ends; `{pages: 'item'}` moves one item per flick instead. Under right-to-left layout, pages run from the inline start. With one item per view both give the same stops. A mouse wheel keeps native snapping, and `hasSnap={true}` keeps native CSS snap under every pointer. An edge button steps about one view: the viewport width less half an item, landing on the nearest stop and moving at least one stop. Evidence gap: the one-item-per-flick feel is not yet measured against UIKit's group paging; measure before claiming parity. | DEC-2; `spec:AST-094` FR3, FR6, DEC-25 | settled |
-| FR8 | Carousel's module imports no pager code: not the internal pager, its paging motion, or its gesture code. The `useSnapPaging` module imports that code statically, and Carousel calls only attach and detach on the `SnapPaging` value from an effect, and its move of a row the value holds from Carousel's own scroll calls. The pager is tree-shaken by module boundary, with no lazy `import()` (`architecture:react-component-runtime` INV13), so a Carousel without `hasSnap={useSnapPaging()}` bundles no pager code. Importing the module does no DOM work. | DEC-2; `architecture:react-component-runtime` INV13 | settled |
+| FR8 | Carousel's module imports no pager code: not the internal pager, its paging motion, or its gesture code. The `useSnapPaging` module imports that code statically, and Carousel calls only attach and detach on the `SnapPaging` value from an effect, and its moves of the row from Carousel's own scroll calls. The pager is tree-shaken by module boundary, with no lazy `import()` (`architecture:react-component-runtime` INV13), so a Carousel without `hasSnap={useSnapPaging()}` bundles no pager code. Importing the module does no DOM work. Under snap paging, the edge buttons, the edge fades and the handle's `canScrollPrev()`/`canScrollNext()` follow the held row, one state. | DEC-2; `architecture:react-component-runtime` INV13 | settled |
| FR9 | `useSnapPaging(options?)` has no non-React equivalent by default: its value feeds only Carousel's `hasSnap` (`architecture:public-component-api` INV22). Carousel attaches FR7 to its scroll area through that value, and detaching it removes every listener it added. | `architecture:public-component-api` INV22 | settled |
### Representative states
@@ -162,13 +165,13 @@ visual evidence.
| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
-| FR1, AR1 | Unit and accessibility-tree tests | at rest at each edge; no overflow | A hidden button that is focusable or exposed fails | `audit:Carousel/accessibility` |
+| FR1, AR1 | Unit and accessibility-tree tests; a real-browser test of the held row in Chromium and WebKit | at rest at each edge; no overflow; under snap paging, a flick away from each edge and a press on the end button | A hidden button that is focusable or exposed fails; so does an edge button that comes back more than two frames after the held row leaves its edge | `audit:Carousel/accessibility` |
| FR2, AR2 | Real-browser keyboard test | Enter on "Scroll right" until the end; same on the start | Focus on the page body, a hidden button, or the opposite button fails | `audit:Carousel/accessibility` |
| FR3 | Real-browser test with swipe and resize | edge reached with focus outside the carousel | Focus moving without an edge-button press, or moving twice for one edge, fails | `audit:Carousel/accessibility` |
| FR5, FR6 | Unit tests of the scroll area's styles and listeners | `hasSnap` absent, `false`, `true`, and a `SnapPaging` value; one and three items per view | Snapping with `hasSnap` omitted or `false`, a stop other than each child's start edge, gesture listeners under `hasSnap={true}`, `hasSnap={true}` that pages, or paging stops that differ from native snap's fails | — |
| FR7, AR3 | Real-browser touch and trackpad tests in Chromium and WebKit, under a finger and a trackpad swipe under a coarse and a fine primary pointer, each for the default and for `{pages: 'item'}` | one item per view; three items per view; a partial last page; right-to-left; a short flick over 300 pt/s; a slow release before and past half a page; an edge-button step at three per view; a mouse wheel; `hasSnap={true}` under a trackpad swipe | A rest stop other than FR7's, a move of more than one page per flick, a default flick at three per view that moves one item, a `{pages: 'item'}` flick that moves more than one item, empty space after the last item, an unmirrored right-to-left flick, a fine-pointer trackpad swipe that does not page, a mouse wheel that runs the pager, or `hasSnap={true}` that pages fails | — |
| FR7 | Preview stories at desktop and phone widths, used under a finger, a trackpad under a coarse and a fine primary pointer, and a mouse wheel | one item per view; three items per view; a partial last page; right-to-left; each with `hasSnap`, with `hasSnap={useSnapPaging()}`, and with `hasSnap={useSnapPaging({pages: 'item'})}` | A missing story, or a story whose paging stops differ from its native-snap stops, fails | — |
-| FR8 | Bundle test over Core's source with the size report's esbuild options, its eager output attributed by module, and a positive control | Carousel alone; Carousel with `useSnapPaging`; a server import of the module | A Carousel without `hasSnap={useSnapPaging()}` that bundles pager code, an `import()` of the pager, or DOM work on import fails | — |
+| FR8 | Bundle test over Core's source with the size report's esbuild options, its eager output attributed by module, and a positive control; real-browser tests of the held row | Carousel alone; Carousel with `useSnapPaging`; a server import of the module; an edge-button press at rest and a flick under snap paging | A Carousel without `hasSnap={useSnapPaging()}` that bundles pager code, an `import()` of the pager, or DOM work on import fails; so do an edge-button press that leaves the paging and edges that lag the held row | — |
| FR9 | Unit tests of the hook in Carousel | the hook in Carousel; Carousel unmounting, or dropping the value, mid-settle | A listener left after the carousel unmounts or drops the value, or a public `create…` equivalent of the hook, fails | — |
## Decision log
diff --git a/packages/core/src/Carousel/Carousel.tsx b/packages/core/src/Carousel/Carousel.tsx
index 311509f31c..d42271fef9 100644
--- a/packages/core/src/Carousel/Carousel.tsx
+++ b/packages/core/src/Carousel/Carousel.tsx
@@ -65,6 +65,7 @@ import {
attachSnapPaging,
isSnapPaging,
moveHeldSnapPaging,
+ moveSnapPaging,
nearestStop,
type SnapPaging,
snapStops,
@@ -507,9 +508,10 @@ export function Carousel({
if (!el) {
return;
}
- // While a flick's drag or settle holds the row, the paging moves it.
+ // Under snap paging the paging moves the row, held or at rest. A touch
+ // then catches the move, and the release rests on a page.
if (
- moveHeldSnapPaging(el, (at, end) =>
+ moveSnapPaging(el, (at, end) =>
pagingStep(el, at, end, direction, hasLoop && hasOverflow),
)
) {
@@ -590,8 +592,15 @@ export function Carousel({
const delta = isRtlElement(el)
? itemRect.right - containerRect.right
: itemRect.left - containerRect.left;
+ // Under snap paging the row goes to the item's stop, inside the scroll
+ // padding, so the hand-back's snap does not pull it back.
if (
- moveHeldSnapPaging(el, at => at + (isRtlElement(el) ? -delta : delta))
+ moveSnapPaging(el, (at, end) =>
+ nearestStop(
+ snapStops(el, at, end),
+ at + (isRtlElement(el) ? -delta : delta),
+ ),
+ )
) {
return;
}
diff --git a/packages/core/src/Carousel/__tests__/CarouselSnapPagingButtons.interaction.browser.spec.ts b/packages/core/src/Carousel/__tests__/CarouselSnapPagingButtons.interaction.browser.spec.ts
new file mode 100644
index 0000000000..0e087f4eac
--- /dev/null
+++ b/packages/core/src/Carousel/__tests__/CarouselSnapPagingButtons.interaction.browser.spec.ts
@@ -0,0 +1,186 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CarouselSnapPagingButtons.interaction.browser.spec.ts
+ * @input The Core/Carousel three-up snap paging story in paging mode, the
+ * scroll-right button, real touches from the interaction harness, and a
+ * per-frame page sampler
+ * @output Proves an edge button press at rest moves the row through the
+ * paging. The press holds the row, lands on the next page, and leaves no
+ * item a layer once the row rests. A still touch that catches the move
+ * leaves the row on a page. The press's own task lays out nothing.
+ * @position Interaction proofs for Carousel's scroll calls under snap paging,
+ * run in Chromium and WebKit
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ countBetween,
+ openStory,
+ tap,
+ touchDriver,
+ traceRendering,
+ withStorybook,
+} from '@astryxdesign/interaction-harness';
+
+import {nearestStop} from '../../SnapPaging/snapPagingValue';
+
+const storybook = withStorybook(test);
+
+async function open(page: Page) {
+ await openStory(page, storybook(), 'core-carousel--snap-paging-three-up', {
+ mode: 'paging',
+ });
+ const scroller = page.getByRole('region').getByRole('group').first();
+ const next = page.getByRole('button', {name: 'Scroll right'});
+ await expect(scroller).toBeVisible();
+ await expect(next).toBeEnabled();
+ return {scroller, next};
+}
+
+/** Each item's snap stop at rest, from the row's start. */
+const stopsOf = async (scroller: Locator) =>
+ scroller.evaluate(el => {
+ const box = el.getBoundingClientRect();
+ const end = el.scrollWidth - el.clientWidth;
+ return Array.from(el.children).map(child => {
+ const start = child.getBoundingClientRect().left - box.left;
+ return Math.min(start + Math.abs(el.scrollLeft), end);
+ });
+ });
+
+/** Whether any item carries the paging's translate. */
+const isHeld = async (scroller: Locator) =>
+ scroller.evaluate(el =>
+ Array.from(el.children).some(
+ child => (child as HTMLElement).style.translate !== '',
+ ),
+ );
+
+/** The items that carry an inline will-change, by index and value. */
+const layeredItems = async (scroller: Locator) =>
+ scroller.evaluate(el =>
+ Array.from(el.children)
+ .map((child, i) => [i, (child as HTMLElement).style.willChange] as const)
+ .filter(([, value]) => value !== '')
+ .map(([i, value]) => `${i}:${value}`),
+ );
+
+// Records on every frame whether the paging holds the row, and whether an
+// item has a layer then.
+async function sampleHeld(scroller: Locator): Promise<void> {
+ await scroller.evaluate(row => {
+ const held: boolean[] = [];
+ const layered: boolean[] = [];
+ Object.assign(window, {__held: held, __layered: layered});
+ const tick = () => {
+ const items = Array.from(row.children) as HTMLElement[];
+ held.push(items.some(child => child.style.translate !== ''));
+ layered.push(items.some(child => child.style.willChange !== ''));
+ if (held.length < 300) {
+ requestAnimationFrame(tick);
+ }
+ };
+ requestAnimationFrame(tick);
+ });
+}
+
+async function settled(scroller: Locator): Promise<void> {
+ await expect.poll(async () => isHeld(scroller)).toBe(false);
+}
+
+test('a scroll-right press at rest moves the row through the paging, onto the next page', async ({
+ page,
+}) => {
+ const {scroller, next} = await open(page);
+ const stops = await stopsOf(scroller);
+ await sampleHeld(scroller);
+ await next.click();
+ // Long enough for the paging's move to start and end.
+ await page.waitForTimeout(700);
+ await settled(scroller);
+ const {held, layered} = await page.evaluate(() => {
+ const frames = window as unknown as {
+ __held: boolean[];
+ __layered: boolean[];
+ };
+ return {held: frames.__held, layered: frames.__layered};
+ });
+ expect(held.filter(Boolean).length, JSON.stringify(held)).toBeGreaterThan(0);
+ // The animator gives the moving items their layers.
+ expect(
+ held.some((isHeld, frame) => isHeld && layered[frame]),
+ JSON.stringify({held, layered}),
+ ).toBe(true);
+ const at = await scroller.evaluate(el => Math.abs(el.scrollLeft));
+ expect(Math.abs(at - nearestStop(stops, at)), String(at)).toBeLessThan(0.5);
+ expect(at).toBeGreaterThan(0.5);
+ // The animator keeps the motion's layers a short while after the row
+ // rests, then takes them away. From then on no item keeps a will-change.
+ await expect
+ .poll(async () => layeredItems(scroller), {timeout: 2000})
+ .toEqual([]);
+ for (let read = 0; read < 20; read += 1) {
+ await page.waitForTimeout(100);
+ expect(await layeredItems(scroller)).toEqual([]);
+ }
+});
+
+test('a still touch that catches the press move leaves the row on a page after the lift', async ({
+ page,
+}) => {
+ const {scroller, next} = await open(page);
+ const stops = await stopsOf(scroller);
+ await next.click();
+ await page.waitForTimeout(120);
+ const box = await scroller.boundingBox();
+ if (box == null) {
+ throw new Error('no scroller');
+ }
+ const point = {x: box.x + box.width / 2, y: box.y + box.height / 2};
+ const driver = await touchDriver(page);
+ // A touch that lands and lifts without moving, held 300 ms.
+ await driver.play(tap(point, {holdMs: 300}));
+ await page.waitForTimeout(700);
+ await settled(scroller);
+ const at = await scroller.evaluate(el => Math.abs(el.scrollLeft));
+ expect(Math.abs(at - nearestStop(stops, at)), String(at)).toBeLessThan(0.5);
+});
+
+test('a press reads the row before its first write, so its own task lays out nothing', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');
+ const {next} = await open(page);
+ // The press's own task: from the click's first listener to its last.
+ await page.evaluate(() => {
+ const press = {from: 0, to: 0};
+ (window as unknown as {__press: typeof press}).__press = press;
+ document.addEventListener(
+ 'click',
+ () => {
+ press.from = performance.timeOrigin + performance.now();
+ },
+ {capture: true},
+ );
+ window.addEventListener('click', () => {
+ press.to = performance.timeOrigin + performance.now();
+ });
+ });
+ const trace = await traceRendering(page, async () => {
+ await next.click();
+ await page.waitForTimeout(100);
+ });
+ const press = await page.evaluate(
+ () => (window as unknown as {__press: {from: number; to: number}}).__press,
+ );
+ const during = countBetween(trace, press.from, press.to);
+ expect(press.to, JSON.stringify(press)).toBeGreaterThan(press.from);
+ expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0);
+});
diff --git a/packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.ts b/packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.ts
index f0bbef032b..767872ff76 100644
--- a/packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.ts
+++ b/packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.ts
@@ -3,10 +3,12 @@
/**
* @file CarouselSnapPagingEdges.interaction.browser.spec.ts
* @input The Core/Carousel three-up snap paging story in paging mode, real
- * touch flicks from the interaction harness, and a per-frame page sampler
+ * touch flicks and a press from the interaction harness, and a per-frame
+ * page sampler
* @output Proves the edge scroll buttons follow the row as shown while snap
* paging holds it. Each button comes back within two frames of the row
- * leaving its edge, before the settle hands the row back.
+ * leaving its edge, before the settle hands the row back. After a press on
+ * the end button, the start button comes back the same way.
* @position Interaction proofs for Carousel's edge buttons under snap paging,
* run in Chromium and WebKit
*/
@@ -176,3 +178,35 @@ test('the end button comes back within two frames of the held row leaving the en
expect(back - left, detail).toBeLessThanOrEqual(2);
expect(samples[back]?.held, detail).toBe(true);
});
+
+test('after a press on the end button, the start button comes back within two frames of the held row leaving the start', async ({
+ page,
+}) => {
+ const {scroller, start, end} = await open(page);
+ await expect(start).toBeDisabled();
+ await startSampling(scroller, start, end);
+ await end.click();
+ await settled(scroller);
+ await expect(start).toBeEnabled();
+ // The button can change after its frame's sample, so wait for a sample
+ // that shows it back.
+ await expect
+ .poll(async () =>
+ (await samplesOf(page)).some(sample => !sample.startDisabled),
+ )
+ .toBe(true);
+ const samples = await samplesOf(page);
+ const detail = JSON.stringify(samples.slice(0, 40));
+ const left = samples.findIndex(sample => sample.shown > 1);
+ const back = samples.findIndex(sample => !sample.startDisabled);
+ test.info().annotations.push({
+ type: 'frames from leaving the start to the start button, after a press',
+ description: String(back - left),
+ });
+ expect(left, detail).toBeGreaterThanOrEqual(0);
+ expect(back, detail).toBeGreaterThanOrEqual(left);
+ expect(back - left, detail).toBeLessThanOrEqual(2);
+ // The press moves the row through the paging, so the paging still holds
+ // the row when the button comes back.
+ expect(samples[back]?.held, detail).toBe(true);
+});
diff --git a/packages/core/src/SnapPaging/SnapPaging.test.tsx b/packages/core/src/SnapPaging/SnapPaging.test.tsx
index 07bb615470..43a5818a45 100644
--- a/packages/core/src/SnapPaging/SnapPaging.test.tsx
+++ b/packages/core/src/SnapPaging/SnapPaging.test.tsx
@@ -11,8 +11,9 @@
*/
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {createRef} from 'react';
import {act, render, renderHook, screen} from '@testing-library/react';
-import {Carousel} from '../Carousel/Carousel';
+import {Carousel, type CarouselHandle} from '../Carousel/Carousel';
import {useSnapPaging} from './SnapPaging';
import {
type HeldRow,
@@ -63,6 +64,7 @@ afterEach(() => {
const attachment = (detach = () => {}): SnapPagingAttachment => ({
detach,
+ move: () => {},
moveHeld: () => false,
});
@@ -244,6 +246,64 @@ describe('Carousel with hasSnap', () => {
expect(attached).toEqual(['first', 'first detached']);
});
+ describe('a scroll call under snap paging', () => {
+ // A paging value that records each move it is asked for.
+ function renderMoves() {
+ const moves: ((at: number, end: number) => number)[] = [];
+ const value = makeSnapPaging(() => ({
+ ...attachment(),
+ move: target => {
+ moves.push(target);
+ },
+ }));
+ const handle = createRef<CarouselHandle>();
+ render(
+ <Carousel aria-label="Items" hasSnap={value} handleRef={handle}>
+ <div>One</div>
+ <div>Two</div>
+ <div>Three</div>
+ </Carousel>,
+ );
+ const row = scroller();
+ const scrollTo = vi.fn();
+ const scrollBy = vi.fn();
+ row.scrollTo = scrollTo;
+ row.scrollBy = scrollBy;
+ return {moves, handle, scrollTo, scrollBy};
+ }
+
+ it('moves the row at rest through the paging, not with a native smooth scroll', () => {
+ const {moves, handle, scrollTo, scrollBy} = renderMoves();
+ act(() => handle.current?.scrollNext());
+ act(() => handle.current?.scrollPrev());
+ expect(moves).toHaveLength(2);
+ expect(scrollTo).not.toHaveBeenCalled();
+ expect(scrollBy).not.toHaveBeenCalled();
+ });
+
+ it('moves the row through the paging for a scroll to an item', () => {
+ const {moves, handle, scrollTo, scrollBy} = renderMoves();
+ act(() => handle.current?.scrollTo(2));
+ expect(moves).toHaveLength(1);
+ expect(scrollTo).not.toHaveBeenCalled();
+ expect(scrollBy).not.toHaveBeenCalled();
+ });
+
+ it('moves a scroll to an item onto its snap stop, inside the scroll padding', () => {
+ const {moves, handle} = renderMoves();
+ const row = scroller();
+ // Three 100 px items in a 300 px row with 16 px of scroll padding.
+ row.style.setProperty('scroll-padding-left', '16px');
+ row.getBoundingClientRect = () => new DOMRect(0, 0, 300, 100);
+ Array.from(row.children).forEach((child, i) => {
+ child.getBoundingClientRect = () => new DOMRect(i * 100, 0, 100, 100);
+ });
+ act(() => handle.current?.scrollTo(2));
+ // The stop is the item's start less the padding, not its border edge.
+ expect(moves[0](0, 500)).toBe(184);
+ });
+ });
+
describe('the edge buttons follow a held row as shown', () => {
// A paging value that reports a held row on demand, as the pager does on
// each frame of a hold.
diff --git a/packages/core/src/SnapPaging/SnapPaging.ts b/packages/core/src/SnapPaging/SnapPaging.ts
index 5b0c50179f..46f0a5558a 100644
--- a/packages/core/src/SnapPaging/SnapPaging.ts
+++ b/packages/core/src/SnapPaging/SnapPaging.ts
@@ -135,8 +135,9 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
(child): child is HTMLElement => child instanceof HTMLElement,
);
const isRtl = () => isRtlElement(element);
- // The pager's x for a position, and what a child's translate adds to it.
- const sign = () => (isRtl() ? -1 : 1);
+ // The pager's x for a position, and what a child's translate adds to it. A
+ // held row keeps the direction it was taken over with.
+ const sign = () => (isMoving ? heldSign : isRtl() ? -1 : 1);
const xOf = (position: number) => -sign() * position;
const nativePosition = () => Math.abs(element.scrollLeft);
const padding = () => {
@@ -187,8 +188,14 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
}
function place(at: number): void {
+ const x = toChild(xOf(at));
for (const child of children()) {
- animatorFor(child).set({x: toChild(xOf(at))});
+ const animator = animatorFor(child);
+ // A set reads the element's style back, so a child already there
+ // gets none.
+ if (animator.get('x') !== x) {
+ animator.set({x});
+ }
}
}
@@ -196,27 +203,23 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
if (isMoving) {
return;
}
- heldOffset = nativePosition();
- heldTravel = Math.max(0, element.scrollWidth - element.clientWidth);
+ // Every read comes before the first write, so the takeover forces no
+ // layout of its own.
+ const offset = nativePosition();
+ const rowTravel = Math.max(0, element.scrollWidth - element.clientWidth);
+ const rowSign = isRtl() ? -1 : 1;
+ const items = children();
+ heldOffset = offset;
+ heldTravel = rowTravel;
+ heldSign = rowSign;
+ lead = items[0] ?? null;
isMoving = true;
// A snap type would snap the row again as its children move.
ownSnapType = element.style.getPropertyValue('scroll-snap-type');
element.style.setProperty('scroll-snap-type', 'none');
- // A flick moves one view at most: the items within a view of the
- // viewport get their own layers, and no others.
- const box = element.getBoundingClientRect();
- for (const child of children()) {
- const rect = child.getBoundingClientRect();
- if (
- rect.right >= box.left - box.width &&
- rect.left <= box.right + box.width
- ) {
- child.style.setProperty('will-change', 'transform');
- }
- }
+ // Each child's animator gives it a layer while it moves and takes the layer
+ // away after the motion. So the takeover writes no will-change itself.
place(heldOffset);
- heldSign = sign();
- lead = children()[0] ?? null;
follow();
}
@@ -230,7 +233,6 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
animator.stop(['x']);
animator.set({x: 0});
child.style.removeProperty('translate');
- child.style.removeProperty('will-change');
}
isMoving = false;
if (ownSnapType === '') {
@@ -324,8 +326,38 @@ function attachPaging(
onHeld?: HeldRowListener,
): SnapPagingAttachment {
const track = childTrack(element, onHeld);
+ // A child's animator reads its stylesheet's will-change in a later task. So
+ // a press that moves the row reads no style in its own task.
+ for (const child of Array.from(element.children)) {
+ if (child instanceof HTMLElement) {
+ animatorFor(child);
+ }
+ }
// The stop that view pages count from, set when a gesture takes over.
let anchor = 0;
+ // The row's stops and view width, read before a takeover's first write.
+ let measured: {stops: number[]; viewWidth: number} | null = null;
+ // Takes the row over where it is shown, at `at`, on the page nearest it.
+ const takeOverShown = (at: number) => {
+ // Every read comes before the takeover's first write.
+ const stops = track.stops();
+ const viewWidth = track.viewWidth();
+ anchor = stops.reduce(
+ (best, stop, i) =>
+ Math.abs(stop - at) < Math.abs(stops[best] - at) ? i : best,
+ 0,
+ );
+ measured = {stops, viewWidth};
+ pager.setOptions({});
+ measured = null;
+ // The pager learns its page while the row is at rest, which moves
+ // nothing. The takeover then holds the row where it is shown.
+ pager.goTo(pager.nearestPage(at), {
+ animated: false,
+ reason: 'controlled',
+ });
+ track.takeOver();
+ };
const pager = createPager(
{
count: 1,
@@ -334,32 +366,19 @@ function attachPaging(
// the pointer kinds.
panOptions: {allowedPointerTypes: ['touch', 'pen']},
measurePages: () => {
- const stops = track.stops();
+ const stops = measured?.stops ?? track.stops();
return (options.pages ?? 'view') === 'item'
? stops
: viewPages(
stops,
Math.min(anchor, stops.length - 1),
- track.viewWidth(),
+ measured?.viewWidth ?? track.viewWidth(),
);
},
shouldBeginPan: () => {
+ // The finger catches the row where it is shown.
if (!track.isMoving) {
- const at = track.position();
- const stops = track.stops();
- anchor = stops.reduce(
- (best, stop, i) =>
- Math.abs(stop - at) < Math.abs(stops[best] - at) ? i : best,
- 0,
- );
- track.takeOver();
- pager.setOptions({});
- pager.goTo(pager.nearestPage(at), {
- animated: false,
- reason: 'controlled',
- });
- // The finger catches the row where it is shown.
- track.place(at);
+ takeOverShown(track.position());
}
return true;
},
@@ -378,6 +397,23 @@ function attachPaging(
pager.dispose();
track.handBack();
},
+ move: target => {
+ // A finger on the row keeps it.
+ if (pager.isDragging) {
+ return;
+ }
+ // The target reads the row too, so every read comes before the
+ // takeover's first write.
+ const at = track.position();
+ const end = track.travel();
+ const to = Math.min(Math.max(target(at, end), 0), end);
+ // A move from rest is the pager's own too. So a touch catches it as it
+ // catches a settle, and the release rests on a page.
+ if (!track.isMoving) {
+ takeOverShown(at);
+ }
+ pager.goTo(pager.nearestPage(to), {offset: to});
+ },
moveHeld: target => {
if (!track.isMoving) {
return false;
diff --git a/packages/core/src/SnapPaging/snapPagingValue.ts b/packages/core/src/SnapPaging/snapPagingValue.ts
index eb702deaa0..3f4e7d0d11 100644
--- a/packages/core/src/SnapPaging/snapPagingValue.ts
+++ b/packages/core/src/SnapPaging/snapPagingValue.ts
@@ -4,8 +4,8 @@
* @file snapPagingValue.ts
* @input A scrolling row of snap items
* @output The `SnapPaging` value, the calls Carousel makes on it
- * (`isSnapPaging`, `attachSnapPaging`, `moveHeldSnapPaging`), where a held
- * row is shown, and stops
+ * (`isSnapPaging`, `attachSnapPaging`, `moveSnapPaging`,
+ * `moveHeldSnapPaging`), where a held row is shown, and stops
* @position Carousel's only link to snap paging. It imports no pager code,
* so a Carousel without `hasSnap={useSnapPaging()}` bundles none
*/
@@ -35,6 +35,7 @@ export interface SnapPaging {
/** The paging attached to one row. */
export interface SnapPagingAttachment {
readonly detach: () => void;
+ readonly move: (target: (at: number, end: number) => number) => void;
readonly moveHeld: (target: (at: number, end: number) => number) => boolean;
}
@@ -95,6 +96,23 @@ export function attachSnapPaging(
};
}
+/**
+ * Moves the row through the paging to `target(shown, end)`, an offset toward
+ * the end, and takes the row over first when it is at rest. `end` is its
+ * travel. False when no paging is attached.
+ */
+export function moveSnapPaging(
+ element: HTMLElement,
+ target: (shown: number, end: number) => number,
+): boolean {
+ const attachment = attachments.get(element);
+ if (attachment == null) {
+ return false;
+ }
+ attachment.move(target);
+ return true;
+}
+
/**
* Moves a row the paging holds to `target(shown, end)`, an offset toward the
* end. `end` is its travel when taken over. False when it is not held.
diff --git a/packages/core/src/hooks/useScrollOverflow.ts b/packages/core/src/hooks/useScrollOverflow.ts
index 44a94ee796..305d66bf97 100644
--- a/packages/core/src/hooks/useScrollOverflow.ts
+++ b/packages/core/src/hooks/useScrollOverflow.ts
@@ -160,7 +160,9 @@ export function useShownScrollOverflow() {
// again.
const measure = useCallback(() => {
const el = elRef.current;
- if (el && isRendered(el)) {
+ // A held row's edges come from where it is shown, which reads no layout.
+ // So the paging's own style writes force no layout here.
+ if (el && (shownRef.current != null || isRendered(el))) {
measureNow(el);
}
}, [measureNow]);
@@ -190,7 +192,8 @@ export function useShownScrollOverflow() {
shownRef.current = null;
return;
}
- // The reported edges stand until then, so no edge flickers.
+ // Keep the reported edges until the next frame, when the scroll offset
+ // is current. Otherwise an edge flickers.
releaseFrameRef.current = requestAnimationFrame(() => {
shownRef.current = null;
measure();