Skip to content

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

TypeScript

fix(Carousel): under snap paging, the edge buttons follow the held row (#10359)

Christopher Chedeau72a35585112e
diff --git a/.changeset/carousel-snap-edges-follow.md b/.changeset/carousel-snap-edges-follow.md
new file mode 100644
index 0000000000..5c6a25b74d
--- /dev/null
+++ b/.changeset/carousel-snap-edges-follow.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Under snap paging (`hasSnap={useSnapPaging()}`), Carousel's edge scroll buttons and edge fades follow the row as it moves. A flick used to leave them as they were until the settle ended and the row went back to native scrolling, so the start button came back about half a second after the row had visibly left the start.
+
+@vjeux
diff --git a/packages/core/src/Carousel/Carousel.tsx b/packages/core/src/Carousel/Carousel.tsx
index 2f281eb6b6..311509f31c 100644
--- a/packages/core/src/Carousel/Carousel.tsx
+++ b/packages/core/src/Carousel/Carousel.tsx
@@ -53,7 +53,7 @@ import {Button} from '../Button';
import {Icon} from '../Icon';
import {useLayer} from '../Layer';
import {useAttachment} from '../hooks/useAttachment';
-import {useScrollOverflow} from '../hooks/useScrollOverflow';
+import {useShownScrollOverflow} from '../hooks/useScrollOverflow';
import {isRtlElement} from '../hooks/isRtlElement';
import type {BaseProps} from '../BaseProps';
import {mergeProps, rtlStyles} from '../utils';
@@ -408,8 +408,8 @@ export function Carousel({
// transition it is allowed to act on.
const focusedNavRef = useRef<'start' | 'end' | null>(null);
const prevCanScrollRef = useRef<{start: boolean; end: boolean} | null>(null);
- const {scrollRef, overflowStart, overflowEnd, hasOverflow} =
- useScrollOverflow();
+ const {scrollRef, followShown, overflowStart, overflowEnd, hasOverflow} =
+ useShownScrollOverflow();
// Children.toArray drops null/undefined/boolean children and assigns
// stable keys, so slide numbering ("Slide N of M") matches what actually
@@ -447,12 +447,13 @@ export function Carousel({
setAttachedPaging(snapPaging);
}
// Attaches snap paging to the scroll area, and follows a replaced one.
+ // While the paging holds the row, the edges follow the row as shown.
useAttachment(
scrollElRef,
scroller =>
attachedPaging == null
? () => {}
- : attachSnapPaging(attachedPaging, scroller),
+ : attachSnapPaging(attachedPaging, scroller, followShown),
attachedPaging,
);
// React's wheel listener is passive, so it can't stop the browser's own
diff --git a/packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.ts b/packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.ts
new file mode 100644
index 0000000000..f0bbef032b
--- /dev/null
+++ b/packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.ts
@@ -0,0 +1,178 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @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
+ * @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.
+ * @position Interaction proofs for Carousel's edge buttons under snap paging,
+ * run in Chromium and WebKit
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ drag,
+ openStory,
+ touchDriver,
+ withStorybook,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+interface Sample {
+ readonly shown: number;
+ readonly travel: number;
+ readonly startDisabled: boolean;
+ readonly endDisabled: boolean;
+ readonly held: boolean;
+}
+
+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 start = page.getByRole('button', {
+ name: 'Scroll left',
+ includeHidden: true,
+ });
+ const end = page.getByRole('button', {
+ name: 'Scroll right',
+ includeHidden: true,
+ });
+ await expect(scroller).toBeVisible();
+ return {scroller, start, end};
+}
+
+// Samples on every frame. It records where the row is shown (its scroll
+// offset less the lead item's translate). It also records whether each edge
+// button is disabled and whether the paging holds the row.
+async function startSampling(
+ scroller: Locator,
+ start: Locator,
+ end: Locator,
+): Promise<void> {
+ const startHandle = await start.elementHandle();
+ const endHandle = await end.elementHandle();
+ await scroller.evaluate(
+ (row, [startButton, endButton]) => {
+ const samples: Sample[] = [];
+ (window as unknown as {__edgeSamples: Sample[]}).__edgeSamples = samples;
+ const translateX = (el: Element) =>
+ Number.parseFloat(getComputedStyle(el).translate.split(' ')[0]) || 0;
+ const tick = () => {
+ const lead = row.children[0];
+ const held = Array.from(row.children).some(
+ child => (child as HTMLElement).style.translate !== '',
+ );
+ samples.push({
+ shown:
+ Math.abs(row.scrollLeft) - (lead == null ? 0 : translateX(lead)),
+ travel: row.scrollWidth - row.clientWidth,
+ startDisabled: (startButton as HTMLButtonElement).disabled,
+ endDisabled: (endButton as HTMLButtonElement).disabled,
+ held,
+ });
+ if (samples.length < 600) {
+ requestAnimationFrame(tick);
+ }
+ };
+ requestAnimationFrame(tick);
+ },
+ [startHandle, endHandle] as const,
+ );
+}
+
+async function samplesOf(page: Page): Promise<Sample[]> {
+ return page.evaluate(
+ () => (window as unknown as {__edgeSamples: Sample[]}).__edgeSamples,
+ );
+}
+
+// A flick of 80 px in 80 ms, toward the end of the row or back.
+async function flick(
+ page: Page,
+ scroller: Locator,
+ {back = false}: {back?: boolean} = {},
+): Promise<void> {
+ 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 + (back ? -40 : 40), y};
+ const to = {x: from.x + (back ? 80 : -80), y};
+ const driver = await touchDriver(page);
+ await driver.play(drag(from, to, {durationMs: 80}));
+}
+
+async function settled(scroller: Locator): Promise<void> {
+ await expect
+ .poll(async () =>
+ scroller.evaluate(row =>
+ Array.from(row.children).some(
+ child => (child as HTMLElement).style.translate !== '',
+ ),
+ ),
+ )
+ .toBe(false);
+}
+
+test('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 flick(page, scroller);
+ await settled(scroller);
+ await expect(start).toBeEnabled();
+ 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',
+ description: String(back - left),
+ });
+ expect(left, detail).toBeGreaterThanOrEqual(0);
+ expect(back - left, detail).toBeLessThanOrEqual(2);
+ // While the paging still holds the row: before the settle hands it back.
+ expect(samples[back]?.held, detail).toBe(true);
+});
+
+test('the end button comes back within two frames of the held row leaving the end', async ({
+ page,
+}) => {
+ const {scroller, start, end} = await open(page);
+ // Two views on: the end of the row.
+ await flick(page, scroller);
+ await settled(scroller);
+ await flick(page, scroller);
+ await settled(scroller);
+ await expect(end).toBeDisabled();
+ await startSampling(scroller, start, end);
+ await flick(page, scroller, {back: true});
+ await settled(scroller);
+ await expect(end).toBeEnabled();
+ const samples = await samplesOf(page);
+ const detail = JSON.stringify(samples.slice(0, 40));
+ // The travel at rest: a held row's translate can widen its overflow.
+ const {travel} = samples[0];
+ const left = samples.findIndex(sample => sample.shown < travel - 1);
+ const back = samples.findIndex(sample => !sample.endDisabled);
+ test.info().annotations.push({
+ type: 'frames from leaving the end to the end button',
+ description: String(back - left),
+ });
+ expect(left, detail).toBeGreaterThanOrEqual(0);
+ expect(back - left, detail).toBeLessThanOrEqual(2);
+ 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 2f487f8abb..07bb615470 100644
--- a/packages/core/src/SnapPaging/SnapPaging.test.tsx
+++ b/packages/core/src/SnapPaging/SnapPaging.test.tsx
@@ -15,6 +15,8 @@ import {act, render, renderHook, screen} from '@testing-library/react';
import {Carousel} from '../Carousel/Carousel';
import {useSnapPaging} from './SnapPaging';
import {
+ type HeldRow,
+ type HeldRowListener,
isSnapPaging,
makeSnapPaging,
nearestStop,
@@ -241,4 +243,69 @@ describe('Carousel with hasSnap', () => {
act(() => unmount());
expect(attached).toEqual(['first', 'first detached']);
});
+
+ 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.
+ function renderHeld() {
+ let listener: HeldRowListener | undefined;
+ const value = makeSnapPaging((_element, onHeld) => {
+ listener = onHeld;
+ return attachment();
+ });
+ render(
+ <Carousel aria-label="Items" hasSnap={value}>
+ <div>One</div>
+ <div>Two</div>
+ <div>Three</div>
+ </Carousel>,
+ );
+ const button = (name: string) =>
+ screen.getByRole<HTMLButtonElement>('button', {name, hidden: true});
+ return {
+ report: (held: HeldRow | null) => act(() => listener?.(held)),
+ start: button('Scroll left'),
+ end: button('Scroll right'),
+ };
+ }
+
+ it('enables and disables each button as the held row leaves or reaches its edge, before the hand-back', () => {
+ const {report, start, end} = renderHeld();
+ // jsdom lays nothing out, so at rest the scroll offset gives no room.
+ expect([start.disabled, end.disabled]).toEqual([true, true]);
+ report({offset: 0, travel: 600});
+ expect([start.disabled, end.disabled]).toEqual([true, false]);
+ report({offset: 300, travel: 600});
+ expect([start.disabled, end.disabled]).toEqual([false, false]);
+ report({offset: 599.5, travel: 600});
+ expect([start.disabled, end.disabled]).toEqual([false, true]);
+ });
+
+ it('keeps the held edges for one frame after the hand-back, then reads the scroll offset again', async () => {
+ const {report, start} = renderHeld();
+ report({offset: 300, travel: 600});
+ report({offset: 300, travel: 600});
+ report(null);
+ expect(start.disabled).toBe(false);
+ await act(
+ async () =>
+ new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve());
+ }),
+ );
+ expect(start.disabled).toBe(true);
+ });
+
+ it('hands focus to the scroll area once, when the held row reaches the edge of the focused button', () => {
+ const {report, end} = renderHeld();
+ report({offset: 300, travel: 600});
+ act(() => end.focus());
+ const focus = vi.spyOn(scroller(), 'focus');
+ report({offset: 600, travel: 600});
+ expect(focus).toHaveBeenCalledTimes(1);
+ expect(document.activeElement).toBe(scroller());
+ report({offset: 600, travel: 600});
+ expect(focus).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/packages/core/src/SnapPaging/SnapPaging.ts b/packages/core/src/SnapPaging/SnapPaging.ts
index d9e306083d..5b0c50179f 100644
--- a/packages/core/src/SnapPaging/SnapPaging.ts
+++ b/packages/core/src/SnapPaging/SnapPaging.ts
@@ -18,6 +18,7 @@ import {isRtlElement} from '../hooks/isRtlElement';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {animatorFor, type MotionHandle} from '../motion/animator';
import {
+ type HeldRowListener,
makeSnapPaging,
type SnapPaging,
type SnapPagingAttachment,
@@ -53,7 +54,9 @@ export function useSnapPaging(options: SnapPagingOptions = {}): SnapPaging {
return optionsRef.current.pages;
},
};
- return makeSnapPaging(element => attachPaging(element, live));
+ return makeSnapPaging((element, onHeld) =>
+ attachPaging(element, live, onHeld),
+ );
});
return value;
}
@@ -116,10 +119,15 @@ function combined(handles: ReadonlyArray<MotionHandle>): MotionHandle {
* offset holds, and every child moves by the same translate from there. The
* settle hands the position back to native scrolling.
*/
-function childTrack(element: HTMLElement) {
+function childTrack(element: HTMLElement, onHeld?: HeldRowListener) {
let isMoving = false;
let heldOffset = 0;
let heldTravel = 0;
+ // The direction and the lead child, read at the takeover, so a frame of the
+ // hold reads no style or layout.
+ let heldSign = 1;
+ let lead: HTMLElement | null = null;
+ let followFrame = 0;
// The row's own inline snap type, back at the hand-back.
let ownSnapType = '';
const children = () =>
@@ -147,6 +155,20 @@ function childTrack(element: HTMLElement) {
return -sign() * (animatorFor(first).get('x') - sign() * heldOffset);
}
+ // Reports where the held row is shown, once a frame, from the lead child's
+ // own animator.
+ function follow(): void {
+ if (onHeld == null || !isMoving) {
+ return;
+ }
+ const offset =
+ lead == null
+ ? heldOffset
+ : -heldSign * (animatorFor(lead).get('x') - heldSign * heldOffset);
+ onHeld({offset, travel: heldTravel});
+ followFrame = requestAnimationFrame(follow);
+ }
+
// A held row's translate widens its overflow, so its travel is the one it
// was taken over with.
function travel(): number {
@@ -193,6 +215,9 @@ function childTrack(element: HTMLElement) {
}
}
place(heldOffset);
+ heldSign = sign();
+ lead = children()[0] ?? null;
+ follow();
}
function handBack(): void {
@@ -214,6 +239,11 @@ function childTrack(element: HTMLElement) {
element.style.setProperty('scroll-snap-type', ownSnapType);
}
element.scrollTo({left: isRtl() ? -at : at, behavior: 'instant'});
+ if (onHeld != null) {
+ cancelAnimationFrame(followFrame);
+ onHeld({offset: at, travel: heldTravel});
+ onHeld(null);
+ }
}
const animator: PagerAnimator = {
@@ -291,8 +321,9 @@ function childTrack(element: HTMLElement) {
function attachPaging(
element: HTMLElement,
options: SnapPagingOptions,
+ onHeld?: HeldRowListener,
): SnapPagingAttachment {
- const track = childTrack(element);
+ const track = childTrack(element, onHeld);
// The stop that view pages count from, set when a gesture takes over.
let anchor = 0;
const pager = createPager(
diff --git a/packages/core/src/SnapPaging/snapPagingValue.ts b/packages/core/src/SnapPaging/snapPagingValue.ts
index fc895b1463..eb702deaa0 100644
--- a/packages/core/src/SnapPaging/snapPagingValue.ts
+++ b/packages/core/src/SnapPaging/snapPagingValue.ts
@@ -4,7 +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`), and stops
+ * (`isSnapPaging`, `attachSnapPaging`, `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
*/
@@ -37,8 +38,25 @@ export interface SnapPagingAttachment {
readonly moveHeld: (target: (at: number, end: number) => number) => boolean;
}
+/**
+ * Where a row the paging holds is shown: its offset toward the end, and the
+ * travel it was taken over with.
+ */
+export interface HeldRow {
+ readonly offset: number;
+ readonly travel: number;
+}
+
+/** Hears a held row on each frame of the hold, and null at the hand-back. */
+export type HeldRowListener = (held: HeldRow | null) => void;
+
+type Attach = (
+ element: HTMLElement,
+ onHeld?: HeldRowListener,
+) => SnapPagingAttachment;
+
interface SnapPagingValue {
- readonly attach: (element: HTMLElement) => SnapPagingAttachment;
+ readonly attach: Attach;
}
const values = new WeakSet<object>();
@@ -46,9 +64,7 @@ const values = new WeakSet<object>();
const attachments = new WeakMap<HTMLElement, SnapPagingAttachment>();
/** A `SnapPaging` value that attaches with `attach`. */
-export function makeSnapPaging(
- attach: (element: HTMLElement) => SnapPagingAttachment,
-): SnapPaging {
+export function makeSnapPaging(attach: Attach): SnapPaging {
const value: SnapPagingValue = {attach};
values.add(value);
return value as unknown as SnapPaging;
@@ -59,12 +75,19 @@ export function isSnapPaging(value: unknown): value is SnapPaging {
return typeof value === 'object' && value !== null && values.has(value);
}
-/** Attaches snap paging to `element`; the returned function detaches it. */
+/**
+ * Attaches snap paging to `element`; the returned function detaches it.
+ * `onHeld` hears where the row is shown while the paging holds it.
+ */
export function attachSnapPaging(
value: SnapPaging,
element: HTMLElement,
+ onHeld?: HeldRowListener,
): () => void {
- const attachment = (value as unknown as SnapPagingValue).attach(element);
+ const attachment = (value as unknown as SnapPagingValue).attach(
+ element,
+ onHeld,
+ );
attachments.set(element, attachment);
return () => {
attachments.delete(element);
diff --git a/packages/core/src/hooks/useScrollOverflow.test.tsx b/packages/core/src/hooks/useScrollOverflow.test.tsx
index 8faccc3c70..56155b8187 100644
--- a/packages/core/src/hooks/useScrollOverflow.test.tsx
+++ b/packages/core/src/hooks/useScrollOverflow.test.tsx
@@ -11,7 +11,7 @@
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {act, renderHook} from '@testing-library/react';
-import {useScrollOverflow} from './useScrollOverflow';
+import {useScrollOverflow, useShownScrollOverflow} from './useScrollOverflow';
// jsdom has no ResizeObserver. This one hands the test the shared observer's
// callback so a resize can be delivered on demand; the registration-time
@@ -320,4 +320,86 @@ describe('useScrollOverflow', () => {
expect(result.current.overflowEnd).toBe(false);
unmount();
});
+
+ it('returns the same fields as before, with no way to report a position', () => {
+ const {result, unmount} = renderHook(() => useScrollOverflow());
+ expect(Object.keys(result.current).sort()).toEqual([
+ 'hasOverflow',
+ 'overflowEnd',
+ 'overflowStart',
+ 'scrollRef',
+ ]);
+ unmount();
+ });
+});
+
+describe('useShownScrollOverflow', () => {
+ function attach() {
+ const el = document.createElement('div');
+ fakeScrollBox(el, {scrollWidth: 600, clientWidth: 300});
+ stubRendered(el, true);
+ const hook = renderHook(() => useShownScrollOverflow());
+ act(() => {
+ hook.result.current.scrollRef(el);
+ });
+ return {el, ...hook};
+ }
+
+ const nextFrame = async () =>
+ act(
+ async () =>
+ new Promise<void>(resolve => {
+ requestAnimationFrame(() => resolve());
+ }),
+ );
+
+ it('measures the edges from a reported position while the scroll offset stays put', () => {
+ const {result, unmount} = attach();
+ expect([result.current.overflowStart, result.current.overflowEnd]).toEqual([
+ false,
+ true,
+ ]);
+ act(() => result.current.followShown({offset: 150, travel: 300}));
+ expect([result.current.overflowStart, result.current.overflowEnd]).toEqual([
+ true,
+ true,
+ ]);
+ act(() => result.current.followShown({offset: 299.5, travel: 300}));
+ expect([result.current.overflowStart, result.current.overflowEnd]).toEqual([
+ true,
+ false,
+ ]);
+ unmount();
+ });
+
+ it('keeps the reported edges for one frame after null, then measures the scroll offset', async () => {
+ const {el, result, unmount} = attach();
+ act(() => result.current.followShown({offset: 300, travel: 300}));
+ act(() => result.current.followShown(null));
+ expect(result.current.overflowEnd).toBe(false);
+ // A scroll before that frame still reads the reported position.
+ act(() => {
+ el.dispatchEvent(new Event('scroll'));
+ });
+ expect(result.current.overflowEnd).toBe(false);
+ await nextFrame();
+ expect(result.current.overflowEnd).toBe(true);
+ unmount();
+ });
+
+ it('leaves no frame running when the container detaches or the hook unmounts', () => {
+ const cancel = vi.spyOn(window, 'cancelAnimationFrame');
+ const {result, unmount} = attach();
+ act(() => result.current.followShown({offset: 300, travel: 300}));
+ act(() => result.current.followShown(null));
+ const calls = cancel.mock.calls.length;
+ act(() => result.current.scrollRef(null));
+ expect(cancel.mock.calls.length).toBeGreaterThan(calls);
+ // With no container, null schedules nothing.
+ const request = vi.spyOn(window, 'requestAnimationFrame');
+ act(() => result.current.followShown({offset: 300, travel: 300}));
+ act(() => result.current.followShown(null));
+ expect(request).not.toHaveBeenCalled();
+ unmount();
+ });
});
diff --git a/packages/core/src/hooks/useScrollOverflow.ts b/packages/core/src/hooks/useScrollOverflow.ts
index 4ed2a24d59..44a94ee796 100644
--- a/packages/core/src/hooks/useScrollOverflow.ts
+++ b/packages/core/src/hooks/useScrollOverflow.ts
@@ -5,7 +5,9 @@
/**
* @file useScrollOverflow.ts
* @input React refs, state and effects
- * @output useScrollOverflow, which tracks the overflow at the scroll edges
+ * @output useScrollOverflow, which tracks the overflow at the scroll edges,
+ * and the internal useShownScrollOverflow, which can also measure from a
+ * position its caller reports
* @position Core hook; used by Carousel and TabList for fade-edge and button
* state
*
@@ -16,6 +18,15 @@
import {useState, useCallback, useEffect, useRef} from 'react';
import {observeResize} from '../utils/sharedResizeObserver';
+/**
+ * Where the content is shown while something other than scrolling moves it:
+ * its offset toward the end, and how far it travels.
+ */
+export interface ShownPosition {
+ readonly offset: number;
+ readonly travel: number;
+}
+
export interface ScrollOverflowState {
/** Content overflows the start (left in LTR, right in RTL) */
overflowStart: boolean;
@@ -97,8 +108,23 @@ function observeContent(el: HTMLElement, measure: () => void): () => void {
* ```
*/
export function useScrollOverflow() {
+ const {scrollRef, overflowStart, overflowEnd, hasOverflow} =
+ useShownScrollOverflow();
+ return {scrollRef, overflowStart, overflowEnd, hasOverflow};
+}
+
+/**
+ * `useScrollOverflow`, plus `followShown`: while snap paging holds a row, its
+ * scroll offset stays where the hold began and its items move. The caller
+ * reports where the row is shown, and the edges follow it. Null measures the
+ * scroll offset again from the next frame, when the handed-back offset is
+ * current. Internal: not exported from the hooks entry.
+ */
+export function useShownScrollOverflow() {
const elRef = useRef<HTMLElement | null>(null);
const unobserveRef = useRef<(() => void) | null>(null);
+ const shownRef = useRef<ShownPosition | null>(null);
+ const releaseFrameRef = useRef(0);
const [state, setState] = useState<ScrollOverflowState>({
overflowStart: false,
@@ -108,12 +134,13 @@ export function useScrollOverflow() {
const measureNow = useCallback((el: HTMLElement) => {
const tolerance = 1;
- const {scrollLeft, scrollWidth, clientWidth} = el;
- const maxScroll = scrollWidth - clientWidth;
+ const shown = shownRef.current;
+ const offset = shown?.offset ?? Math.abs(el.scrollLeft);
+ const maxScroll = shown?.travel ?? el.scrollWidth - el.clientWidth;
- const overflowStart = Math.abs(scrollLeft) > tolerance;
- const overflowEnd = Math.abs(scrollLeft) < maxScroll - tolerance;
- const hasOverflow = scrollWidth > clientWidth + tolerance;
+ const overflowStart = offset > tolerance;
+ const overflowEnd = offset < maxScroll - tolerance;
+ const hasOverflow = maxScroll > tolerance;
setState(prev => {
if (
@@ -148,12 +175,38 @@ export function useScrollOverflow() {
}
}, [measureNow]);
+ const followShown = useCallback(
+ (shown: ShownPosition | null) => {
+ cancelAnimationFrame(releaseFrameRef.current);
+ const el = elRef.current;
+ if (shown != null) {
+ shownRef.current = shown;
+ if (el) {
+ measureNow(el);
+ }
+ return;
+ }
+ if (shownRef.current == null || el == null) {
+ shownRef.current = null;
+ return;
+ }
+ // The reported edges stand until then, so no edge flickers.
+ releaseFrameRef.current = requestAnimationFrame(() => {
+ shownRef.current = null;
+ measure();
+ });
+ },
+ [measure, measureNow],
+ );
+
const scrollRef = useCallback(
(el: HTMLElement | null) => {
if (elRef.current) {
unobserveRef.current?.();
unobserveRef.current = null;
elRef.current.removeEventListener('scroll', measureOnScroll);
+ cancelAnimationFrame(releaseFrameRef.current);
+ shownRef.current = null;
}
elRef.current = el;
@@ -168,6 +221,7 @@ export function useScrollOverflow() {
useEffect(() => {
return () => {
+ cancelAnimationFrame(releaseFrameRef.current);
if (elRef.current) {
unobserveRef.current?.();
unobserveRef.current = null;
@@ -178,6 +232,7 @@ export function useScrollOverflow() {
return {
scrollRef,
+ followShown,
...state,
};
}