Skip to content

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

TypeScript

fix(SnapPaging): a held row's travel follows a resize (#10425)

Christopher Chedeau1e268c32c60f
diff --git a/.changeset/snap-paging-held-resize-travel.md b/.changeset/snap-paging-held-resize-travel.md
new file mode 100644
index 0000000000..42dd4b792c
--- /dev/null
+++ b/.changeset/snap-paging-held-resize-travel.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Carousel paging: a row that narrows while a finger holds it now rests where the row ends, instead of short of its end by as much as it narrowed.
+
+@vjeux
diff --git a/packages/core/src/SnapPaging/SnapPaging.ts b/packages/core/src/SnapPaging/SnapPaging.ts
index 46f0a5558a..fd8f877a29 100644
--- a/packages/core/src/SnapPaging/SnapPaging.ts
+++ b/packages/core/src/SnapPaging/SnapPaging.ts
@@ -20,6 +20,7 @@ import {animatorFor, type MotionHandle} from '../motion/animator';
import {
type HeldRowListener,
makeSnapPaging,
+ rowScale,
type SnapPaging,
type SnapPagingAttachment,
type SnapPagingOptions,
@@ -128,6 +129,12 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
let heldSign = 1;
let lead: HTMLElement | null = null;
let followFrame = 0;
+ // The row's travel, the children's span and the row's width at the
+ // takeover. A resize while the row is held moves the travel by the change in
+ // span and width.
+ let takeoverTravel = 0;
+ let heldSpan = 0;
+ let heldWidth = 0;
// The row's own inline snap type, back at the hand-back.
let ownSnapType = '';
const children = () =>
@@ -170,8 +177,52 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
followFrame = requestAnimationFrame(follow);
}
+ // Every child carries the same translate, so a held row's span is its
+ // layout's.
+ function span(): number {
+ const items = children();
+ if (items.length === 0) {
+ return 0;
+ }
+ let start = Infinity;
+ let end = -Infinity;
+ for (const child of items) {
+ const rect = child.getBoundingClientRect();
+ start = Math.min(start, rect.left);
+ end = Math.max(end, rect.right);
+ }
+ return (end - start) / rowScale(element, element.getBoundingClientRect());
+ }
+
+ // A resize while the row is held moves its travel with the row's width and
+ // the children's span. A frame of the hold reads the result, not the row.
+ function remeasure(): void {
+ if (!isMoving) {
+ return;
+ }
+ const nextSpan = span();
+ const nextWidth = element.clientWidth;
+ const native = nativePosition();
+ // WebKit truncates a fractional scroll offset, so the travel stays a whole
+ // number of pixels, as the scroll width is. It rounds once, from the
+ // takeover, so a resize over many frames adds up no rounding.
+ heldTravel = Math.max(
+ 0,
+ Math.round(
+ takeoverTravel + (nextSpan - heldSpan) - (nextWidth - heldWidth),
+ ),
+ );
+ // A shorter travel clamps the row's own scroll offset. The children take
+ // up the clamp, so the row still shows where the pager holds it.
+ if (native !== heldOffset) {
+ const at = position();
+ heldOffset = native;
+ place(at);
+ }
+ }
+
// A held row's translate widens its overflow, so its travel is the one it
- // was taken over with.
+ // was taken over with, moved by any resize since.
function travel(): number {
return isMoving
? heldTravel
@@ -209,8 +260,13 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
const rowTravel = Math.max(0, element.scrollWidth - element.clientWidth);
const rowSign = isRtl() ? -1 : 1;
const items = children();
+ const rowSpan = span();
+ const rowWidth = element.clientWidth;
heldOffset = offset;
heldTravel = rowTravel;
+ takeoverTravel = rowTravel;
+ heldSpan = rowSpan;
+ heldWidth = rowWidth;
heldSign = rowSign;
lead = items[0] ?? null;
isMoving = true;
@@ -307,6 +363,7 @@ function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
},
position,
travel,
+ remeasure,
stops,
viewWidth,
place,
@@ -337,7 +394,6 @@ 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;
- // 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();
@@ -366,6 +422,8 @@ function attachPaging(
// the pointer kinds.
panOptions: {allowedPointerTypes: ['touch', 'pen']},
measurePages: () => {
+ // A resize while the row is held moves its travel first.
+ track.remeasure();
const stops = measured?.stops ?? track.stops();
return (options.pages ?? 'view') === 'item'
? stops
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 97cc2947fe..f8a8f8457b 100644
--- a/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts
+++ b/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts
@@ -192,6 +192,215 @@ for (const mode of ['paging', 'item'] as const) {
).toBeLessThan(1);
});
+ // Three per view, the drag goes past half a page, so the lift moves on.
+ for (const [story, px, dragPx] of [
+ ['snap-paging-partial-last-page', 1, 60],
+ ['snap-paging-three-up', 100, 90],
+ ] as const) {
+ test(`a ${px} px resize while a finger holds the row at its end: the lift rests where the row ends (${story})`, async ({
+ page,
+ }) => {
+ const {scroller} = await open(page, story, mode);
+ for (let i = 0; i < 7; i++) {
+ await swipe(page, scroller, {px: 80, ms: 80});
+ await settled(scroller);
+ }
+ // The row narrows under the finger, at its third move.
+ await scroller.evaluate((el, by) => {
+ let moves = 0;
+ el.addEventListener(
+ 'touchmove',
+ () => {
+ moves += 1;
+ if (moves === 3) {
+ el.style.width = `${el.clientWidth - by}px`;
+ }
+ },
+ {passive: true},
+ );
+ }, px);
+ const box = await scroller.boundingBox();
+ if (box == null) {
+ throw new Error('no scroller');
+ }
+ const from = {x: box.x + box.width / 2, y: box.y + box.height / 2};
+ const driver = await touchDriver(page);
+ await driver.play(
+ drag(
+ from,
+ {x: from.x - dragPx, y: from.y},
+ {durationMs: 200, restMs: 120},
+ ),
+ );
+ await settled(scroller);
+ expect(await offset(scroller)).toBeCloseTo(await travel(scroller), 0);
+ // The last item's end meets the row's end, with no pixel cut off.
+ expect(
+ await scroller.evaluate(el => {
+ const last = el.lastElementChild as HTMLElement;
+ return (
+ el.getBoundingClientRect().right -
+ last.getBoundingClientRect().right
+ );
+ }),
+ ).toBeGreaterThan(-0.5);
+ });
+ }
+
+ test('a row narrowed 1 px a frame under a held finger, its items a share of its width: the lift rests where the row ends', async ({
+ page,
+ }) => {
+ const {scroller} = await open(page, 'snap-paging-three-up', mode);
+ // Items 40 % of the row wide: each pixel the row narrows takes 2.6 px
+ // off its travel.
+ await scroller.evaluate(el => {
+ for (const child of Array.from(el.children)) {
+ (child as HTMLElement).style.width = '40%';
+ }
+ });
+ for (let i = 0; i < 12; i++) {
+ if (
+ Math.abs((await offset(scroller)) - (await travel(scroller))) < 0.5
+ ) {
+ break;
+ }
+ await swipe(page, scroller, {px: 80, ms: 80});
+ await settled(scroller);
+ }
+ expect(await offset(scroller)).toBeCloseTo(await travel(scroller), 0);
+ // From the drag's first move, the row narrows 1 px a frame for 20
+ // frames. The page records how far the last item ends inside the row
+ // on each frame of the hold.
+ await scroller.evaluate(el => {
+ const last = el.lastElementChild as HTMLElement;
+ const record = window as unknown as {heldGaps: number[]};
+ record.heldGaps = [];
+ const isHeld = () =>
+ Array.from(el.children).some(
+ child => (child as HTMLElement).style.translate !== '',
+ );
+ const sample = () => {
+ if (isHeld()) {
+ record.heldGaps.push(
+ el.getBoundingClientRect().right -
+ last.getBoundingClientRect().right,
+ );
+ }
+ requestAnimationFrame(sample);
+ };
+ requestAnimationFrame(sample);
+ let frames = 0;
+ const narrow = () => {
+ el.style.width = `${el.clientWidth - 1}px`;
+ frames += 1;
+ if (frames < 20) {
+ requestAnimationFrame(narrow);
+ }
+ };
+ el.addEventListener('touchmove', () => requestAnimationFrame(narrow), {
+ once: true,
+ passive: true,
+ });
+ });
+ const box = await scroller.boundingBox();
+ if (box == null) {
+ throw new Error('no scroller');
+ }
+ const from = {x: box.x + box.width / 2, y: box.y + box.height / 2};
+ const driver = await touchDriver(page);
+ await driver.play(
+ drag(from, {x: from.x - 90, y: from.y}, {durationMs: 500, restMs: 150}),
+ );
+ await settled(scroller);
+ const heldGaps = await page.evaluate(
+ () => (window as unknown as {heldGaps: number[]}).heldGaps,
+ );
+ expect(heldGaps.at(-1)).toBeGreaterThan(-0.5);
+ expect(await offset(scroller)).toBeCloseTo(await travel(scroller), 0);
+ expect(
+ await scroller.evaluate(el => {
+ const last = el.lastElementChild as HTMLElement;
+ return (
+ el.getBoundingClientRect().right -
+ last.getBoundingClientRect().right
+ );
+ }),
+ ).toBeGreaterThan(-0.5);
+ });
+
+ test('a 100 px widening while a finger holds the row at its end: the settle ends where the row ends, with no jump at the hand-back', async ({
+ page,
+ }) => {
+ const {scroller} = await open(page, 'snap-paging-three-up', mode);
+ for (let i = 0; i < 7; i++) {
+ await swipe(page, scroller, {px: 80, ms: 80});
+ await settled(scroller);
+ }
+ // The frame widens under the finger, at its third move, so the row's
+ // travel drops below its scroll offset. The page records how far the
+ // last item ends inside the row on each frame of the hold.
+ await scroller.evaluate(el => {
+ const frame = el.closest('[role="region"]')?.parentElement;
+ if (frame == null) {
+ throw new Error('no frame');
+ }
+ const last = el.lastElementChild as HTMLElement;
+ const record = window as unknown as {heldGaps: number[]};
+ record.heldGaps = [];
+ const isHeld = () =>
+ Array.from(el.children).some(
+ child => (child as HTMLElement).style.translate !== '',
+ );
+ const sample = () => {
+ if (isHeld()) {
+ record.heldGaps.push(
+ el.getBoundingClientRect().right -
+ last.getBoundingClientRect().right,
+ );
+ }
+ requestAnimationFrame(sample);
+ };
+ requestAnimationFrame(sample);
+ let moves = 0;
+ el.addEventListener(
+ 'touchmove',
+ () => {
+ moves += 1;
+ if (moves === 3) {
+ frame.style.width = `${frame.clientWidth + 100}px`;
+ }
+ },
+ {passive: true},
+ );
+ });
+ const box = await scroller.boundingBox();
+ if (box == null) {
+ throw new Error('no scroller');
+ }
+ const from = {x: box.x + box.width / 2, y: box.y + box.height / 2};
+ const driver = await touchDriver(page);
+ await driver.play(
+ drag(from, {x: from.x - 90, y: from.y}, {durationMs: 200, restMs: 120}),
+ );
+ await settled(scroller);
+ // The last frame of the hold shows the row at its end, as the hand-back
+ // leaves it.
+ const heldGaps = await page.evaluate(
+ () => (window as unknown as {heldGaps: number[]}).heldGaps,
+ );
+ expect(heldGaps.at(-1)).toBeGreaterThan(-0.5);
+ expect(await offset(scroller)).toBeCloseTo(await travel(scroller), 0);
+ expect(
+ await scroller.evaluate(el => {
+ const last = el.lastElementChild as HTMLElement;
+ return (
+ el.getBoundingClientRect().right -
+ last.getBoundingClientRect().right
+ );
+ }),
+ ).toBeGreaterThan(-0.5);
+ });
+
test('right-to-left: a flick toward the inline end moves forward, mirrored', async ({
page,
}) => {
@@ -301,7 +510,7 @@ for (const pointer of ['coarse', 'fine'] as const) {
});
}
-test('the scroll offset holds through a swipe, so the edge fades and buttons stay put, and the settle hands it on', async ({
+test('the scroll offset holds through a swipe, and the settle hands it on', async ({
page,
}) => {
const {scroller} = await open(page, 'snap-paging-three-up', 'paging');
diff --git a/packages/core/src/SnapPaging/snapPagingValue.ts b/packages/core/src/SnapPaging/snapPagingValue.ts
index 3f4e7d0d11..1e83df83c7 100644
--- a/packages/core/src/SnapPaging/snapPagingValue.ts
+++ b/packages/core/src/SnapPaging/snapPagingValue.ts
@@ -132,6 +132,16 @@ export function nearestStop(stops: ReadonlyArray<number>, at: number): number {
);
}
+/**
+ * The scale a scaled ancestor gives the row's rects: the rect's width over the
+ * row's layout width. Scroll offsets do not have it.
+ */
+export function rowScale(element: HTMLElement, box: DOMRect): number {
+ return element.offsetWidth > 0 && box.width > 0
+ ? box.width / element.offsetWidth
+ : 1;
+}
+
/**
* 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
@@ -144,11 +154,7 @@ export function snapStops(
): number[] {
const rtl = isRtlElement(element);
const box = element.getBoundingClientRect();
- // A scaled ancestor scales the rects, not the scroll offsets.
- const scale =
- element.offsetWidth > 0 && box.width > 0
- ? box.width / element.offsetWidth
- : 1;
+ const scale = rowScale(element, box);
const border = rtl
? element.offsetWidth - element.clientWidth - element.clientLeft
: element.clientLeft;
diff --git a/packages/core/src/hooks/usePager.test.ts b/packages/core/src/hooks/usePager.test.ts
index e50f0f4210..8aaa381500 100644
--- a/packages/core/src/hooks/usePager.test.ts
+++ b/packages/core/src/hooks/usePager.test.ts
@@ -1187,6 +1187,81 @@ describe('createPager', () => {
}
});
+ // The shared resize observer is one per module. So this case loads a fresh
+ // pager module after it installs its ResizeObserver.
+ it('a resize during a drag renumbers the pages, and the release still moves one page from where the drag began', async () => {
+ let onResize: ResizeObserverCallback | null = null;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ onResize = callback;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ vi.resetModules();
+ const fresh = await import('./usePager');
+ const f = setup({defaultIndex: 0});
+ f.pager.dispose();
+ // Three views of a nine-item row. A narrower view gives five.
+ let pages = [0, 308, 616];
+ const calls: string[] = [];
+ const pager = fresh.createPager(
+ {
+ count: 3,
+ pages: 'children',
+ measurePages: () => pages,
+ defaultIndex: 2,
+ onSettle: (i, previous) => calls.push(`settle:${i}:${previous}`),
+ },
+ {
+ host: f.host,
+ animator: f.animator,
+ requestFrame: callback => {
+ frameQueue.push(callback);
+ },
+ },
+ );
+ pager.attach(f.viewport, f.track);
+ try {
+ expect(f.x()).toBe(-616);
+ touch('touchstart', f.page, 300, 100, now);
+ // An 88 px drag toward the end, well past half the next page.
+ for (let i = 1; i <= 22; i++) {
+ await advance(8, f.clock);
+ touch('touchmove', f.page, 300 - 4 * i, 100, now);
+ if (i === 6) {
+ pages = [0, 205.3, 410.7, 616, 716];
+ Object.defineProperty(f.viewport, 'clientWidth', {
+ value: 200,
+ configurable: true,
+ });
+ expect(onResize).not.toBeNull();
+ onResize!(
+ [{target: f.viewport} as unknown as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ }
+ }
+ // A still finger before the lift: the release has no speed.
+ await advance(120, f.clock);
+ touch('touchend', f.page, 212, 100, now);
+ for (let i = 0; i < 80 && pager.isSettling; i++) {
+ await advance(16, f.clock);
+ }
+ await advance(16, f.clock);
+ // The drag began on the page at 616, and the page at 716 is the next one.
+ expect(f.x()).toBe(-716);
+ expect(calls).toEqual(['settle:4:2']);
+ } finally {
+ pager.dispose();
+ vi.unstubAllGlobals();
+ }
+ });
+
// The shared resize observer is one per module. So this case loads a fresh
// pager module after it installs its ResizeObserver.
it('a resize after a forward wrap keeps the wrapped page: no jump and no callback', async () => {
diff --git a/packages/core/src/hooks/usePager.ts b/packages/core/src/hooks/usePager.ts
index ebf0dd9d5c..8168b05c0a 100644
--- a/packages/core/src/hooks/usePager.ts
+++ b/packages/core/src/hooks/usePager.ts
@@ -958,7 +958,13 @@ export function createPager(
if (isChildPages()) {
const offsets = measureChildOffsets();
if (!sameOffsets(offsets, childOffsets)) {
+ // A drag's release moves at most one page from where the drag began.
+ // New pages renumber, so the drag keeps the page nearest that offset.
+ const dragFrom = isDragging ? offsetOf(dragStartIndex) : null;
childOffsets = offsets;
+ if (dragFrom != null) {
+ dragStartIndex = nearestPage(dragFrom);
+ }
changed = true;
const pageCount = offsets.length;
deliver(() => options.onPagesChange?.(pageCount));