Skip to content

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

TypeScript

fix(SnapPaging): a stop within half a step of the end is the end page (#10591)

Christopher Chedeau9218a4598edf
diff --git a/.changeset/snap-paging-end-page.md b/.changeset/snap-paging-end-page.md
new file mode 100644
index 0000000000..5a20ef9ba6
--- /dev/null
+++ b/.changeset/snap-paging-end-page.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Carousel snap paging: a stop that sits within half a step of the row's end is part of the last page, so a flick, a wheel or a key never rests a pixel short of the end, and a step back from the end moves a full step.
+
+@vjeux
diff --git a/docs/specs/components/Carousel/Carousel.spec.md b/docs/specs/components/Carousel/Carousel.spec.md
index a6fe6e2dea..10ffea4efb 100644
--- a/docs/specs/components/Carousel/Carousel.spec.md
+++ b/docs/specs/components/Carousel/Carousel.spec.md
@@ -104,17 +104,17 @@ Consumer migration instructions belong in consumer docs and release notes.
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | ------------------ |
-| FR1 | An edge scroll button whose direction has run out is hidden. While hidden it takes no tab stop and is not exposed to assistive technology. It stays mounted so layout does not shift. This is removal under `spec:AST-085` FR4, not a disabled control. | DEC-1 | settled |
-| FR2 | When the focused edge scroll button runs out, focus moves to the scroll area without scrolling it. This holds when the content no longer overflows and the scroll area is out of the tab order (`spec:AST-025` FR12): it still takes focus programmatically. Focus never lands on the page body or on a hidden button. | DEC-1; `spec:AST-085` FR4 | settled |
-| FR3 | The handoff happens once per edge transition, and only while the edge button held focus. An edge reached by swipe, resize, or wheel while focus is elsewhere moves nothing. | `architecture:interaction-modality` INV8 | settled |
-| FR4 | An edge scroll button that is available behaves as an ordinary Button. | `family:buttons` | settled |
-| 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). A `SnapPaging` value is recognized through a registered key, and its type carries one optional phantom member typed `never`, so the package's value and a swizzled copy's match (`spec:AST-110` FR3); the member is never present at runtime and the value stays opaque. | 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 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 |
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | ------------------ |
+| FR1 | An edge scroll button whose direction has run out is hidden. While hidden it takes no tab stop and is not exposed to assistive technology. It stays mounted so layout does not shift. This is removal under `spec:AST-085` FR4, not a disabled control. | DEC-1 | settled |
+| FR2 | When the focused edge scroll button runs out, focus moves to the scroll area without scrolling it. This holds when the content no longer overflows and the scroll area is out of the tab order (`spec:AST-025` FR12): it still takes focus programmatically. Focus never lands on the page body or on a hidden button. | DEC-1; `spec:AST-085` FR4 | settled |
+| FR3 | The handoff happens once per edge transition, and only while the edge button held focus. An edge reached by swipe, resize, or wheel while focus is elsewhere moves nothing. | `architecture:interaction-modality` INV8 | settled |
+| FR4 | An edge scroll button that is available behaves as an ordinary Button. | `family:buttons` | settled |
+| 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, with FR7's end-page exception, 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). A `SnapPaging` value is recognized through a registered key, and its type carries one optional phantom member typed `never`, so the package's value and a swizzled copy's match (`spec:AST-110` FR3); the member is never present at runtime and the value stays opaque. | 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, except a stop within half its preceding step of the end, which joins the end's page. 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 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
@@ -127,6 +127,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| One item per view, snap paging | A flick moves one item, as a UIKit paging scroll view moves one page; `{pages: 'item'}` gives the same | — |
| Three items per view, snap paging | A flick moves one view, settling on the item start edge nearest one viewport on; with `{pages: 'item'}` it moves one item; an edge button moves about one view | — |
| Partial last page | The last page rests where the row ends; no empty space | — |
+| Split end | The end's page is the page the end rounds to: a stop within half its preceding step of the end rests where the row ends (FR7); native snap skips it | — |
| Right-to-left | Pages run from the inline start; stops and flick directions mirror | — |
| `hasSnap={true}` | Native snap; no pager code loaded or run | Platform momentum |
@@ -171,6 +172,7 @@ visual evidence.
| 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 | — |
+| FR7 | Unit tests of the stops; real-browser tests in Chromium and WebKit under a finger and a mouse wheel | a stop within half its preceding step of the end; a resize that moves it further from the end | A flick or a wheel that rests on that stop, a step back from the end shorter than a full step, or that stop still skipped by native snap once further from the end 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 | — |
diff --git a/packages/core/src/SnapPaging/SnapPaging.test.tsx b/packages/core/src/SnapPaging/SnapPaging.test.tsx
index b556fd3936..accea5340f 100644
--- a/packages/core/src/SnapPaging/SnapPaging.test.tsx
+++ b/packages/core/src/SnapPaging/SnapPaging.test.tsx
@@ -22,6 +22,8 @@ import {
makeSnapPaging,
nearestStop,
type SnapPagingAttachment,
+ snapPages,
+ snapStops,
} from './snapPagingValue';
class MockResizeObserver {
@@ -226,6 +228,40 @@ describe('Carousel with hasSnap', () => {
expect(nearestStop([], 42)).toBe(42);
});
+ describe('the end page', () => {
+ // A row 299 px wide holds seven items 94.67 px wide and 8 px apart. The
+ // fifth item's stop, 410.67, sits 1.33 px before the row's end.
+ function row() {
+ const element = document.createElement('div');
+ const box = {left: 0, right: 299, width: 299} as DOMRect;
+ element.getBoundingClientRect = () => box;
+ for (let i = 0; i < 7; i++) {
+ const item = document.createElement('div');
+ const left = i * (94.67 + 8);
+ item.getBoundingClientRect = () =>
+ ({left, right: left + 94.67, width: 94.67}) as DOMRect;
+ element.append(item);
+ }
+ document.body.append(element);
+ return element;
+ }
+ const rounded = (stops: number[]) => stops.map(stop => Math.round(stop));
+
+ it('a stop within half its preceding step of the end is the end page, which rests where the row ends', () => {
+ expect(rounded(snapStops(row(), 0, 412))).toEqual([
+ 0, 103, 205, 308, 412,
+ ]);
+ });
+
+ it('native snap skips that stop until the stop is further from the end than half its step', () => {
+ const element = row();
+ expect(snapPages(element, 0, 412).skipped).toEqual([element.children[4]]);
+ const split = snapPages(element, 0, 471);
+ expect(rounded(split.stops)).toEqual([0, 103, 205, 308, 411, 471]);
+ expect(split.skipped).toEqual([]);
+ });
+ });
+
it('attaches once: a new paging value on a later render attaches nothing again', () => {
const attached: string[] = [];
const first = makeSnapPaging(() => {
diff --git a/packages/core/src/SnapPaging/SnapPaging.ts b/packages/core/src/SnapPaging/SnapPaging.ts
index 63a3185a66..516e80e996 100644
--- a/packages/core/src/SnapPaging/SnapPaging.ts
+++ b/packages/core/src/SnapPaging/SnapPaging.ts
@@ -17,14 +17,17 @@ import {createPager, type PagerAnimator} from '../hooks/usePager';
import {isRtlElement} from '../hooks/isRtlElement';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {animatorFor, type MotionHandle} from '../motion/animator';
+import {observeMutations} from '../utils/sharedMutationObserver';
+import {observeResize} from '../utils/sharedResizeObserver';
import {
type HeldRowListener,
makeSnapPaging,
rowScale,
+ type SnapPages,
type SnapPaging,
type SnapPagingAttachment,
type SnapPagingOptions,
- snapStops,
+ snapPages,
} from './snapPagingValue';
export type {SnapPaging, SnapPagingOptions} from './snapPagingValue';
@@ -229,8 +232,12 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
: Math.max(0, element.scrollWidth - element.clientWidth);
}
+ function pages(): SnapPages {
+ return snapPages(element, position(), travel());
+ }
+
function stops(): number[] {
- return snapStops(element, position(), travel());
+ return pages().stops;
}
function viewWidth(): number {
@@ -279,7 +286,10 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
follow();
}
- function handBack(): void {
+ // `beforeSnap` runs once the children are back in place and before the
+ // row's snap type returns, so the hand-back's scroll snaps on what it
+ // writes.
+ function handBack(beforeSnap?: () => void): void {
if (!isMoving) {
return;
}
@@ -291,6 +301,7 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
child.style.removeProperty('translate');
}
isMoving = false;
+ beforeSnap?.();
if (ownSnapType === '') {
element.style.removeProperty('scroll-snap-type');
} else {
@@ -364,6 +375,7 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
position,
travel,
remeasure,
+ pages,
stops,
viewWidth,
place,
@@ -394,6 +406,52 @@ function attachPaging(
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;
+ // Native snap skips each item whose stop the end's page takes. So a wheel,
+ // a key or a scroll rests on the same pages as a flick. Each skipped item
+ // gets its own inline value and priority back when its stop leaves the
+ // end's page or the paging detaches.
+ const skipped = new Map<HTMLElement, {value: string; priority: string}>();
+ const skip = (items: ReadonlyArray<Element>) => {
+ for (const [item, own] of skipped) {
+ if (!items.includes(item)) {
+ skipped.delete(item);
+ if (own.value === '') {
+ item.style.removeProperty('scroll-snap-align');
+ } else {
+ item.style.setProperty('scroll-snap-align', own.value, own.priority);
+ }
+ }
+ }
+ for (const item of items) {
+ if (item instanceof HTMLElement && !skipped.has(item)) {
+ skipped.set(item, {
+ value: item.style.getPropertyValue('scroll-snap-align'),
+ priority: item.style.getPropertyPriority('scroll-snap-align'),
+ });
+ item.style.setProperty('scroll-snap-align', 'none');
+ }
+ }
+ };
+ // The skip follows the stops at rest, at most once a frame. A change while
+ // the paging holds the row waits for the hand-back, which writes it before
+ // the row snaps again.
+ let resnapFrame: number | null = null;
+ let isResnapDue = false;
+ const resnap = () => {
+ if (track.isMoving) {
+ isResnapDue = true;
+ return;
+ }
+ resnapFrame ??= requestAnimationFrame(() => {
+ resnapFrame = null;
+ if (track.isMoving) {
+ isResnapDue = true;
+ return;
+ }
+ isResnapDue = false;
+ skip(track.pages().skipped);
+ });
+ };
const takeOverShown = (at: number) => {
// Every read comes before the takeover's first write.
const stops = track.stops();
@@ -425,6 +483,9 @@ function attachPaging(
// A resize while the row is held moves its travel first.
track.remeasure();
const stops = measured?.stops ?? track.stops();
+ // Native snap follows the new stops. The skip writes in a later
+ // frame, so this read stays ahead of any write.
+ resnap();
return (options.pages ?? 'view') === 'item'
? stops
: viewPages(
@@ -442,18 +503,49 @@ function attachPaging(
},
onSettle: () => {
if (!pager.isDragging && !pager.isSettling) {
- track.handBack();
+ track.handBack(
+ isResnapDue
+ ? () => {
+ isResnapDue = false;
+ skip(track.pages().skipped);
+ }
+ : undefined,
+ );
}
},
},
{animator: track.animator},
);
const detach = pager.attach(element, element);
+ // Items that change while the row keeps its size move the stops too.
+ let unobserveItems: (() => void)[] = [];
+ const observeItems = () => {
+ for (const unobserve of unobserveItems) {
+ unobserve();
+ }
+ unobserveItems = Array.from(element.children, item =>
+ observeResize(item, resnap),
+ );
+ };
+ const unobserveList = observeMutations(element, {childList: true}, () => {
+ observeItems();
+ resnap();
+ });
+ observeItems();
return {
detach: () => {
detach();
pager.dispose();
+ unobserveList();
+ for (const unobserve of unobserveItems) {
+ unobserve();
+ }
+ if (resnapFrame != null) {
+ cancelAnimationFrame(resnapFrame);
+ resnapFrame = null;
+ }
track.handBack();
+ skip([]);
},
move: target => {
// A finger on the row keeps it.
diff --git a/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts b/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts
index b11231d3d9..92df1f564c 100644
--- a/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts
+++ b/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts
@@ -561,6 +561,200 @@ test('the scroll offset holds through a swipe, and the settle hands it on', asyn
await expect.poll(async () => offset(scroller)).toBeCloseTo(stops[6], 0);
});
+/**
+ * The partial last page with its row 1 px narrower. The fifth item's stop sits
+ * 1.37 px before the row's end, within half its step of it.
+ */
+async function openSplitEnd(page: Page, mode: Mode) {
+ const {scroller} = await open(page, 'snap-paging-partial-last-page', mode);
+ const before = await travel(scroller);
+ await scroller.evaluate(el => {
+ el.style.width = `${el.clientWidth - 1}px`;
+ });
+ await expect
+ .poll(async () => travel(scroller), {
+ message: 'the row is 1 px narrower',
+ timeout: 5000,
+ })
+ .toBe(before + 1);
+ return scroller;
+}
+
+/** The fifth item's native snap alignment. */
+const fifthAlign = async (scroller: Locator) =>
+ scroller.evaluate(el => getComputedStyle(el.children[4]).scrollSnapAlign);
+
+/** Adds an eighth item to the row, a copy of its last. */
+async function addItem(scroller: Locator) {
+ await scroller.evaluate(el => {
+ el.append((el.lastElementChild as HTMLElement).cloneNode(true));
+ });
+}
+
+/**
+ * A flick of the row toward its start (`back`) or its end. Past the pan's
+ * start, its 70 px still move the row more than half a step. So the rest page
+ * is the same whatever speed the page reads at the lift.
+ */
+async function flick(
+ page: Page,
+ scroller: Locator,
+ direction: 'back' | 'forward',
+) {
+ const box = await scroller.boundingBox();
+ if (box == null) {
+ throw new Error('no scroller');
+ }
+ const y = box.y + box.height / 2;
+ const from = {x: box.x + box.width / 2, y};
+ const to = {x: from.x + (direction === 'back' ? 70 : -70), y};
+ const driver = await touchDriver(page);
+ await driver.play(drag(from, to, {durationMs: 60}), {pacing: 'spacing'});
+}
+
+test('a stop within half its step of the end is the end page: a flick back from the end moves a full step', async ({
+ page,
+}) => {
+ const scroller = await openSplitEnd(page, 'item');
+ const stops = await stopsOf(scroller);
+ await scroller.evaluate(el => {
+ el.scrollTo({left: el.scrollWidth - el.clientWidth, behavior: 'instant'});
+ });
+ await expect
+ .poll(async () => offset(scroller), {
+ message: 'the row starts at its end',
+ timeout: 5000,
+ })
+ .toBeCloseTo(await travel(scroller), 0);
+ await flick(page, scroller, 'back');
+ await settled(scroller);
+ expect(await offset(scroller)).toBeCloseTo(stops[3], 0);
+});
+
+test('a stop within half its step of the end is the end page: a flick onto it rests where the row ends', async ({
+ page,
+}) => {
+ const scroller = await openSplitEnd(page, 'item');
+ const stops = await stopsOf(scroller);
+ await scroller.evaluate((el, left) => {
+ el.scrollTo({left, behavior: 'instant'});
+ }, stops[3]);
+ await expect
+ .poll(async () => offset(scroller), {
+ message: 'the row starts one step before its end page',
+ timeout: 5000,
+ })
+ .toBeCloseTo(stops[3], 0);
+ await flick(page, scroller, 'forward');
+ await settled(scroller);
+ expect(await offset(scroller)).toBeCloseTo(await travel(scroller), 0);
+});
+
+test('a resize that moves the stop further from the end than half its step gives it back to native snap and to flicks', async ({
+ page,
+}) => {
+ const scroller = await openSplitEnd(page, 'item');
+ await expect
+ .poll(async () => fifthAlign(scroller), {
+ message: "native snap skips the fifth item's stop",
+ timeout: 5000,
+ })
+ .toBe('none');
+ // 59 px narrower still: the fifth item's stop sits 60 px before the end.
+ const before = await travel(scroller);
+ await scroller.evaluate(el => {
+ el.style.width = `${el.clientWidth - 59}px`;
+ });
+ await expect
+ .poll(async () => travel(scroller), {
+ message: 'the row is 59 px narrower still',
+ timeout: 5000,
+ })
+ .toBe(before + 59);
+ await expect
+ .poll(async () => fifthAlign(scroller), {
+ message: "native snap takes the fifth item's stop back",
+ timeout: 5000,
+ })
+ .toMatch(/^start/);
+ const stops = await stopsOf(scroller);
+ await scroller.evaluate(el => {
+ el.scrollTo({left: el.scrollWidth - el.clientWidth, behavior: 'instant'});
+ });
+ await expect
+ .poll(async () => offset(scroller), {
+ message: 'the row starts at its end',
+ timeout: 5000,
+ })
+ .toBeCloseTo(await travel(scroller), 0);
+ await flick(page, scroller, 'back');
+ await settled(scroller);
+ expect(await offset(scroller)).toBeCloseTo(stops[4], 0);
+});
+
+test('an item added while the row settles: once it rests, native snap follows the new stops', async ({
+ page,
+}) => {
+ const scroller = await openSplitEnd(page, 'item');
+ await expect
+ .poll(async () => fifthAlign(scroller), {
+ message: "native snap skips the fifth item's stop",
+ timeout: 5000,
+ })
+ .toBe('none');
+ const stops = await stopsOf(scroller);
+ await scroller.evaluate((el, left) => {
+ el.scrollTo({left, behavior: 'instant'});
+ }, stops[3]);
+ await expect
+ .poll(async () => offset(scroller), {
+ message: 'the row starts one step before its end page',
+ timeout: 5000,
+ })
+ .toBeCloseTo(stops[3], 0);
+ // The page adds an eighth item 60 ms after the lift, while the row
+ // settles. The fifth item's stop then sits a full step from the end.
+ await scroller.evaluate(el => {
+ el.addEventListener(
+ 'touchend',
+ () => {
+ setTimeout(() => {
+ (window as unknown as {heldAtAdd?: boolean}).heldAtAdd = Array.from(
+ el.children,
+ ).some(child => (child as HTMLElement).style.translate !== '');
+ el.append((el.lastElementChild as HTMLElement).cloneNode(true));
+ }, 60);
+ },
+ {once: true},
+ );
+ });
+ await flick(page, scroller, 'forward');
+ await expect
+ .poll(
+ async () =>
+ page.evaluate(
+ () => (window as unknown as {heldAtAdd?: boolean}).heldAtAdd,
+ ),
+ {message: 'the item lands while the paging holds the row', timeout: 5000},
+ )
+ .toBe(true);
+ await settled(scroller);
+ await expect
+ .poll(async () => fifthAlign(scroller), {
+ message:
+ "native snap takes the fifth item's stop back once the row rests",
+ timeout: 5000,
+ })
+ .toMatch(/^start/);
+ // The hand-back snaps on the new stops: the row rests on the fifth item.
+ await expect
+ .poll(async () => offset(scroller), {
+ message: "the row rests on the fifth item's stop",
+ timeout: 5000,
+ })
+ .toBeCloseTo(stops[4], 0);
+});
+
test('an edge button steps about one view: the viewport less half an item, on the nearest stop', async ({
page,
}) => {
@@ -767,6 +961,93 @@ test.describe("a touch that lands on a flick's settle", () => {
test.describe('with a finger and a mouse', () => {
test.use({hasTouch: true, isMobile: false});
+ test('native snap skips a stop within half its step of the end: ArrowLeft at the end moves at least a full step', async ({
+ page,
+ }) => {
+ const scroller = await openSplitEnd(page, 'paging');
+ const stops = await stopsOf(scroller);
+ await scroller.evaluate(el => {
+ el.scrollTo({left: el.scrollWidth - el.clientWidth, behavior: 'instant'});
+ });
+ await expect
+ .poll(async () => offset(scroller), {
+ message: 'the row starts at its end',
+ timeout: 5000,
+ })
+ .toBeCloseTo(await travel(scroller), 0);
+ await scroller.focus();
+ await page.keyboard.press('ArrowLeft');
+ await expect
+ .poll(async () => offset(scroller), {
+ message: 'ArrowLeft rests a full step back or more',
+ timeout: 5000,
+ })
+ .toBeLessThan(stops[3] + 0.5);
+ });
+
+ test('an item added at rest gives the stop before the end back to native snap: ArrowRight steps onto it', async ({
+ page,
+ }) => {
+ const scroller = await openSplitEnd(page, 'paging');
+ await expect
+ .poll(async () => fifthAlign(scroller), {
+ message: "native snap skips the fifth item's stop",
+ timeout: 5000,
+ })
+ .toBe('none');
+ await addItem(scroller);
+ await expect
+ .poll(async () => fifthAlign(scroller), {
+ message: "native snap takes the fifth item's stop back",
+ timeout: 5000,
+ })
+ .toMatch(/^start/);
+ const stops = await stopsOf(scroller);
+ await scroller.evaluate((el, left) => {
+ el.scrollTo({left, behavior: 'instant'});
+ }, stops[3]);
+ await expect
+ .poll(async () => offset(scroller), {
+ message: 'the row starts at the fourth item',
+ timeout: 5000,
+ })
+ .toBeCloseTo(stops[3], 0);
+ await scroller.focus();
+ await page.keyboard.press('ArrowRight');
+ await expect
+ .poll(async () => offset(scroller), {
+ message: "ArrowRight rests on the fifth item's stop",
+ timeout: 5000,
+ })
+ .toBeCloseTo(stops[4], 0);
+ });
+
+ test('native snap skips a stop within half its step of the end: a wheel back from the end moves at least a full step', async ({
+ page,
+ }) => {
+ const scroller = await openSplitEnd(page, 'paging');
+ const stops = await stopsOf(scroller);
+ await scroller.evaluate(el => {
+ el.scrollTo({left: el.scrollWidth - el.clientWidth, behavior: 'instant'});
+ });
+ await expect
+ .poll(async () => offset(scroller), {
+ message: 'the row starts at its end',
+ timeout: 5000,
+ })
+ .toBeCloseTo(await travel(scroller), 0);
+ await scroller.hover();
+ await page.keyboard.down('Shift');
+ await page.mouse.wheel(0, -150);
+ await page.keyboard.up('Shift');
+ await expect
+ .poll(async () => offset(scroller), {
+ message: 'the wheel rests a full step back or more',
+ timeout: 5000,
+ })
+ .toBeLessThan(stops[3] + 0.5);
+ });
+
test('Shift+wheel during an edge press goes to a stop', async ({page}) => {
const {scroller} = await open(page, 'snap-paging-three-up', 'paging', {
freeze: true,
diff --git a/packages/core/src/SnapPaging/snapPagingValue.ts b/packages/core/src/SnapPaging/snapPagingValue.ts
index 8e2abd490a..4df19972d8 100644
--- a/packages/core/src/SnapPaging/snapPagingValue.ts
+++ b/packages/core/src/SnapPaging/snapPagingValue.ts
@@ -149,16 +149,62 @@ export function rowScale(element: HTMLElement, box: DOMRect): number {
: 1;
}
+/** A row's pages: one stop each, and the items whose stops native snap skips. */
+export interface SnapPages {
+ readonly stops: number[];
+ readonly skipped: Element[];
+}
+
/**
- * Each item's snap stop: the scroll offset that aligns its start edge with
- * the scroll padding, clamped to `end`. Read from the items' rects, with the
- * position `shown` added back. Stops closer than half a pixel are one stop.
+ * The row's stops, one per page (`snapPages`). Read from the items' rects,
+ * with the position `shown` added back.
*/
export function snapStops(
element: HTMLElement,
shown: number,
end: number,
): number[] {
+ return snapPages(element, shown, end).stops;
+}
+
+/**
+ * The row's stops, one per page. Stops closer than half a pixel are one stop.
+ * The end's page is the page that the end rounds to. So a stop within half
+ * its preceding step of the end is that page, which rests where the row
+ * ends. Native snap skips the items of that stop (`skipped`).
+ */
+export function snapPages(
+ element: HTMLElement,
+ shown: number,
+ end: number,
+): SnapPages {
+ const stops: number[] = [];
+ const owners: Element[][] = [];
+ for (const {item, stop} of itemStops(element, shown, end)) {
+ if (stops.length === 0 || stop > stops[stops.length - 1] + 0.5) {
+ stops.push(stop);
+ owners.push([item]);
+ } else {
+ owners[owners.length - 1].push(item);
+ }
+ }
+ const n = stops.length;
+ if (
+ n >= 3 &&
+ stops[n - 1] >= end - 0.5 &&
+ stops[n - 1] - stops[n - 2] < (stops[n - 2] - stops[n - 3]) / 2
+ ) {
+ stops.splice(n - 2, 1);
+ return {stops, skipped: owners[n - 2]};
+ }
+ return {stops: n > 0 ? stops : [0], skipped: []};
+}
+
+function itemStops(
+ element: HTMLElement,
+ shown: number,
+ end: number,
+): {item: Element; stop: number}[] {
const rtl = isRtlElement(element);
const box = element.getBoundingClientRect();
const scale = rowScale(element, box);
@@ -170,18 +216,13 @@ export function snapStops(
Number.parseFloat(
rtl ? style.scrollPaddingRight : style.scrollPaddingLeft,
) || 0;
- const stops: number[] = [];
- for (const child of Array.from(element.children)) {
- const rect = child.getBoundingClientRect();
+ return Array.from(element.children, item => {
+ const rect = item.getBoundingClientRect();
const fromEdge =
(rtl ? box.right - rect.right : rect.left - box.left) / scale;
- const stop = Math.min(
- Math.max(fromEdge - border + shown - padding, 0),
- end,
- );
- if (stops.length === 0 || stop > stops[stops.length - 1] + 0.5) {
- stops.push(stop);
- }
- }
- return stops.length > 0 ? stops : [0];
+ return {
+ item,
+ stop: Math.min(Math.max(fromEdge - border + shown - padding, 0), end),
+ };
+ });
}