Skip to content

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

TypeScript

fix(Carousel): Shift and a wheel notch scroll the row once (#10246)

Christopher Chedeau5c71dee92c48
diff --git a/.changeset/carousel-passive-wheel-lint-note.md b/.changeset/carousel-passive-wheel-lint-note.md
deleted file mode 100644
index d460a70952..0000000000
--- a/.changeset/carousel-passive-wheel-lint-note.md
+++ /dev/null
@@ -1,7 +0,0 @@
----
-'@astryxdesign/core': patch
----
-
-[chore] Internal: Carousel's Shift+wheel handler carries a lint suppression for the new passive-handler rule until it moves to a native listener. Apps see no change.
-
-@cixzhang
diff --git a/.changeset/carousel-shift-wheel-once.md b/.changeset/carousel-shift-wheel-once.md
new file mode 100644
index 0000000000..8a2cef502a
--- /dev/null
+++ b/.changeset/carousel-shift-wheel-once.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Shift and one mouse wheel notch now scroll a `Carousel` row by the notch, once. Before, Firefox also scrolled the row on its own, so each notch moved it twice: React's wheel listener is passive, so Carousel could not stop the browser's scroll. A wheel with a horizontal delta, such as a trackpad swipe, and a row with nothing to scroll keep the browser's own scroll.
+
+@vjeux
diff --git a/packages/core/src/Carousel/Carousel.test.tsx b/packages/core/src/Carousel/Carousel.test.tsx
index d3182ad0c3..e794a21e4e 100644
--- a/packages/core/src/Carousel/Carousel.test.tsx
+++ b/packages/core/src/Carousel/Carousel.test.tsx
@@ -300,6 +300,8 @@ describe('Carousel', () => {
);
const scroller = getScroller();
makeOverflowing(scroller);
+ // The row measures its overflow again on a scroll.
+ fireEvent.scroll(scroller);
const scrollBy = vi.fn();
scroller.scrollBy = scrollBy;
@@ -308,6 +310,25 @@ describe('Carousel', () => {
expect(scrollBy).toHaveBeenCalledWith({left: 120, behavior: 'auto'});
});
+ it("stops the browser's own scroll, so a notch scrolls the row once", () => {
+ render(
+ <Carousel aria-label="Wheel">
+ <div>Item 1</div>
+ <div>Item 2</div>
+ </Carousel>,
+ );
+ const scroller = getScroller();
+ makeOverflowing(scroller);
+ // The row measures its overflow again on a scroll.
+ fireEvent.scroll(scroller);
+ scroller.scrollBy = vi.fn();
+
+ // A listener that called preventDefault() makes dispatch return false.
+ expect(
+ fireEvent.wheel(scroller, {shiftKey: true, deltaY: 120, deltaX: 0}),
+ ).toBe(false);
+ });
+
it('does not translate wheel without Shift held', () => {
render(
<Carousel aria-label="Wheel">
@@ -317,6 +338,8 @@ describe('Carousel', () => {
);
const scroller = getScroller();
makeOverflowing(scroller);
+ // The row measures its overflow again on a scroll.
+ fireEvent.scroll(scroller);
const scrollBy = vi.fn();
scroller.scrollBy = scrollBy;
@@ -335,6 +358,8 @@ describe('Carousel', () => {
);
const scroller = getScroller();
makeOverflowing(scroller);
+ // The row measures its overflow again on a scroll.
+ fireEvent.scroll(scroller);
const scrollBy = vi.fn();
scroller.scrollBy = scrollBy;
@@ -343,6 +368,62 @@ describe('Carousel', () => {
expect(scrollBy).not.toHaveBeenCalled();
});
+ it('reads no style or layout on a wheel over the row, with Shift or without', () => {
+ render(
+ <Carousel aria-label="Wheel">
+ <div>Item 1</div>
+ <div>Item 2</div>
+ </Carousel>,
+ );
+ const scroller = getScroller();
+ let reads = 0;
+ for (const [name, value] of [
+ ['scrollWidth', 500],
+ ['clientWidth', 200],
+ ] as const) {
+ Object.defineProperty(scroller, name, {
+ configurable: true,
+ get: () => {
+ reads += 1;
+ return value;
+ },
+ });
+ }
+ fireEvent.scroll(scroller);
+ scroller.scrollBy = vi.fn();
+ reads = 0;
+ const style = vi.spyOn(window, 'getComputedStyle');
+
+ fireEvent.wheel(scroller, {deltaY: 120});
+ fireEvent.wheel(scroller, {shiftKey: true, deltaY: 120});
+ const styles = style.mock.calls.length;
+ style.mockRestore();
+
+ expect({reads, styles}).toEqual({reads: 0, styles: 0});
+ expect(scroller.scrollBy).toHaveBeenCalledTimes(1);
+ });
+
+ it('adds no wheel listener to a row with nothing to scroll', () => {
+ const addEventListener = vi.spyOn(
+ HTMLElement.prototype,
+ 'addEventListener',
+ );
+ render(
+ <Carousel aria-label="Wheel">
+ <div>Item 1</div>
+ </Carousel>,
+ );
+ const scroller = getScroller();
+ const wheels = addEventListener.mock.contexts.filter(
+ (element, call) =>
+ element === scroller &&
+ addEventListener.mock.calls[call][0] === 'wheel',
+ );
+ addEventListener.mockRestore();
+
+ expect(wheels).toHaveLength(0);
+ });
+
it('does not intercept when there is no horizontal overflow', () => {
render(
<Carousel aria-label="Wheel">
diff --git a/packages/core/src/Carousel/Carousel.tsx b/packages/core/src/Carousel/Carousel.tsx
index 77ae24ab93..a8401df4b8 100644
--- a/packages/core/src/Carousel/Carousel.tsx
+++ b/packages/core/src/Carousel/Carousel.tsx
@@ -455,60 +455,51 @@ export function Carousel({
: attachSnapPaging(attachedPaging, scroller),
attachedPaging,
);
- // React's wheel listener is passive. While a flick holds the row, the paging
- // takes a wheel the gesture host leaves to the stop nearest its travel.
+ // React's wheel listener is passive, so it can't stop the browser's own
+ // scroll; this native one can. While a flick holds the row, the paging takes
+ // a wheel the gesture host leaves to the stop nearest its travel.
+ //
+ // A mouse wheel gives only deltaY. Shift + wheel is the convention for a
+ // horizontal scroll. A trackpad gives deltaX, so the browser scrolls the row.
+ // A row that fits gets no listener, so a page scroll over it does not wait
+ // for script. The listener reads no style or layout. Only a held row's move
+ // reads the row's direction.
useAttachment(
scrollElRef,
el => {
+ if (!hasOverflow) {
+ return () => {};
+ }
const onWheel = (event: WheelEvent) => {
+ if (event.defaultPrevented) {
+ return;
+ }
const delta = event.deltaX || (event.shiftKey ? event.deltaY : 0);
- const travel = isRtlElement(el) ? -delta : delta;
if (
- !event.defaultPrevented &&
delta !== 0 &&
moveHeldSnapPaging(el, (at, end) =>
- nearestStop(snapStops(el, at, end), at + travel),
+ nearestStop(
+ snapStops(el, at, end),
+ at + (isRtlElement(el) ? -delta : delta),
+ ),
)
) {
event.preventDefault();
event.stopPropagation();
+ return;
}
+ if (!event.shiftKey || event.deltaY === 0 || event.deltaX !== 0) {
+ return;
+ }
+ event.preventDefault();
+ el.scrollBy({left: event.deltaY, behavior: 'auto'});
};
- if (attachedPaging == null) {
- return () => {};
- }
el.addEventListener('wheel', onWheel, {passive: false});
return () => el.removeEventListener('wheel', onWheel);
},
- attachedPaging,
+ hasOverflow,
);
- // Map Shift + vertical wheel to horizontal scroll. Trackpads emit
- // horizontal deltas natively, but a standard mouse only produces deltaY —
- // so mouse users can't wheel-scroll a horizontal container. Shift + wheel
- // is the long-established convention for horizontal scroll containers; we
- // honor it by translating the vertical delta into a horizontal scroll.
- //
- // Only kicks in when Shift is held and the wheel is purely vertical
- // (deltaX === 0), so native trackpad horizontal scrolling is untouched.
- const handleWheel = useCallback((event: React.WheelEvent<HTMLDivElement>) => {
- if (!event.shiftKey || event.deltaY === 0 || event.deltaX !== 0) {
- return;
- }
- const el = scrollElRef.current;
- if (!el) {
- return;
- }
- // Nothing to scroll horizontally — let the event fall through so the page
- // can scroll as it normally would.
- if (el.scrollWidth <= el.clientWidth) {
- return;
- }
- // eslint-disable-next-line @astryx/no-prevent-default-in-passive-react-handler -- passive React handler: preventDefault() is ignored; a native non-passive listener replaces it
- event.preventDefault();
- el.scrollBy({left: event.deltaY, behavior: 'auto'});
- }, []);
-
const scrollBy = useCallback(
(direction: -1 | 1) => {
const el = scrollElRef.current;
@@ -738,7 +729,6 @@ export function Carousel({
role="group"
aria-label={ariaLabel}
tabIndex={hasOverflow ? 0 : -1}
- onWheel={handleWheel}
{...focusOwnerProps}
{...mergeProps(
themeProps('carousel-scroller', {
diff --git a/packages/core/src/Carousel/__tests__/Carousel.interaction.browser.spec.ts b/packages/core/src/Carousel/__tests__/Carousel.interaction.browser.spec.ts
new file mode 100644
index 0000000000..0fc5316918
--- /dev/null
+++ b/packages/core/src/Carousel/__tests__/Carousel.interaction.browser.spec.ts
@@ -0,0 +1,137 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Carousel.interaction.browser.spec.ts
+ * @input The built Carousel stories and a real mouse wheel (Chromium CDP /
+ * WebKit's injected events) through the interaction harness
+ * @output Proof that Shift and one mouse wheel notch scroll the row once, by
+ * the notch's delta. Carousel prevents the wheel's default, so the
+ * browser's own horizontal scroll adds nothing. Firefox shows that second
+ * scroll when the default runs
+ * @position Browser proof for Carousel, run by `pnpm test:interaction`
+ */
+
+import {expect, test} from '@astryxdesign/a11y-spec/playwright';
+import {openStory, withStorybook} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+test.describe('with a mouse', () => {
+ test.use({hasTouch: false, isMobile: false});
+
+ test('Shift and a wheel notch scroll the row by the notch, once', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-carousel--default');
+ const scroller = page.getByRole('region').getByRole('group').first();
+ // The window hears the wheel last, after every listener in the page.
+ const wheel = page.evaluate(
+ async () =>
+ new Promise<{notch: number; isPrevented: boolean}>(resolve => {
+ window.addEventListener(
+ 'wheel',
+ event =>
+ resolve({
+ notch: event.deltaY,
+ isPrevented: event.defaultPrevented,
+ }),
+ {once: true},
+ );
+ }),
+ );
+ await scroller.hover();
+ await page.keyboard.down('Shift');
+ await page.mouse.wheel(0, 100);
+ await page.keyboard.up('Shift');
+ // The row's offset once two reads a while apart agree.
+ let last = -1;
+ await expect
+ .poll(
+ async () => {
+ const at = await scroller.evaluate(el => el.scrollLeft);
+ const isStill = at === last;
+ last = at;
+ return isStill && at > 0;
+ },
+ {intervals: [200]},
+ )
+ .toBe(true);
+ const {notch, isPrevented} = await wheel;
+ expect(isPrevented).toBe(true);
+ expect(last).toBeCloseTo(notch, 0);
+ });
+ test('a wheel tick over the row reads no style or layout, with Shift or without', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-carousel--default');
+ const scroller = page.getByRole('region').getByRole('group').first();
+ // Counts style and layout reads made while the page dispatches a wheel.
+ await page.evaluate(() => {
+ const probe = window as unknown as {reads: number; isCounting: boolean};
+ probe.reads = 0;
+ probe.isCounting = false;
+ const count = () => {
+ if (probe.isCounting) {
+ probe.reads += 1;
+ }
+ };
+ const computedStyle = window.getComputedStyle.bind(window);
+ window.getComputedStyle = (element, pseudo) => {
+ count();
+ return computedStyle(element, pseudo);
+ };
+ const getters: [object, string[]][] = [
+ [
+ Element.prototype,
+ ['scrollWidth', 'scrollHeight', 'scrollLeft', 'scrollTop'],
+ ],
+ [Element.prototype, ['clientWidth', 'clientHeight']],
+ [
+ HTMLElement.prototype,
+ ['offsetWidth', 'offsetHeight', 'offsetLeft', 'offsetTop'],
+ ],
+ ];
+ for (const [prototype, names] of getters) {
+ for (const name of names) {
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
+ const read = descriptor?.get;
+ if (descriptor == null || read == null) {
+ continue;
+ }
+ Object.defineProperty(prototype, name, {
+ ...descriptor,
+ get(this: Element): number {
+ count();
+ return read.call(this) as number;
+ },
+ });
+ }
+ }
+ const rect = Element.prototype.getBoundingClientRect;
+ Element.prototype.getBoundingClientRect = function (this: Element) {
+ count();
+ return rect.call(this);
+ };
+ window.addEventListener(
+ 'wheel',
+ () => {
+ probe.reads = 0;
+ probe.isCounting = true;
+ },
+ {capture: true},
+ );
+ window.addEventListener('wheel', () => {
+ probe.isCounting = false;
+ });
+ });
+ const reads = async () =>
+ page.evaluate(() => (window as unknown as {reads: number}).reads);
+ await scroller.hover();
+ await page.mouse.wheel(0, 100);
+ const plain = await reads();
+ await page.keyboard.down('Shift');
+ await page.mouse.wheel(0, 100);
+ await page.keyboard.up('Shift');
+ expect({plain, shift: await reads()}).toEqual({plain: 0, shift: 0});
+ });
+});