An open source design system that's fully customizable and agent ready
TypeScript
fix(Carousel): an edge button changes in the frame the held row leaves (#10523)
Christopher Chedeau209e067656de
diff --git a/.changeset/carousel-snap-edges-follow.md b/.changeset/carousel-snap-edges-follow.mdindex 5c6a25b74d..9c20438d72 100644--- a/.changeset/carousel-snap-edges-follow.md+++ b/.changeset/carousel-snap-edges-follow.md@@ -2,6 +2,6 @@'@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.+[fix] Under snap paging (`hasSnap={useSnapPaging()}`), Carousel's edge scroll buttons and edge fades follow the row as it moves. They change in the frame where it leaves an edge. 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.@vjeuxdiff --git a/packages/core/src/Carousel/Carousel.test.tsx b/packages/core/src/Carousel/Carousel.test.tsxindex 651581c8e2..e5f895596e 100644--- a/packages/core/src/Carousel/Carousel.test.tsx+++ b/packages/core/src/Carousel/Carousel.test.tsx@@ -1,10 +1,14 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, it, expect, vi} from 'vitest';-import {createRef} from 'react';+import {createRef, useEffect, useRef} from 'react';import {act, render, screen, fireEvent} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {Carousel, type CarouselHandle} from './Carousel';+import {+ makeSnapPaging,+ type HeldRowListener,+} from '../SnapPaging/snapPagingValue';// Mock ResizeObserver (not available in jsdom)class MockResizeObserver {@@ -252,6 +256,75 @@ describe('Carousel', () => {expect(screen.getByLabelText('Scroll right')).toBeInTheDocument();});+ it('unmounts while the paging holds the row, with no flushSync in the commit', () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ let report: HeldRowListener | undefined;+ // A stand-in paging: it reports a held row, and hands the row back as it+ // detaches, as the pager does.+ const paging = makeSnapPaging((_element, onHeld) => {+ report = onHeld;+ return {+ detach: () => {+ onHeld?.({offset: 0, travel: 400});+ onHeld?.(null);+ },+ move: () => {},+ moveHeld: () => false,+ };+ });+ const view = render(+ <Carousel aria-label="Held" hasSnap={paging}>+ <div>Item 1</div>+ <div>Item 2</div>+ </Carousel>,+ );+ act(() => report?.({offset: 150, travel: 400}));+ expect(screen.getByLabelText('Scroll left')).not.toHaveAttribute(+ 'aria-disabled',+ 'true',+ );+ // The detach runs in an effect cleanup, inside React's commit.+ view.unmount();+ expect(error).not.toHaveBeenCalled();+ error.mockRestore();+ });++ it('scrolls from an Effect after a slide is added, with no flushSync in the commit', () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ // A stand-in paging: a move takes the row over and reports it at once,+ // as the pager does.+ const paging = makeSnapPaging((_element, onHeld) => ({+ detach: () => {},+ move: () => {+ onHeld?.({offset: 150, travel: 400});+ },+ moveHeld: () => false,+ }));+ function Grows({count}: {count: number}) {+ const ref = useRef<CarouselHandle>(null);+ useEffect(() => {+ if (count > 2) {+ ref.current?.scrollNext();+ }+ }, [count]);+ return (+ <Carousel handleRef={ref} aria-label="Grows" hasSnap={paging}>+ {Array.from({length: count}, (_, i) => (+ <div key={i}>Item {i + 1}</div>+ ))}+ </Carousel>+ );+ }+ const view = render(<Grows count={2} />);+ view.rerender(<Grows count={3} />);+ expect(screen.getByLabelText('Scroll left')).not.toHaveAttribute(+ 'aria-disabled',+ 'true',+ );+ expect(error).not.toHaveBeenCalled();+ error.mockRestore();+ });+it('disables edge scroll buttons instead of removing them from the tab order', () => {// In jsdom there is no measurable overflow, so both edges are at rest and// the scroll buttons are in their hidden/inert state. They must staydiff --git a/packages/core/src/Carousel/Carousel.tsx b/packages/core/src/Carousel/Carousel.tsxindex 51f7730641..e48145dec5 100644--- a/packages/core/src/Carousel/Carousel.tsx+++ b/packages/core/src/Carousel/Carousel.tsx@@ -328,6 +328,20 @@ const paddingStyles = stylex.create({},});+/**+ * Runs one of Carousel's own calls into the paging: a scroll call or the+ * detach. Such a call can run inside React's commit, so a report it raises+ * takes React's scheduling.+ */+function ownCall<T>(depth: {current: number}, run: () => T): T {+ depth.current += 1;+ try {+ return run();+ } finally {+ depth.current -= 1;+ }+}+/*** Where an edge press under snap paging goes from offset `at`: about one view* on, to the nearest stop and at least one stop on. With `wraps`, a press past@@ -402,6 +416,7 @@ export function Carousel({const t = useComponentTranslator();const ariaLabel = ariaLabelFromProps ?? t('@astryx.carousel.label');const scrollElRef = useRef<HTMLElement | null>(null);+ const runningOwnCallsRef = useRef(0);const startButtonRef = useRef<HTMLButtonElement>(null);const endButtonRef = useRef<HTMLButtonElement>(null);// Which nav button last held focus, and what the overflow state was on the@@ -451,10 +466,15 @@ export function Carousel({// While the paging holds the row, the edges follow the row as shown.useAttachment(scrollElRef,- scroller =>- attachedPaging == null- ? () => {}- : attachSnapPaging(attachedPaging, scroller, followShown),+ scroller => {+ if (attachedPaging == null) {+ return () => {};+ }+ const detach = attachSnapPaging(attachedPaging, scroller, held =>+ followShown(held, runningOwnCallsRef.current === 0),+ );+ return () => ownCall(runningOwnCallsRef, detach);+ },attachedPaging,);// React's wheel listener is passive, so it can't stop the browser's own@@ -511,8 +531,10 @@ export function Carousel({// 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 (- moveSnapPaging(el, (at, end) =>- pagingStep(el, at, end, direction, hasLoop && hasOverflow),+ ownCall(runningOwnCallsRef, () =>+ moveSnapPaging(el, (at, end) =>+ pagingStep(el, at, end, direction, hasLoop && hasOverflow),+ ),)) {return;@@ -595,10 +617,12 @@ export function Carousel({// 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 (- moveSnapPaging(el, (at, end) =>- nearestStop(- snapStops(el, at, end),- at + (isRtlElement(el) ? -delta : delta),+ ownCall(runningOwnCallsRef, () =>+ moveSnapPaging(el, (at, end) =>+ nearestStop(+ snapStops(el, at, end),+ at + (isRtlElement(el) ? -delta : delta),+ ),),)) {diff --git a/packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.ts b/packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.tsindex 3ddaebb154..6d33a89cf0 100644--- a/packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.ts+++ b/packages/core/src/Carousel/__tests__/CarouselSnapPagingEdges.interaction.browser.spec.ts@@ -2,12 +2,12 @@/*** @file CarouselSnapPagingEdges.interaction.browser.spec.ts- * @input The Core/Carousel three-up snap paging story in paging mode, real- * touch flicks and a press from the interaction harness, and a per-frame- * page sampler+ * @input Carousel's three-up snap paging story in paging mode, harness touch+ * flicks and a press, a per-frame sampler and a record of each button+ * change* @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. After a press on+ * leaving its edge, no later than the settle's hand-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@@ -36,6 +36,17 @@ interface Sample {readonly held: boolean;}+/**+ * An edge button's change, whether the paging held the row then, and the+ * observer batch it came in: one batch per task.+ */+interface Flip {+ readonly button: 'start' | 'end';+ readonly disabled: boolean;+ readonly held: boolean;+ readonly batch: number;+}+async function open(page: Page) {await openStory(page, storybook(), 'core-carousel--snap-paging-three-up', {mode: 'paging',@@ -55,7 +66,10 @@ async function open(page: Page) {// 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.+// button is disabled and whether the paging holds the row. A frame's sample+// can come before that frame's change to a button. So each change is also+// recorded as it happens, with whether the paging holds the row then. The+// task in which the paging hands the row back is recorded too.async function startSampling(scroller: Locator,start: Locator,@@ -67,13 +81,45 @@ async function startSampling((row, [startButton, endButton]) => {const samples: Sample[] = [];(window as unknown as {__edgeSamples: Sample[]}).__edgeSamples = samples;+ const flips: Flip[] = [];+ const log = {flips, handBack: -1};+ (window as unknown as {__edgeLog: typeof log}).__edgeLog = log;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(+ const isHeld = () =>+ Array.from(row.children).some(child => (child as HTMLElement).style.translate !== '',);+ let batch = 0;+ let wasHeld = isHeld();+ const observer = new MutationObserver(records => {+ batch += 1;+ const held = isHeld();+ for (const record of records) {+ const target = record.target as Element;+ if (target === startButton || target === endButton) {+ flips.push({+ button: target === startButton ? 'start' : 'end',+ disabled: target.getAttribute('aria-disabled') === 'true',+ held,+ batch,+ });+ }+ }+ if (wasHeld && !held) {+ log.handBack = batch;+ }+ wasHeld = held;+ });+ for (const button of [startButton, endButton]) {+ if (button != null) {+ observer.observe(button, {attributeFilter: ['aria-disabled']});+ }+ }+ observer.observe(row, {subtree: true, attributeFilter: ['style']});+ const tick = () => {+ const lead = row.children[0];+ const held = isHeld();samples.push({shown:Math.abs(row.scrollLeft) - (lead == null ? 0 : translateX(lead)),@@ -102,6 +148,24 @@ async function samplesOf(page: Page): Promise<Sample[]> {);}+// Whether the first change that brings `button` back came while the paging+// held the row, or in the task that handed it back. No frame paints between+// two changes in one task.+async function cameBackHeld(page: Page, button: Flip['button']) {+ const log = await page.evaluate(+ () =>+ (window as unknown as {__edgeLog: {flips: Flip[]; handBack: number}})+ .__edgeLog,+ );+ const flip = log.flips.find(+ change => change.button === button && !change.disabled,+ );+ return {+ held: flip != null && (flip.held || flip.batch === log.handBack),+ detail: JSON.stringify(log),+ };+}+// A flick of 80 px in 80 ms, toward the end of the row or back.async function flick(page: Page,@@ -151,7 +215,8 @@ test('the start button comes back within two frames of the held row leaving theexpect(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);+ const {held, detail: changes} = await cameBackHeld(page, 'start');+ expect(held, changes).toBe(true);});test('the end button comes back within two frames of the held row leaving the end', async ({@@ -180,7 +245,8 @@ test('the end button comes back within two frames of the held row leaving the en});expect(left, detail).toBeGreaterThanOrEqual(0);expect(back - left, detail).toBeLessThanOrEqual(2);- expect(samples[back]?.held, detail).toBe(true);+ const {held, detail: changes} = await cameBackHeld(page, 'end');+ expect(held, changes).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 ({@@ -212,5 +278,6 @@ test('after a press on the end button, the start button comes back within two frexpect(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);+ const {held, detail: changes} = await cameBackHeld(page, 'start');+ expect(held, changes).toBe(true);});diff --git a/packages/core/src/hooks/useScrollOverflow.test.tsx b/packages/core/src/hooks/useScrollOverflow.test.tsxindex 56155b8187..903bac9832 100644--- a/packages/core/src/hooks/useScrollOverflow.test.tsx+++ b/packages/core/src/hooks/useScrollOverflow.test.tsx@@ -372,6 +372,36 @@ describe('useShownScrollOverflow', () => {unmount();});+ it('commits an edge change in the report itself, so a held row changes the buttons in its frame', () => {+ const {result, unmount} = attach();+ act(() => {+ result.current.followShown({offset: 150, travel: 300});+ // Rendered before the report returns, not when the batch ends.+ expect(result.current.overflowStart).toBe(true);+ });+ unmount();+ });++ it('renders nothing for a report that changes no edge', () => {+ let renders = 0;+ const el = document.createElement('div');+ fakeScrollBox(el, {scrollWidth: 600, clientWidth: 300});+ stubRendered(el, true);+ const {result, unmount} = renderHook(() => {+ renders += 1;+ return useShownScrollOverflow();+ });+ act(() => {+ result.current.scrollRef(el);+ });+ act(() => result.current.followShown({offset: 150, travel: 300}));+ const before = renders;+ act(() => result.current.followShown({offset: 160, travel: 300}));+ act(() => result.current.followShown({offset: 170, travel: 300}));+ expect(renders).toBe(before);+ 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}));diff --git a/packages/core/src/hooks/useScrollOverflow.ts b/packages/core/src/hooks/useScrollOverflow.tsindex 305d66bf97..734654eaa6 100644--- a/packages/core/src/hooks/useScrollOverflow.ts+++ b/packages/core/src/hooks/useScrollOverflow.ts@@ -4,7 +4,7 @@/*** @file useScrollOverflow.ts- * @input React refs, state and effects+ * @input React refs, state and effects, and react-dom's flushSync* @output useScrollOverflow, which tracks the overflow at the scroll edges,* and the internal useShownScrollOverflow, which can also measure from a* position its caller reports@@ -16,6 +16,7 @@*/import {useState, useCallback, useEffect, useRef} from 'react';+import {flushSync} from 'react-dom';import {observeResize} from '../utils/sharedResizeObserver';/**@@ -116,7 +117,10 @@ export function useScrollOverflow() {/*** `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+ * reports where the row is shown, and the edges follow it. A live report+ * commits an edge change before it returns. A report that the caller's own+ * call into the paging raises passes `isLive` false. That call can run inside+ * React's commit, so the report takes React's scheduling. Null measures the* scroll offset again from the next frame, when the handed-back offset is* current. Internal: not exported from the hooks entry.*/@@ -131,8 +135,10 @@ export function useShownScrollOverflow() {overflowEnd: false,hasOverflow: false,});+ // The edges last set, so a measure that changes no edge renders nothing.+ const edgesRef = useRef(state);- const measureNow = useCallback((el: HTMLElement) => {+ const measureNow = useCallback((el: HTMLElement, isLive = false) => {const tolerance = 1;const shown = shownRef.current;const offset = shown?.offset ?? Math.abs(el.scrollLeft);@@ -142,16 +148,24 @@ export function useShownScrollOverflow() {const overflowEnd = offset < maxScroll - tolerance;const hasOverflow = maxScroll > tolerance;- setState(prev => {- if (- prev.overflowStart === overflowStart &&- prev.overflowEnd === overflowEnd &&- prev.hasOverflow === hasOverflow- ) {- return prev;- }- return {overflowStart, overflowEnd, hasOverflow};- });+ const prev = edgesRef.current;+ if (+ prev.overflowStart === overflowStart &&+ prev.overflowEnd === overflowEnd &&+ prev.hasOverflow === hasOverflow+ ) {+ return;+ }+ const next = {overflowStart, overflowEnd, hasOverflow};+ edgesRef.current = next;+ if (isLive) {+ // A live report comes from the paging's frame or event. An edge change+ // commits there, before the paging can hand the row back.+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the buttons must change in the frame the row leaves its edge+ flushSync(() => setState(next));+ } else {+ setState(next);+ }}, []);// Only a rendered container is measured at registration and on a resize or@@ -178,13 +192,13 @@ export function useShownScrollOverflow() {}, [measureNow]);const followShown = useCallback(- (shown: ShownPosition | null) => {+ (shown: ShownPosition | null, isLive = true) => {cancelAnimationFrame(releaseFrameRef.current);const el = elRef.current;if (shown != null) {shownRef.current = shown;if (el) {- measureNow(el);+ measureNow(el, isLive);}return;}