diff --git a/.changeset/carousel-snap-paging.md b/.changeset/carousel-snap-paging.md new file mode 100644 index 0000000000000..0ff90e1e99c6b --- /dev/null +++ b/.changeset/carousel-snap-paging.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] Carousel's `hasSnap` also takes `useSnapPaging()`, from `@astryxdesign/core/SnapPaging`: iOS paging on native snap's stops, under a finger and on a trackpad swipe. A flick moves one view, or one item with `useSnapPaging({pages: 'item'})`. A mouse wheel keeps native snapping. Only a carousel given the hook's value loads the pager, and `hasSnap` alone is unchanged. + +@vjeux diff --git a/.changeset/use-snap-paging-example.md b/.changeset/use-snap-paging-example.md new file mode 100644 index 0000000000000..ca2a89bbecd59 --- /dev/null +++ b/.changeset/use-snap-paging-example.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/cli': patch +--- + +[docs] A `useSnapPaging — Onboarding Pages` example block: onboarding cards in a Carousel with `hasSnap={useSnapPaging()}` move one view per flick, and a switch moves one card per flick through the hook's `pages` option. Copy it with `astryx template CarouselSnapPaging `. + +@vjeux diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json index 519ffa8599431..6f58e5cbe3077 100644 --- a/apps/sandbox/scripts/next-export-routes.json +++ b/apps/sandbox/scripts/next-export-routes.json @@ -146,6 +146,7 @@ "/templates/CarouselCards/", "/templates/CarouselShowcase/", "/templates/CarouselSnap/", + "/templates/CarouselSnapPaging/", "/templates/CenterHorizontal/", "/templates/CenterInsideACard/", "/templates/CenterShowcase/", diff --git a/apps/storybook/stories/Carousel.stories.tsx b/apps/storybook/stories/Carousel.stories.tsx index a1260a823431d..8d078cfd5fa9b 100644 --- a/apps/storybook/stories/Carousel.stories.tsx +++ b/apps/storybook/stories/Carousel.stories.tsx @@ -5,6 +5,7 @@ import type {Meta, StoryObj} from '@storybook/react'; import * as stylex from '@stylexjs/stylex'; import {Carousel} from '@astryxdesign/core/Carousel'; import type {CarouselHandle} from '@astryxdesign/core/Carousel'; +import {useSnapPaging} from '@astryxdesign/core/SnapPaging'; import {Thumbnail} from '@astryxdesign/core/Thumbnail'; import {Card} from '@astryxdesign/core/Card'; import {Button} from '@astryxdesign/core/Button'; @@ -53,6 +54,27 @@ const styles = stylex.create({ borderRadius: radiusVars['--radius-element'], flexShrink: 0, }, + pagingFrame: { + width: 300, + }, + pagingItem: { + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + height: 120, + borderRadius: radiusVars['--radius-element'], + backgroundColor: colorVars['--color-background-muted'], + color: colorVars['--color-text-primary'], + fontFamily: typographyVars['--font-family-body'], + fontSize: 24, + fontWeight: 600, + }, + oneUp: { + width: 300, + }, + threeUp: { + width: `calc((300px - 2 * ${spacingVars['--spacing-2']}) / 3)`, + }, label: { fontSize: 12, color: colorVars['--color-text-secondary'], @@ -468,3 +490,87 @@ export const SingleItem: Story = { ), }; + +type PagingMode = 'snap' | 'paging' | 'item'; + +/** + * A 300 px carousel of numbered items, snapping natively (`snap`) or with snap + * paging: one view per flick (`paging`) or one item (`item`). + */ +function PagingCarousel({ + layout, + count, + mode, +}: { + layout: '1-up' | '3-up'; + count: number; + mode: PagingMode; +}) { + // One value: Carousel keeps the value it first attached, and a new `pages` + // applies from the next flick. + const paging = useSnapPaging({pages: mode === 'item' ? 'item' : 'view'}); + const hasSnap = mode === 'snap' ? true : paging; + return ( +
+ + {Array.from({length: count}, (_, i) => ( +
+ {i + 1} +
+ ))} +
+
+ ); +} + +const pagingArgTypes = { + mode: { + control: {type: 'select' as const}, + options: ['snap', 'paging', 'item'], + description: + 'hasSnap (native snap), hasSnap={useSnapPaging()} (one view per flick) or hasSnap={useSnapPaging({pages: "item"})}', + }, +}; + +type PagingStory = StoryObj<{mode: PagingMode}>; + +export const SnapPagingOneUp: PagingStory = { + name: 'Snap Paging: One Item per View', + argTypes: pagingArgTypes, + args: {mode: 'paging'}, + render: ({mode}) => , +}; + +export const SnapPagingThreeUp: PagingStory = { + name: 'Snap Paging: Three Items per View', + argTypes: pagingArgTypes, + args: {mode: 'paging'}, + render: ({mode}) => , +}; + +export const SnapPagingPartialLastPage: PagingStory = { + name: 'Snap Paging: Partial Last Page', + argTypes: pagingArgTypes, + args: {mode: 'paging'}, + render: ({mode}) => , +}; + +export const SnapPagingRightToLeft: PagingStory = { + name: 'Snap Paging: Right to Left', + argTypes: pagingArgTypes, + args: {mode: 'paging'}, + render: ({mode}) => ( +
+ +
+ ), +}; diff --git a/docs/specs/components/Carousel/Carousel.spec.md b/docs/specs/components/Carousel/Carousel.spec.md index dd8e2672d3651..726f3e42c6c6f 100644 --- a/docs/specs/components/Carousel/Carousel.spec.md +++ b/docs/specs/components/Carousel/Carousel.spec.md @@ -14,6 +14,9 @@ verified_by: [ packages/core/src/Carousel/Carousel.test.tsx, packages/core/src/Carousel/__tests__/Carousel.a11y.chromium.spec.ts, + packages/core/src/SnapPaging/SnapPaging.test.tsx, + packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts, + scripts/snap-paging-bundle.test.mjs, ] modules: [] families: [family:buttons] @@ -38,7 +41,7 @@ system_specs: [spec:AST-085, spec:AST-025, spec:AST-094] | Behavior | Native snap stops each item at its start edge and leaves the momentum to the platform. Snap paging uses the same stops: under a finger, and on a trackpad swipe under every pointer, a flick moves one view by default, or one item with `{pages: 'item'}`, by `spec:AST-094` FR3's paging rule. An edge button whose direction has run out is hidden and takes no tab stop; when the focused one runs out, focus moves to the scroll area. | | End-user impact | People who swipe a paging carousel on a phone feel iOS paging; people on a carousel without it download no paging code. A keyboard user who scrolls to the first or last item stays inside the carousel. | | Builder impact | `hasSnap` and `hasSnap={true}` are unchanged. Paging is the same prop given `useSnapPaging()`. A Carousel without the paging config bundles no pager code. | -| Compatibility/readiness | Additive: `hasSnap`'s type widens from `boolean` to `boolean \| SnapPaging`, with no rename, deprecation, or codemod; `true` keeps today's native snapping and gains no paging. Implementation gap: the widened `hasSnap` and `useSnapPaging` are not built; shipped Carousel still uses native `disabled` on edge buttons. Evidence gap: `{pages: 'item'}` is not measured against UIKit's group paging (FR7). | +| Compatibility/readiness | Additive: `hasSnap`'s type widens from `boolean` to `boolean \| SnapPaging`, with no rename, deprecation, or codemod; `true` keeps today's native snapping and gains no paging. Implementation gap: shipped Carousel still uses native `disabled` on edge buttons. Evidence gap: `{pages: 'item'}` is not measured against UIKit's group paging (FR7). | | Review checks | Reject pager code reachable from Carousel's default import; a lazy `import()` of the pager; snap paging on a carousel whose `hasSnap` is not a `useSnapPaging` value; `hasSnap={true}` that pages; snap paging stops that differ from native snap's; a claim that `{pages: 'item'}` matches UIKit before it is measured; a dependency on a Chromium-only carousel feature; focus left on a hidden edge button. | | Governing rules | `spec:AST-094` FR3, FR6, FR43, DEC-25; `architecture:public-component-api` INV3 (a known deviation, DEC-2), INV22; `architecture:react-component-runtime` INV13; `spec:AST-085` FR1, FR4; `spec:AST-025` FR12; `architecture:interaction-modality` INV1. | @@ -98,17 +101,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). | 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. Implementation gap: snap paging is not built, so no trackpad swipe pages yet. | 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 only calls attach and detach on the `SnapPaging` value from an effect. 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. | 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 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). | 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 move of a row the value holds 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. | 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 @@ -165,7 +168,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 | — | -| FR8 | Bundle test on the built package: each public import built with the size report's options and its eager output attributed by module, base against head | Carousel alone; Carousel with `useSnapPaging`; a server import of the module | A Carousel without `hasSnap={useSnapPaging()}` that bundles pager code, an `import()` of the pager, or DOM work on import 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 | Carousel alone; Carousel with `useSnapPaging`; a server import of the module | A Carousel without `hasSnap={useSnapPaging()}` that bundles pager code, an `import()` of the pager, or DOM work on import fails | — | | 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 | — | ## Decision log diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json index beea5af7e88a2..897cd88208d2f 100644 --- a/internal/shadcn-registry/routes.lock.json +++ b/internal/shadcn-registry/routes.lock.json @@ -3851,6 +3851,11 @@ "path": "examples/use-scrollable-area/activity-log-panel", "aliases": [] }, + { + "name": "example-use-snap-paging-onboarding-pages", + "path": "examples/use-snap-paging/onboarding-pages", + "aliases": [] + }, { "name": "example-use-streaming-text-streaming-response", "path": "examples/use-streaming-text/streaming-response", @@ -4201,6 +4206,11 @@ "path": "hooks/use-scrollable-area", "aliases": [] }, + { + "name": "hook-use-snap-paging", + "path": "hooks/use-snap-paging", + "aliases": [] + }, { "name": "hook-use-streaming-text", "path": "hooks/use-streaming-text", diff --git a/packages/cli/assets/templates/blocks/components/Carousel/CarouselSnapPaging.doc.mjs b/packages/cli/assets/templates/blocks/components/Carousel/CarouselSnapPaging.doc.mjs new file mode 100644 index 0000000000000..a61ef869be93f --- /dev/null +++ b/packages/cli/assets/templates/blocks/components/Carousel/CarouselSnapPaging.doc.mjs @@ -0,0 +1,14 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */ +export const doc = { + type: 'block', + exampleFor: 'useSnapPaging', + name: 'useSnapPaging — Onboarding Pages', + displayName: 'useSnapPaging — Onboarding Pages', + description: + "Onboarding cards in a Carousel with hasSnap={useSnapPaging()}: under a finger or a trackpad swipe, each flick moves one view and rests on a card's start edge. A switch picks one view or one card per flick through the hook's pages option.", + isReady: true, + aspectRatio: 4 / 3, + componentsUsed: ['Carousel', 'Card', 'Layout', 'Switch', 'Text'], +}; diff --git a/packages/cli/assets/templates/blocks/components/Carousel/CarouselSnapPaging.tsx b/packages/cli/assets/templates/blocks/components/Carousel/CarouselSnapPaging.tsx new file mode 100644 index 0000000000000..925d9cf3f8574 --- /dev/null +++ b/packages/cli/assets/templates/blocks/components/Carousel/CarouselSnapPaging.tsx @@ -0,0 +1,49 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +import {useState} from 'react'; +import {Card} from '@astryxdesign/core/Card'; +import {Carousel} from '@astryxdesign/core/Carousel'; +import {Stack} from '@astryxdesign/core/Layout'; +import {useSnapPaging} from '@astryxdesign/core/SnapPaging'; +import {Switch} from '@astryxdesign/core/Switch'; +import {Text} from '@astryxdesign/core/Text'; + +const SCREENS = [ + {title: 'Welcome', body: 'Swipe to see what is new.'}, + {title: 'Shared albums', body: 'Invite friends to add their photos.'}, + {title: 'Memories', body: 'See a day from years ago.'}, + {title: 'Search', body: 'Find a photo by what is in it.'}, + {title: 'All set', body: 'Your library is ready.'}, +]; + +export default function CarouselSnapPaging() { + const [isOneCard, setIsOneCard] = useState(false); + // A flick moves one view, or one card with {pages: 'item'}. + const paging = useSnapPaging({pages: isOneCard ? 'item' : 'view'}); + + return ( + + + + {SCREENS.map(screen => ( + + + + {screen.title} + + + {screen.body} + + + + ))} + + + ); +} diff --git a/packages/core/api-report.md b/packages/core/api-report.md index 8a0dd7137af94..aec4d3e2d1b71 100644 --- a/packages/core/api-report.md +++ b/packages/core/api-report.md @@ -337,7 +337,7 @@ component Carousel(props: CarouselProps) prop hasButtons?: boolean = true prop hasEdgeFade?: boolean = true prop hasLoop?: boolean = false - prop hasSnap?: boolean = false + prop hasSnap?: boolean | SnapPaging = false prop padding?: SpacingStep = undefined (no padding) prop ref?: React.Ref prop xstyle?: StyleXStyles @@ -2946,6 +2946,7 @@ hook useSelectedItemOffset: ({…}: UseSelectedItemOffsetOptions) => UseSelected hook useSideNavCollapse: () => SideNavCollapseState hook useSideNavRenderMode: () => SideNavRenderMode hook useSize: (sizeProp?: T, defaultSize?: T) => T +hook useSnapPaging: (options?: SnapPagingOptions) => SnapPaging hook useSpeechRecognition: (options?: UseSpeechRecognitionOptions) => UseSpeechRecognitionReturn hook useStepperContext: () => StepperContextValue hook useStreamingText: (targetText: string, isStreaming: boolean, options?: UseStreamingTextOptions) => string @@ -5302,6 +5303,10 @@ interface SliderSingleProps extends SliderBaseProps valueDisplay?: 'tooltip' | 'text' | 'none' = "tooltip" width?: SizeValue inherits AriaAttributes, DOMAttributes, HTMLAttributes +interface SnapPaging + [snapPagingBrand]: true +interface SnapPagingOptions + pages?: 'view' | 'item' = 'view' type SourceRange end: number start: number @@ -8529,6 +8534,16 @@ SliderRangeProps (.) SliderSingleProps (.) ``` +## `./SnapPaging` + +### Also exported from an earlier entry point + +```text +SnapPaging (.) +SnapPagingOptions (.) +useSnapPaging (.) +``` + ## `./Spinner` ### Also exported from an earlier entry point diff --git a/packages/core/package.json b/packages/core/package.json index 13a8d126067c7..05d739f696960 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -579,6 +579,11 @@ "types": "./dist/Slider/index.d.ts", "default": "./dist/Slider/index.js" }, + "./SnapPaging": { + "source": "./src/SnapPaging/index.ts", + "types": "./dist/SnapPaging/index.d.ts", + "default": "./dist/SnapPaging/index.js" + }, "./Spinner": { "source": "./src/Spinner/index.ts", "types": "./dist/Spinner/index.d.ts", diff --git a/packages/core/src/Carousel/Carousel.doc.mjs b/packages/core/src/Carousel/Carousel.doc.mjs index 3317a6d7a27e7..8fc24902a8e6c 100644 --- a/packages/core/src/Carousel/Carousel.doc.mjs +++ b/packages/core/src/Carousel/Carousel.doc.mjs @@ -12,6 +12,7 @@ export const docs = { 'Carousel scrolls a row of items horizontally when they overflow the available width. Use it for card grids, image galleries, product lists, or any set of items that should be browsable without taking up the full page.', bestPractices: [ {guidance: true, description: 'Enable scroll-snap when each item should land precisely at the start edge, like a gallery or product list.'}, + {guidance: true, description: "For iOS paging under a finger and on a trackpad swipe, pass hasSnap={useSnapPaging()} from @astryxdesign/core/SnapPaging. A flick moves one view, or one item with useSnapPaging({pages: 'item'}). A mouse wheel keeps native snapping. Only a carousel given it loads the paging code."}, {guidance: true, description: 'Reach for hasLoop on small, cyclable sets like a photo gallery, where wrapping past the last item back to the first feels natural.'}, {guidance: true, description: 'Always provide an aria-label that describes what the carousel contains, like "Featured products" or "Team members".'}, {guidance: true, description: 'Carousel implements the WAI-ARIA APG carousel pattern (https://www.w3.org/WAI/ARIA/apg/patterns/carousel/) without auto-rotation: the region is labelled and carries aria-roledescription="carousel", each item is a group named "Slide N of M", and the scroll container is a tab stop while its content overflows, so keyboard users can pan it with the arrow keys; while everything fits it stays out of the tab order.'}, @@ -34,7 +35,7 @@ export const docs = { {name: 'hasButtons', type: 'boolean', description: 'Show prev/next navigation buttons when content is scrollable.', default: 'true'}, {name: 'hasEdgeFade', type: 'boolean', description: 'Show a gradient edge-fade mask when content overflows, signalling that more items exist off-screen.', default: 'true'}, {name: 'hasLoop', type: 'boolean', description: 'Wrap-around scrolling: next at the end scrolls to the start, prev at the start scrolls to the end. Buttons stay visible at both edges. Only engages when content overflows.', default: 'false'}, - {name: 'hasSnap', type: 'boolean', description: 'Enable scroll-snap so each child snaps to the start edge.', default: 'false'}, + {name: 'hasSnap', type: 'boolean | SnapPaging', description: "Snap each child to the start edge. hasSnap uses native CSS scroll snap. hasSnap={useSnapPaging()} adds iOS paging under a finger and on a trackpad swipe, on the same stops: a flick moves one view, or one item with useSnapPaging({pages: 'item'}). Only that value loads the paging code.", default: 'false'}, {name: 'padding', type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10', description: 'Inline padding inside the scroll container, with matching scroll-padding so snap points align to the content edge.'}, {name: 'aria-label', type: 'string', description: 'Accessible label for the carousel region.', default: "\'Carousel\'"}, {name: 'ref', type: 'React.Ref', description: 'Ref forwarded to the root element.'}, @@ -84,7 +85,7 @@ export const docsZh = { hasButtons: '内容可滚动时显示上一个/下一个导航按钮。', hasEdgeFade: '内容溢出时显示渐变边缘遮罩,提示屏幕外还有更多项目。', hasLoop: '环绕滚动:在末尾按"下一个"回到开头,在开头按"上一个"跳到末尾。按钮在两端始终可见。仅在内容溢出时生效。', - hasSnap: '启用滚动吸附,使每个子元素吸附到起始边缘。', + hasSnap: "使每个子元素吸附到起始边缘。hasSnap 使用原生 CSS 滚动吸附。hasSnap={useSnapPaging()} 在相同吸附点上增加手指和触控板轻扫下的 iOS 分页:一次轻扫移动一屏,或用 useSnapPaging({pages: 'item'}) 移动一项。只有该值会加载分页代码。", padding: '滚动容器内的内联内边距,并设置匹配的 scroll-padding,使吸附点与内容边缘对齐。', 'aria-label': '轮播区域的无障碍标签。', handleRef: '命令式句柄,暴露 scrollNext()、scrollPrev()、scrollTo(index)、canScrollNext() 和 canScrollPrev() 以进行编程式滚动控制。', @@ -114,7 +115,7 @@ export const docsDense = { hasButtons: 'prev/next buttons when content is scrollable', hasEdgeFade: 'gradient edge-fade mask on overflow', hasLoop: 'wrap-around: next at end -> start, prev at start -> end; buttons stay visible; only when overflowing', - hasSnap: 'scroll-snap; children snap to start edge', + hasSnap: "scroll-snap; children snap to start edge. hasSnap={useSnapPaging()}: iOS paging under a finger or trackpad swipe, one view per flick ({pages: 'item'}: one item); only that value loads the pager", padding: 'inline padding; scroll-padding keeps snap points on content edge', 'aria-label': 'accessible label for carousel region', handleRef: 'imperative handle: scrollNext/scrollPrev/scrollTo(index)/canScrollNext/canScrollPrev', diff --git a/packages/core/src/Carousel/Carousel.tsx b/packages/core/src/Carousel/Carousel.tsx index 8ba62b7c490d9..c589507f285f7 100644 --- a/packages/core/src/Carousel/Carousel.tsx +++ b/packages/core/src/Carousel/Carousel.tsx @@ -30,6 +30,7 @@ import { useCallback, useEffect, useImperativeHandle, + useState, Children, isValidElement, } from 'react'; @@ -45,6 +46,7 @@ import { import {Button} from '../Button'; import {Icon} from '../Icon'; import {useLayer} from '../Layer'; +import {useAttachment} from '../hooks/useAttachment'; import {useScrollOverflow} from '../hooks/useScrollOverflow'; import {isRtlElement} from '../hooks/isRtlElement'; import type {BaseProps} from '../BaseProps'; @@ -53,6 +55,14 @@ import type {SpacingStep} from '../utils/types'; import {themeProps} from '../utils/themeProps'; import {useMergedRefs} from '../hooks/useMergedRefs'; +import { + attachSnapPaging, + isSnapPaging, + moveHeldSnapPaging, + nearestStop, + type SnapPaging, + snapStops, +} from '../SnapPaging/snapPagingValue'; import { registerEnglishFallback, useComponentTranslator, @@ -132,10 +142,14 @@ export interface CarouselProps extends BaseProps { */ hasLoop?: boolean; /** - * Enable scroll-snap on items. Each direct child snaps to the start edge. + * Snap each item to the start edge. `true` (written `hasSnap`) uses native + * CSS scroll snap. A `useSnapPaging()` value adds iOS paging on the same + * stops, under a finger and on a trackpad swipe. A flick moves one view, or + * one item with `useSnapPaging({pages: 'item'})`. Only that value loads the + * paging code. * @default false */ - hasSnap?: boolean; + hasSnap?: boolean | SnapPaging; /** * Inline padding on the scroll container. Applied as padding-inline * so the gutter is inside the scrollable area — items can scroll fully @@ -307,6 +321,38 @@ const paddingStyles = stylex.create({ }, }); +/** + * 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 + * an edge goes to the opposite edge. + */ +function pagingStep( + el: HTMLElement, + at: number, + end: number, + direction: -1 | 1, + wraps: boolean, +): number { + if (wraps && (direction === 1 ? at >= end - 0.5 : at <= 0.5)) { + return direction === 1 ? 0 : end; + } + const firstChild = el.firstElementChild as HTMLElement | null; + const itemWidth = firstChild ? firstChild.offsetWidth : 0; + const amount = el.clientWidth - itemWidth * 0.5; + const stops = snapStops(el, at, end); + const nearest = nearestStop( + stops, + at + direction * Math.max(amount, itemWidth), + ); + if (direction === 1 && nearest <= at + 0.5) { + return stops.find(stop => stop > at + 0.5) ?? nearest; + } + if (direction === -1 && nearest >= at - 0.5) { + return [...stops].reverse().find(stop => stop < at - 0.5) ?? nearest; + } + return nearest; +} + // ============================================================================= // Component // ============================================================================= @@ -386,6 +432,51 @@ export function Carousel({ [scrollRef], ); + // Snap paging attaches once, with the first value. A new value on a later + // render does not restart a settle or attach again. + const snapPaging = isSnapPaging(hasSnap) ? hasSnap : null; + const isPaging = snapPaging != null; + const [attachedPaging, setAttachedPaging] = useState(snapPaging); + if ((attachedPaging != null) !== isPaging) { + setAttachedPaging(snapPaging); + } + // Attaches snap paging to the scroll area, and follows a replaced one. + useAttachment( + scrollElRef, + scroller => + attachedPaging == null + ? () => {} + : 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. + useAttachment( + scrollElRef, + el => { + const onWheel = (event: WheelEvent) => { + 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), + ) + ) { + event.preventDefault(); + event.stopPropagation(); + } + }; + if (attachedPaging == null) { + return () => {}; + } + el.addEventListener('wheel', onWheel, {passive: false}); + return () => el.removeEventListener('wheel', onWheel); + }, + attachedPaging, + ); + // 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 @@ -417,6 +508,14 @@ export function Carousel({ if (!el) { return; } + // While a flick's drag or settle holds the row, the paging moves it. + if ( + moveHeldSnapPaging(el, (at, end) => + pagingStep(el, at, end, direction, hasLoop && hasOverflow), + ) + ) { + return; + } // Respect the user's reduced-motion preference — mirrors the CSS // scroll-behavior override so button-driven scrolling doesn't animate // for users who opted out of motion. @@ -446,6 +545,20 @@ export function Carousel({ const firstChild = el.firstElementChild as HTMLElement | null; const itemWidth = firstChild ? firstChild.offsetWidth : 0; const amount = el.clientWidth - itemWidth * 0.5; + if (isPaging) { + // Snap paging lands the step on the nearest stop, at least one stop + // on, in every engine. A native snap after scrollBy picks its own. + const end = Math.max(0, el.scrollWidth - el.clientWidth); + const next = pagingStep( + el, + Math.abs(el.scrollLeft), + end, + direction, + false, + ); + el.scrollTo({left: rtlSign * next, behavior}); + return; + } el.scrollBy({ // `direction` is the logical intent (-1 = toward content start, +1 = // toward content end). @@ -453,7 +566,7 @@ export function Carousel({ behavior, }); }, - [hasLoop, hasOverflow, overflowStart, overflowEnd], + [hasLoop, hasOverflow, overflowStart, overflowEnd, isPaging], ); const scrollToIndex = useCallback((index: number) => { @@ -478,6 +591,11 @@ export function Carousel({ const delta = isRtlElement(el) ? itemRect.right - containerRect.right : itemRect.left - containerRect.left; + if ( + moveHeldSnapPaging(el, at => at + (isRtlElement(el) ? -delta : delta)) + ) { + return; + } el.scrollBy({ left: delta, behavior: prefersReducedMotion ? 'auto' : 'smooth', diff --git a/packages/core/src/SnapPaging/SnapPaging.test.tsx b/packages/core/src/SnapPaging/SnapPaging.test.tsx new file mode 100644 index 0000000000000..2f487f8abb3d2 --- /dev/null +++ b/packages/core/src/SnapPaging/SnapPaging.test.tsx @@ -0,0 +1,244 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file SnapPaging.test.tsx + * @input vitest (jsdom), Testing Library, SnapPaging, Carousel + * @output Proves the hook in Carousel. It claims the row's pans under every + * pointer, and dropping the value or unmounting removes every listener it + * added. Its entry has no `create…` equivalent. The value is stable, and + * Carousel attaches it once and snaps as `hasSnap` does + * @position Testing; the paging motion itself is in the browser proofs + */ + +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {act, render, renderHook, screen} from '@testing-library/react'; +import {Carousel} from '../Carousel/Carousel'; +import {useSnapPaging} from './SnapPaging'; +import { + isSnapPaging, + makeSnapPaging, + nearestStop, + type SnapPagingAttachment, +} from './snapPagingValue'; + +class MockResizeObserver { + observe() {} + unobserve() {} + disconnect() {} +} + +/** The primary pointer each case runs under, read live by every list. */ +const pointer = {coarse: false}; +const listeners = new Set<() => void>(); + +beforeEach(() => { + pointer.coarse = false; + listeners.clear(); + vi.stubGlobal('ResizeObserver', MockResizeObserver); + vi.stubGlobal( + 'matchMedia', + vi.fn((query: string) => ({ + get matches() { + return query.includes('pointer: coarse') ? pointer.coarse : false; + }, + media: query, + onchange: null, + addListener: vi.fn(), + removeListener: vi.fn(), + addEventListener: (_type: string, listener: () => void) => + listeners.add(listener), + removeEventListener: (_type: string, listener: () => void) => + listeners.delete(listener), + dispatchEvent: vi.fn(), + })), + ); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + document.body.innerHTML = ''; +}); + +const attachment = (detach = () => {}): SnapPagingAttachment => ({ + detach, + moveHeld: () => false, +}); + +/** The touch-action the gesture host derived for `element`, '' for none. */ +const touchAction = (element: HTMLElement) => + element.getAttribute('data-astryx-touch-action') ?? ''; + +describe('useSnapPaging', () => { + it('returns one value for the component\u2019s life, which only Carousel reads', () => { + const {result, rerender} = renderHook( + ({pages}: {pages: 'view' | 'item'}) => useSnapPaging({pages}), + {initialProps: {pages: 'view'}}, + ); + const first = result.current; + expect(isSnapPaging(first)).toBe(true); + rerender({pages: 'item'}); + expect(result.current).toBe(first); + expect(isSnapPaging({})).toBe(false); + }); + + it('is the entry\u2019s only export: no create\u2026 equivalent feeds anything else', async () => { + const entry = await import('./index'); + expect(Object.keys(entry)).toEqual(['useSnapPaging']); + }); +}); + +describe('Carousel with hasSnap', () => { + function scroller() { + return screen + .getByRole('region', {name: 'Items'}) + .querySelector('[role="group"]') as HTMLElement; + } + + it('hands its scroll area to the hook\u2019s value under every pointer, a fine one included', () => { + function Paging() { + return ( + +
One
+
Two
+
+ ); + } + const {unmount} = render(); + expect(touchAction(scroller())).toBe('pan-y pinch-zoom'); + unmount(); + }); + + it('removes every listener it added to the scroll area when Carousel drops the value or unmounts', () => { + // Every listener added to or removed from any target, in order. + const log: { + isAdd: boolean; + target: EventTarget; + type: string; + listener: unknown; + }[] = []; + const realAdd = EventTarget.prototype.addEventListener; + const realRemove = EventTarget.prototype.removeEventListener; + const add = vi + .spyOn(EventTarget.prototype, 'addEventListener') + .mockImplementation(function (this: EventTarget, type, listener, opts) { + log.push({isAdd: true, target: this, type, listener}); + realAdd.call(this, type, listener, opts); + }); + const remove = vi + .spyOn(EventTarget.prototype, 'removeEventListener') + .mockImplementation(function (this: EventTarget, type, listener, opts) { + log.push({isAdd: false, target: this, type, listener}); + realRemove.call(this, type, listener, opts); + }); + try { + function Toggle({isPaging}: {isPaging: boolean}) { + const paging = useSnapPaging(); + return ( + +
One
+
Two
+
+ ); + } + const {rerender, unmount} = render(); + const element = scroller(); + // The listeners added to the scroll area since `since` and still on it. + const live = (since: number) => { + const ids = new Map(); + const keyOf = (type: string, listener: unknown) => { + if (!ids.has(listener)) { + ids.set(listener, ids.size); + } + return `${type}|${ids.get(listener)}`; + }; + const keys = new Set(); + for (const entry of log.slice(since)) { + if (entry.target !== element) { + continue; + } + const key = keyOf(entry.type, entry.listener); + if (entry.isAdd) { + keys.add(key); + } else { + keys.delete(key); + } + } + return [...keys]; + }; + let since = log.length; + rerender(); + expect(touchAction(element)).toBe('pan-y pinch-zoom'); + expect(live(since).length).toBeGreaterThan(0); + rerender(); + expect(touchAction(element)).toBe(''); + expect(live(since)).toEqual([]); + since = log.length; + rerender(); + expect(live(since).length).toBeGreaterThan(0); + act(() => unmount()); + expect(live(since)).toEqual([]); + } finally { + add.mockRestore(); + remove.mockRestore(); + } + }); + + it('runs no gesture code with hasSnap alone', () => { + pointer.coarse = true; + render( + +
One
+
Two
+
, + ); + expect(touchAction(scroller())).toBe(''); + }); + + it('snaps alike with hasSnap and with a paging value, and not without either', () => { + const value = makeSnapPaging(() => attachment()); + const classes = (hasSnap?: boolean | typeof value) => { + const {unmount} = render( + +
One
+
, + ); + const className = scroller().className; + unmount(); + return className; + }; + const snapped = classes(true); + expect(classes(value)).toBe(snapped); + expect(classes(false)).not.toBe(snapped); + expect(classes(undefined)).toBe(classes(false)); + }); + + it('nearestStop picks the nearest stop, and keeps the offset with no items', () => { + expect(nearestStop([0, 103, 205], 120)).toBe(103); + expect(nearestStop([], 42)).toBe(42); + }); + + it('attaches once: a new paging value on a later render attaches nothing again', () => { + const attached: string[] = []; + const first = makeSnapPaging(() => { + attached.push('first'); + return attachment(() => attached.push('first detached')); + }); + const second = makeSnapPaging(() => { + attached.push('second'); + return attachment(() => attached.push('second detached')); + }); + const {rerender, unmount} = render( + +
One
+
, + ); + rerender( + +
One
+
, + ); + expect(attached).toEqual(['first']); + act(() => unmount()); + expect(attached).toEqual(['first', 'first detached']); + }); +}); diff --git a/packages/core/src/SnapPaging/SnapPaging.ts b/packages/core/src/SnapPaging/SnapPaging.ts new file mode 100644 index 0000000000000..d9e306083dabf --- /dev/null +++ b/packages/core/src/SnapPaging/SnapPaging.ts @@ -0,0 +1,364 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file SnapPaging.ts + * @input The shared pager, each child's own animator and the + * writing-direction read + * @output `useSnapPaging`: UIKit paging on Carousel's row of snap items, under + * a finger and on a trackpad swipe, for every pointer + * @position Public, from `@astryxdesign/core/SnapPaging` and the root. The + * only module that brings the pager to Carousel + */ + +import {useRef, useState} from 'react'; +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 { + makeSnapPaging, + type SnapPaging, + type SnapPagingAttachment, + type SnapPagingOptions, + snapStops, +} from './snapPagingValue'; + +export type {SnapPaging, SnapPagingOptions} from './snapPagingValue'; + +/** + * Snap paging for Carousel: ``. Carousel + * attaches the value to its scroll area. A flick moves one view by default, or + * one item with `{pages: 'item'}`. The same value lasts for the component's + * life, so a render attaches nothing again; a new `pages` applies from the + * next flick. + * + * @example + * ``` + * {cards} + * ``` + */ +export function useSnapPaging(options: SnapPagingOptions = {}): SnapPaging { + const optionsRef = useRef(options); + // Syncs optionsRef with the committed render, so a new `pages` applies from + // the next flick. It is written at commit: a render that React discards + // must not leave its options behind. + useIsomorphicLayoutEffect(() => { + optionsRef.current = options; + }); + const [value] = useState(() => { + const live: SnapPagingOptions = { + get pages() { + return optionsRef.current.pages; + }, + }; + return makeSnapPaging(element => attachPaging(element, live)); + }); + return value; +} + +/** + * The view pages from stop `anchor`. Each lies on the stop nearest one view + * on from the last, and at least one stop on. + */ +function viewPages( + stops: ReadonlyArray, + anchor: number, + width: number, +): number[] { + const nearest = (to: number) => { + let best = 0; + for (let i = 1; i < stops.length; i++) { + if (Math.abs(stops[i] - to) < Math.abs(stops[best] - to)) { + best = i; + } + } + return best; + }; + const pages = [stops[anchor]]; + for (let i = anchor; i < stops.length - 1;) { + i = Math.max(nearest(stops[i] + width), i + 1); + pages.push(stops[i]); + } + for (let i = anchor; i > 0;) { + i = Math.min(nearest(stops[i] - width), i - 1); + pages.unshift(stops[i]); + } + return pages; +} + +/** One handle for the same motion on every child. */ +function combined(handles: ReadonlyArray): MotionHandle { + const [lead] = handles; + return { + properties: lead.properties, + finished: Promise.all(handles.map(async handle => handle.finished)).then( + results => results.every(Boolean), + ), + started: lead.started, + value: (property, time) => lead.value(property, time), + velocity: (property, time) => lead.velocity(property, time), + curve: property => lead.curve(property), + retarget: (to, transition, options) => + combined(handles.map(handle => handle.retarget(to, transition, options))), + stop: () => { + for (const handle of handles) { + handle.stop(); + } + }, + }; +} + +/** + * The track the pager moves. At rest the row scrolls natively, and the + * position is its scroll offset. A gesture takes the row over: its scroll + * 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) { + let isMoving = false; + let heldOffset = 0; + let heldTravel = 0; + // The row's own inline snap type, back at the hand-back. + let ownSnapType = ''; + const children = () => + Array.from(element.children).filter( + (child): child is HTMLElement => child instanceof HTMLElement, + ); + const isRtl = () => isRtlElement(element); + // The pager's x for a position, and what a child's translate adds to it. + const sign = () => (isRtl() ? -1 : 1); + const xOf = (position: number) => -sign() * position; + const nativePosition = () => Math.abs(element.scrollLeft); + const padding = () => { + const style = getComputedStyle(element); + const left = Number.parseFloat(style.scrollPaddingLeft) || 0; + const right = Number.parseFloat(style.scrollPaddingRight) || 0; + return isRtl() ? {start: right, end: left} : {start: left, end: right}; + }; + const toChild = (x: number) => x + sign() * heldOffset; + + function position(): number { + const first = children()[0]; + if (!isMoving || first == null) { + return nativePosition(); + } + return -sign() * (animatorFor(first).get('x') - sign() * heldOffset); + } + + // A held row's translate widens its overflow, so its travel is the one it + // was taken over with. + function travel(): number { + return isMoving + ? heldTravel + : Math.max(0, element.scrollWidth - element.clientWidth); + } + + function stops(): number[] { + return snapStops(element, position(), travel()); + } + + function viewWidth(): number { + const {start, end} = padding(); + return Math.max(1, element.clientWidth - start - end); + } + + function place(at: number): void { + for (const child of children()) { + animatorFor(child).set({x: toChild(xOf(at))}); + } + } + + function takeOver(): void { + if (isMoving) { + return; + } + heldOffset = nativePosition(); + heldTravel = Math.max(0, element.scrollWidth - element.clientWidth); + isMoving = true; + // A snap type would snap the row again as its children move. + ownSnapType = element.style.getPropertyValue('scroll-snap-type'); + element.style.setProperty('scroll-snap-type', 'none'); + // A flick moves one view at most: the items within a view of the + // viewport get their own layers, and no others. + const box = element.getBoundingClientRect(); + for (const child of children()) { + const rect = child.getBoundingClientRect(); + if ( + rect.right >= box.left - box.width && + rect.left <= box.right + box.width + ) { + child.style.setProperty('will-change', 'transform'); + } + } + place(heldOffset); + } + + function handBack(): void { + if (!isMoving) { + return; + } + const at = position(); + for (const child of children()) { + const animator = animatorFor(child); + animator.stop(['x']); + animator.set({x: 0}); + child.style.removeProperty('translate'); + child.style.removeProperty('will-change'); + } + isMoving = false; + if (ownSnapType === '') { + element.style.removeProperty('scroll-snap-type'); + } else { + element.style.setProperty('scroll-snap-type', ownSnapType); + } + element.scrollTo({left: isRtl() ? -at : at, behavior: 'instant'}); + } + + const animator: PagerAnimator = { + get(property, time) { + const first = children()[0]; + if (!isMoving || first == null) { + return property === 'x' ? xOf(nativePosition()) : 0; + } + const value = animatorFor(first).get(property, time); + return property === 'x' ? value - sign() * heldOffset : value; + }, + getVelocity(property, time) { + const first = children()[0]; + return isMoving && first != null + ? animatorFor(first).getVelocity(property, time) + : 0; + }, + set(values, options) { + if (!isMoving) { + return; + } + const shifted = + values.x == null ? values : {...values, x: toChild(values.x)}; + for (const child of children()) { + animatorFor(child).set(shifted, options); + } + }, + stop(properties) { + if (!isMoving) { + return; + } + for (const child of children()) { + animatorFor(child).stop(properties); + } + }, + play(curves, options) { + takeOver(); + const offset = sign() * heldOffset; + const x = curves.x; + const shifted = + x == null + ? curves + : { + ...curves, + x: {...x, at: (t: number) => x.at(t) + offset}, + }; + const items = children(); + const handles = (items.length > 0 ? items : [element]).map(child => + animatorFor(child).play(shifted, options), + ); + return combined(handles); + }, + }; + + return { + animator, + get isMoving() { + return isMoving; + }, + position, + travel, + stops, + viewWidth, + place, + takeOver, + handBack, + }; +} + +/** + * The pager on the row's children. A finger, a pen or a trackpad swipe takes + * the row over, and the settle gives it back. A mouse drag and a mouse wheel + * leave the row to native scrolling. + */ +function attachPaging( + element: HTMLElement, + options: SnapPagingOptions, +): SnapPagingAttachment { + const track = childTrack(element); + // The stop that view pages count from, set when a gesture takes over. + let anchor = 0; + const pager = createPager( + { + count: 1, + pages: 'children', + // A trackpad swipe is a scroll, not a pointer, so it pages whatever + // the pointer kinds. + panOptions: {allowedPointerTypes: ['touch', 'pen']}, + measurePages: () => { + const stops = track.stops(); + return (options.pages ?? 'view') === 'item' + ? stops + : viewPages( + stops, + Math.min(anchor, stops.length - 1), + track.viewWidth(), + ); + }, + shouldBeginPan: () => { + if (!track.isMoving) { + const at = track.position(); + const stops = track.stops(); + anchor = stops.reduce( + (best, stop, i) => + Math.abs(stop - at) < Math.abs(stops[best] - at) ? i : best, + 0, + ); + track.takeOver(); + pager.setOptions({}); + pager.goTo(pager.nearestPage(at), { + animated: false, + reason: 'controlled', + }); + // The finger catches the row where it is shown. + track.place(at); + } + return true; + }, + onSettle: () => { + if (!pager.isDragging && !pager.isSettling) { + track.handBack(); + } + }, + }, + {animator: track.animator}, + ); + const detach = pager.attach(element, element); + return { + detach: () => { + detach(); + pager.dispose(); + track.handBack(); + }, + moveHeld: target => { + if (!track.isMoving) { + return false; + } + // A finger on the row keeps it. + if (!pager.isDragging) { + const end = track.travel(); + const to = Math.min(Math.max(target(track.position(), end), 0), end); + // The pager's own move: a finger catches it as it catches a settle. + pager.goTo(pager.nearestPage(to), {offset: to}); + } + return true; + }, + }; +} diff --git a/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts b/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts new file mode 100644 index 0000000000000..386cfe22d4094 --- /dev/null +++ b/packages/core/src/SnapPaging/__tests__/SnapPaging.interaction.browser.spec.ts @@ -0,0 +1,622 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file SnapPaging.interaction.browser.spec.ts + * @input The built Carousel snap-paging stories, real touch and wheel input + * (Chromium CDP / WebKit's injected events) and the interaction harness + * @output Proof that snap paging pages a carousel under a finger and on a + * trackpad swipe under a coarse and a fine primary pointer, on native snap's + * stops and mirrored in RTL. A mouse wheel and a mouse drag keep native + * scrolling. An edge press or Shift+wheel during a settle moves the row on + * from where it shows. A held touch stops that move. Dropping the value + * mid-settle hands the row back + * @position Browser proof for snap paging, run by `pnpm test:interaction` + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + drag, + openStory, + tap, + touchDriver, + webInputDriver, + withStorybook, +} from '@astryxdesign/interaction-harness'; + +import {nearestStop} from '../snapPagingValue'; + +const storybook = withStorybook(test); + +type Mode = 'snap' | 'paging' | 'item'; + +type Story = + | 'snap-paging-one-up' + | 'snap-paging-three-up' + | 'snap-paging-partial-last-page'; + +async function open( + page: Page, + story: Story, + mode: Mode, + {rtl = false}: {rtl?: boolean} = {}, +) { + if (rtl) { + await page.goto( + `${storybook()}/iframe.html?id=core-carousel--${story}&viewMode=story&args=mode:${mode}&globals=direction:rtl`, + ); + await page.getByRole('region').waitFor(); + } else { + await openStory(page, storybook(), `core-carousel--${story}`, {mode}); + } + const scroller = page.getByRole('region').getByRole('group').first(); + return {scroller}; +} + +/** The row's native scroll offset, toward the end in either direction. */ +const offset = async (scroller: Locator) => + scroller.evaluate(el => Math.abs(el.scrollLeft)); + +/** The row's travel: how far it scrolls. */ +const travel = async (scroller: Locator) => + scroller.evaluate(el => el.scrollWidth - el.clientWidth); + +/** Each item's snap stop: its start edge, from the row's start, at rest. */ +const stopsOf = async (scroller: Locator) => + scroller.evaluate(el => { + const rtl = getComputedStyle(el).direction === 'rtl'; + const box = el.getBoundingClientRect(); + const end = el.scrollWidth - el.clientWidth; + return Array.from(el.children).map(child => { + const rect = child.getBoundingClientRect(); + const start = rtl ? box.right - rect.right : rect.left - box.left; + return Math.min(start + Math.abs(el.scrollLeft), end); + }); + }); + +/** Whether any item still carries the paging's translate. */ +const isTakenOver = async (scroller: Locator) => + scroller.evaluate(el => + Array.from(el.children).some( + child => (child as HTMLElement).style.translate !== '', + ), + ); + +/** Waits until the paging hands the row back to native scrolling. */ +async function settled(scroller: Locator) { + await expect.poll(async () => isTakenOver(scroller)).toBe(false); +} + +/** Sets the open story's `mode` arg, as the preview's control does. */ +async function setMode(page: Page, story: Story, mode: Mode) { + await page.evaluate( + ({storyId, updatedArgs}) => { + const channel = ( + window as unknown as { + __STORYBOOK_ADDONS_CHANNEL__: { + emit: (event: string, payload: unknown) => void; + }; + } + ).__STORYBOOK_ADDONS_CHANNEL__; + channel.emit('updateStoryArgs', {storyId, updatedArgs}); + }, + {storyId: `core-carousel--${story}`, updatedArgs: {mode}}, + ); +} + +/** + * A drag toward the end of the row (right to left in LTR) of `px`, over `ms`, + * held still for `restMs` before the lift. + */ +async function swipe( + page: Page, + scroller: Locator, + { + px, + ms, + restMs = 0, + rtl = false, + }: {px: number; ms: number; restMs?: number; rtl?: boolean}, +) { + const box = await scroller.boundingBox(); + if (box == null) { + throw new Error('no scroller'); + } + const y = box.y + box.height / 2; + const half = px / 2; + const from = {x: box.x + box.width / 2 + (rtl ? -half : half), y}; + const to = {x: from.x + (rtl ? px : -px), y}; + const driver = await touchDriver(page); + await driver.play(drag(from, to, {durationMs: ms, restMs})); +} + +for (const mode of ['paging', 'item'] as const) { + test.describe(`under a finger, ${mode === 'paging' ? 'the default (one view)' : '{pages: "item"}'}`, () => { + test('one item per view: a flick moves one item, and the row rests natively there', async ({ + page, + }) => { + const {scroller} = await open(page, 'snap-paging-one-up', mode); + expect(await offset(scroller)).toBe(0); + await swipe(page, scroller, {px: 80, ms: 80}); + await settled(scroller); + await expect.poll(async () => offset(scroller)).toBeCloseTo(300, 0); + }); + + test(`three items per view: a flick moves ${mode === 'paging' ? 'one view, to the item start edge nearest one viewport on' : 'one item'}`, async ({ + page, + }) => { + const {scroller} = await open(page, 'snap-paging-three-up', mode); + const stops = await stopsOf(scroller); + await swipe(page, scroller, {px: 80, ms: 80}); + await settled(scroller); + await expect + .poll(async () => offset(scroller)) + .toBeCloseTo(stops[mode === 'paging' ? 3 : 1], 0); + }); + + test('a partial last page rests where the row ends, with no empty space', async ({ + page, + }) => { + const {scroller} = await open( + page, + 'snap-paging-partial-last-page', + mode, + ); + const end = await travel(scroller); + for (let i = 0; i < 7; i++) { + await swipe(page, scroller, {px: 80, ms: 80}); + await settled(scroller); + } + await expect.poll(async () => offset(scroller)).toBeCloseTo(end, 0); + // The last item's end meets the row's end. + expect( + await scroller.evaluate(el => { + const last = el.lastElementChild as HTMLElement; + return ( + el.getBoundingClientRect().right - + last.getBoundingClientRect().right + ); + }), + ).toBeLessThan(1); + }); + + test('right-to-left: a flick toward the inline end moves forward, mirrored', async ({ + page, + }) => { + const {scroller} = await open(page, 'snap-paging-three-up', mode, { + rtl: true, + }); + const stops = await stopsOf(scroller); + await swipe(page, scroller, {px: 80, ms: 80, rtl: true}); + await settled(scroller); + await expect + .poll(async () => scroller.evaluate(el => el.scrollLeft)) + .toBeCloseTo(-stops[mode === 'paging' ? 3 : 1], 0); + }); + + test('a short flick over 300 pt/s moves a page', async ({page}) => { + const {scroller} = await open(page, 'snap-paging-one-up', mode); + // 40 px in 40 ms: about 1,000 px/s. + await swipe(page, scroller, {px: 40, ms: 40}); + await settled(scroller); + await expect.poll(async () => offset(scroller)).toBeCloseTo(300, 0); + }); + + test('a slow release before half a page stays; past half a page moves', async ({ + page, + }) => { + const {scroller} = await open(page, 'snap-paging-one-up', mode); + // 120 px over 600 ms, held still: under half of the 300 px page. + await swipe(page, scroller, {px: 120, ms: 600, restMs: 200}); + await settled(scroller); + await expect.poll(async () => offset(scroller)).toBe(0); + // 180 px over 600 ms, held still: past half of it. + await swipe(page, scroller, {px: 180, ms: 600, restMs: 200}); + await settled(scroller); + await expect.poll(async () => offset(scroller)).toBeCloseTo(300, 0); + }); + }); +} + +// Chromium's CDP input sends wheels without a trackpad's legacy `wheelDelta`, +// so the gesture engine reads them as a mouse's wheel. The trackpad cases run +// in WebKit, whose injected wheels carry it. +const TRACKPAD_IN_CHROMIUM = + "Chromium's CDP wheels read as a mouse's wheel; the trackpad cases run in WebKit"; + +/** + * Reports a coarse primary pointer to script, before the story loads: a + * tablet with a trackpad, whose wheels a desktop context can inject. + */ +function coarsePrimaryPointer() { + const real = window.matchMedia.bind(window); + window.matchMedia = (query: string) => { + if (!query.includes('pointer: coarse')) { + return real(query); + } + const list: MediaQueryList = { + matches: true, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + }; + return list; + }; +} + +for (const pointer of ['coarse', 'fine'] as const) { + test.describe(`where the primary pointer is ${pointer} and a trackpad scrolls`, () => { + // WebKit's mobile emulation has no wheel input. A desktop context stands + // for a laptop, and with a coarse primary pointer for a tablet with a + // trackpad. + test.use({hasTouch: false, isMobile: false}); + + for (const mode of ['paging', 'item'] as const) { + test(`${mode === 'paging' ? 'the default' : '{pages: "item"}'}: a trackpad swipe pages`, async ({ + page, + browserName, + }) => { + test.skip(browserName === 'chromium', TRACKPAD_IN_CHROMIUM); + if (pointer === 'coarse') { + await page.addInitScript(coarsePrimaryPointer); + } + const {scroller} = await open(page, 'snap-paging-three-up', mode); + const stops = await stopsOf(scroller); + const box = await scroller.boundingBox(); + if (box == null) { + throw new Error('no scroller'); + } + const input = await webInputDriver(page); + // 40 steps of 6.5 px, a trackpad's continuous scroll: 260 px, past half + // of a view. + for (let i = 0; i < 40; i++) { + await input.wheel({ + x: box.x + box.width / 2, + y: box.y + box.height / 2, + dx: 6.5, + }); + } + await settled(scroller); + await expect + .poll(async () => offset(scroller)) + .toBeCloseTo(stops[mode === 'paging' ? 3 : 1], 0); + }); + } + }); +} + +test('the scroll offset holds through a swipe, so the edge fades and buttons stay put, and the settle hands it on', async ({ + page, +}) => { + const {scroller} = await open(page, 'snap-paging-three-up', 'paging'); + const stops = await stopsOf(scroller); + // Natively at the second view first. + await scroller.evaluate((el, left) => { + el.scrollTo({left, behavior: 'instant'}); + }, stops[3]); + await expect.poll(async () => offset(scroller)).toBeCloseTo(stops[3], 0); + 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 + 40, y}; + const to = {x: from.x - 80, y}; + const seen: number[] = []; + const driver = await touchDriver(page); + await driver.play(drag(from, to, {durationMs: 80, restMs: 0}), { + onEvent: async step => { + if (step.type === 'touchMove') { + seen.push(await offset(scroller)); + } + }, + }); + expect(seen.length).toBeGreaterThan(0); + for (const at of seen) { + expect(at).toBeCloseTo(stops[3], 0); + } + await settled(scroller); + await expect.poll(async () => offset(scroller)).toBeCloseTo(stops[6], 0); +}); + +test('an edge button steps about one view: the viewport less half an item, on the nearest stop', async ({ + page, +}) => { + const {scroller} = await open(page, 'snap-paging-three-up', 'paging'); + const stops = await stopsOf(scroller); + const step = await scroller.evaluate( + el => + el.clientWidth - + (el.firstElementChild as HTMLElement).getBoundingClientRect().width / 2, + ); + const nearest = stops.reduce( + (best, stop) => + Math.abs(stop - step) < Math.abs(best - step) ? stop : best, + stops[1], + ); + await page.getByRole('button', {name: /next|right|forward/i}).click(); + await expect + .poll(async () => offset(scroller)) + .toBeCloseTo(Math.max(nearest, stops[1]), 0); + expect(await isTakenOver(scroller)).toBe(false); +}); + +/** + * Flicks the row (toward the start with `back`) and presses the edge button + * once the row shows past `until`; true if it was still held. + */ +async function pressInSettle( + page: Page, + scroller: Locator, + until: number, + back = false, +) { + const next = await page + .getByRole('button', {name: /next|right|forward/i}) + .boundingBox(); + if (next == null) { + throw new Error('no edge button'); + } + await swipe(page, scroller, {px: 80, ms: 80, rtl: back}); + const past = async () => + scroller.evaluate( + (el, arg) => { + const first = el.firstElementChild as HTMLElement; + const shown = + el.getBoundingClientRect().left - first.getBoundingClientRect().left; + const isPast = arg.back ? shown < arg.until : shown >= arg.until; + return first.style.translate === '' || isPast; + }, + {until, back}, + ); + await expect.poll(past, {intervals: [5]}).toBe(true); + const held = await isTakenOver(scroller); + await page.mouse.click(next.x + next.width / 2, next.y + next.height / 2); + return held; +} + +/** The row's offset once two reads a while apart agree. */ +async function restingOffset(scroller: Locator) { + await settled(scroller); + let at = await offset(scroller); + await expect + .poll(async () => { + const before = at; + at = await offset(scroller); + return Math.abs(at - before); + }) + .toBeLessThan(0.5); + return at; +} + +test('an edge press late in a settle steps on to a stop', async ({page}) => { + const {scroller} = await open(page, 'snap-paging-three-up', 'paging'); + const stops = await stopsOf(scroller); + expect(await pressInSettle(page, scroller, stops[3] * 0.9)).toBe(true); + const at = await restingOffset(scroller); + // At least one stop past the flick's own target. + expect(at).toBeGreaterThan(stops[4] - 0.5); + expect(Math.min(...stops.map(stop => Math.abs(stop - at)))).toBeLessThan(1); +}); + +for (const holdMs of [150, 40]) { + test(`during an edge button's move, a ${holdMs} ms touch on the row ${holdMs > 85 ? 'stops it where it shows' : 'lets it run on'}, and the row rests on a stop`, async ({ + page, + }) => { + const {scroller} = await open(page, 'snap-paging-three-up', 'paging'); + const stops = await stopsOf(scroller); + const box = await scroller.boundingBox(); + if (box == null) { + throw new Error('no scroller'); + } + expect(await pressInSettle(page, scroller, stops[3] * 0.9)).toBe(true); + const driver = await touchDriver(page); + await driver.play( + tap({x: box.x + box.width / 2, y: box.y + box.height / 2}, {holdMs}), + ); + const at = await restingOffset(scroller); + expect(Math.min(...stops.map(stop => Math.abs(stop - at)))).toBeLessThan(1); + // Past the pager's 85 ms catch time, the move stops short of its target. + expect(Math.abs(at - stops[5]) < 1).toBe(holdMs < 85); + }); +} + +test.describe('with a finger and a mouse', () => { + test.use({hasTouch: true, isMobile: false}); + + test('Shift+wheel during an edge press goes to a stop', async ({page}) => { + const {scroller} = await open(page, 'snap-paging-three-up', 'paging'); + const stops = await stopsOf(scroller); + expect(await pressInSettle(page, scroller, stops[3] * 0.9)).toBe(true); + // Where the row shows at the wheel, and any native scroll while held. + const probe = scroller.evaluate(async el => { + const first = el.firstElementChild as HTMLElement; + const event = (await new Promise(resolve => { + el.addEventListener('wheel', resolve, {capture: true, once: true}); + })) as WheelEvent; + const shown = + el.getBoundingClientRect().left - first.getBoundingClientRect().left; + const held = el.scrollLeft; + let drift = 0; + while (first.style.translate !== '') { + drift = Math.max(drift, Math.abs(el.scrollLeft - held)); + await new Promise(requestAnimationFrame); + } + return {shown, held, travel: event.deltaX || event.deltaY, drift}; + }); + await scroller.hover(); + await page.keyboard.down('Shift'); + await page.mouse.wheel(0, 900); + await page.keyboard.up('Shift'); + const {shown, held, travel, drift} = await probe; + const expected = nearestStop(stops, shown + travel); + // A native scroll would move the held offset, and the target is neither + // the press's own nor a reversed wheel's. + expect(held + travel).toBeGreaterThan(0.5); + expect(Math.abs(expected - stops[5])).toBeGreaterThan(1); + expect(drift).toBe(0); + expect(await restingOffset(scroller)).toBeCloseTo(expected, 0); + }); +}); + +test('an edge press after a flick back near the end shows no space past the last item', async ({ + page, +}) => { + const {scroller} = await open(page, 'snap-paging-three-up', 'paging'); + const stops = await stopsOf(scroller); + // One stop from the end, where the edge button still shows. + await scroller.evaluate((el, left) => { + el.scrollTo({left, behavior: 'instant'}); + }, stops[5]); + await expect.poll(async () => offset(scroller)).toBeCloseTo(stops[5], 0); + // The widest space past the last item, on every frame until the hand-back. + const space = scroller.evaluate(async el => { + const last = el.lastElementChild as HTMLElement; + const isHeld = () => last.style.translate !== ''; + let widest = 0; + let wasHeld = false; + while (!wasHeld || isHeld()) { + wasHeld ||= isHeld(); + const box = el.getBoundingClientRect(); + widest = Math.max(widest, box.right - last.getBoundingClientRect().right); + await new Promise(requestAnimationFrame); + } + return widest; + }); + // Once the flick back widens the overflow by its translate. + expect(await pressInSettle(page, scroller, stops[5] - 15, true)).toBe(true); + expect(await space).toBeLessThan(1); + const at = await restingOffset(scroller); + expect(Math.min(...stops.map(stop => Math.abs(stop - at)))).toBeLessThan(1); +}); + +test('hasSnap alone attaches no paging: no gesture claims the row', async ({ + page, +}) => { + const paging = await open(page, 'snap-paging-one-up', 'paging'); + // The paging claims the row's horizontal pans under a finger. + expect( + await paging.scroller.evaluate(el => getComputedStyle(el).touchAction), + ).toBe('pan-y pinch-zoom'); + const {scroller} = await open(page, 'snap-paging-one-up', 'snap'); + expect(await scroller.evaluate(el => getComputedStyle(el).touchAction)).toBe( + 'auto', + ); + expect( + await scroller.evaluate(el => getComputedStyle(el).scrollSnapType), + ).toContain('mandatory'); +}); + +test('a new page size applies from the next flick: one item, then one view', async ({ + page, +}) => { + const {scroller} = await open(page, 'snap-paging-three-up', 'item'); + const stops = await stopsOf(scroller); + await swipe(page, scroller, {px: 80, ms: 80}); + await settled(scroller); + await expect.poll(async () => offset(scroller)).toBeCloseTo(stops[1], 0); + await setMode(page, 'snap-paging-three-up', 'paging'); + await swipe(page, scroller, {px: 80, ms: 80}); + await settled(scroller); + await expect.poll(async () => offset(scroller)).toBeCloseTo(stops[4], 0); +}); + +test('dropping the paging value mid-settle hands the row back to native scrolling', async ({ + page, +}) => { + const {scroller} = await open(page, 'snap-paging-three-up', 'paging'); + const stops = await stopsOf(scroller); + await swipe(page, scroller, {px: 80, ms: 80}); + // Mid-settle: the row is still taken over. + expect(await isTakenOver(scroller)).toBe(true); + // The story now passes hasSnap, so Carousel drops the paging value. + await setMode(page, 'snap-paging-three-up', 'snap'); + await expect + .poll(async () => scroller.evaluate(el => getComputedStyle(el).touchAction)) + .toBe('auto'); + // Handed back: no translate, the row at or between its stops, at rest. + expect(await isTakenOver(scroller)).toBe(false); + const at = await offset(scroller); + expect(at).toBeGreaterThanOrEqual(0); + expect(at).toBeLessThanOrEqual(stops[3] + 1); +}); + +test.describe('under a fine primary pointer', () => { + test.use({hasTouch: false, isMobile: false}); + + test('a mouse wheel scrolls the row natively: the paging does not run', async ({ + page, + }) => { + const {scroller} = await open(page, 'snap-paging-one-up', 'paging'); + expect( + await page.evaluate(() => matchMedia('(pointer: coarse)').matches), + ).toBe(false); + const box = await scroller.boundingBox(); + if (box == null) { + throw new Error('no scroller'); + } + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.wheel(400, 0); + await expect.poll(async () => offset(scroller)).toBeGreaterThan(0); + expect(await isTakenOver(scroller)).toBe(false); + }); + + test('a mouse drag leaves the row where it is: only a finger, a pen or a trackpad pages', async ({ + page, + }) => { + const {scroller} = await open(page, 'snap-paging-three-up', 'paging'); + const box = await scroller.boundingBox(); + if (box == null) { + throw new Error('no scroller'); + } + const y = box.y + box.height / 2; + await page.mouse.move(box.x + box.width / 2 + 75, y); + await page.mouse.down(); + for (let i = 1; i <= 10; i++) { + await page.mouse.move(box.x + box.width / 2 + 75 - 15 * i, y); + } + await page.mouse.up(); + expect(await isTakenOver(scroller)).toBe(false); + expect(await offset(scroller)).toBe(0); + }); + + test('hasSnap alone keeps native snapping under a trackpad swipe', async ({ + page, + browserName, + }) => { + test.skip(browserName === 'chromium', TRACKPAD_IN_CHROMIUM); + const {scroller} = await open(page, 'snap-paging-three-up', 'snap'); + const stops = await stopsOf(scroller); + const box = await scroller.boundingBox(); + if (box == null) { + throw new Error('no scroller'); + } + const input = await webInputDriver(page); + let wasTakenOver = false; + for (let i = 0; i < 40; i++) { + await input.wheel({ + x: box.x + box.width / 2, + y: box.y + box.height / 2, + dx: 6.5, + }); + wasTakenOver ||= await isTakenOver(scroller); + } + expect(wasTakenOver).toBe(false); + // Native snap rests on a stop. + await expect + .poll(async () => { + const at = await offset(scroller); + return stops.some(stop => Math.abs(stop - at) < 1); + }) + .toBe(true); + expect(await offset(scroller)).toBeGreaterThan(0); + }); +}); diff --git a/packages/core/src/SnapPaging/index.ts b/packages/core/src/SnapPaging/index.ts new file mode 100644 index 0000000000000..1c6ef28d9c4e3 --- /dev/null +++ b/packages/core/src/SnapPaging/index.ts @@ -0,0 +1,11 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file index.ts + * @input SnapPaging.ts + * @output Snap paging's public exports: `useSnapPaging` and its types + * @position `@astryxdesign/core/SnapPaging`, also exported from the root + */ + +export {useSnapPaging} from './SnapPaging'; +export type {SnapPaging, SnapPagingOptions} from './SnapPaging'; diff --git a/packages/core/src/SnapPaging/snapPagingValue.ts b/packages/core/src/SnapPaging/snapPagingValue.ts new file mode 100644 index 0000000000000..fc895b1463102 --- /dev/null +++ b/packages/core/src/SnapPaging/snapPagingValue.ts @@ -0,0 +1,133 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @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 + * @position Carousel's only link to snap paging. It imports no pager code, + * so a Carousel without `hasSnap={useSnapPaging()}` bundles none + */ + +import {isRtlElement} from '../hooks/isRtlElement'; + +/** Options of `useSnapPaging`. */ +export interface SnapPagingOptions { + /** + * What one flick moves. `'view'`: one view, landing on the item start edge + * nearest one viewport on. `'item'`: one item. + * @default 'view' + */ + readonly pages?: 'view' | 'item'; +} + +declare const snapPagingBrand: unique symbol; + +/** + * Configured snap paging. Make it with `useSnapPaging`, and pass it to + * Carousel's `hasSnap`. + */ +export interface SnapPaging { + readonly [snapPagingBrand]: true; +} + +/** The paging attached to one row. */ +export interface SnapPagingAttachment { + readonly detach: () => void; + readonly moveHeld: (target: (at: number, end: number) => number) => boolean; +} + +interface SnapPagingValue { + readonly attach: (element: HTMLElement) => SnapPagingAttachment; +} + +const values = new WeakSet(); +// Each attached row's paging, for Carousel's own scroll calls. +const attachments = new WeakMap(); + +/** A `SnapPaging` value that attaches with `attach`. */ +export function makeSnapPaging( + attach: (element: HTMLElement) => SnapPagingAttachment, +): SnapPaging { + const value: SnapPagingValue = {attach}; + values.add(value); + return value as unknown as SnapPaging; +} + +/** Whether `value` came from `useSnapPaging`. */ +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. */ +export function attachSnapPaging( + value: SnapPaging, + element: HTMLElement, +): () => void { + const attachment = (value as unknown as SnapPagingValue).attach(element); + attachments.set(element, attachment); + return () => { + attachments.delete(element); + attachment.detach(); + }; +} + +/** + * Moves a row the paging holds to `target(shown, end)`, an offset toward the + * end. `end` is its travel when taken over. False when it is not held. + */ +export function moveHeldSnapPaging( + element: HTMLElement, + target: (shown: number, end: number) => number, +): boolean { + return attachments.get(element)?.moveHeld(target) ?? false; +} + +/** The stop nearest `at`, or `at` itself when the row has no stops. */ +export function nearestStop(stops: ReadonlyArray, at: number): number { + return stops.reduce( + (best, stop) => (Math.abs(stop - at) < Math.abs(best - at) ? stop : best), + stops[0] ?? at, + ); +} + +/** + * 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. + */ +export function snapStops( + element: HTMLElement, + shown: number, + end: number, +): 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 border = rtl + ? element.offsetWidth - element.clientWidth - element.clientLeft + : element.clientLeft; + const style = getComputedStyle(element); + const padding = + Number.parseFloat( + rtl ? style.scrollPaddingRight : style.scrollPaddingLeft, + ) || 0; + const stops: number[] = []; + for (const child of Array.from(element.children)) { + const rect = child.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]; +} diff --git a/packages/core/src/SnapPaging/useSnapPaging.doc.mjs b/packages/core/src/SnapPaging/useSnapPaging.doc.mjs new file mode 100644 index 0000000000000..d02c54c5b6cb7 --- /dev/null +++ b/packages/core/src/SnapPaging/useSnapPaging.doc.mjs @@ -0,0 +1,86 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** @type {import('@astryxdesign/cli/authoring').HookDoc} */ +export const docs = { + name: 'useSnapPaging', + displayName: 'useSnapPaging', + group: 'Carousel', + keywords: ['carousel', 'paging', 'snap', 'swipe', 'flick', 'onboarding'], + params: [ + { + name: 'options', + type: "{pages?: 'view' | 'item'}", + description: + "What one flick moves. 'view' moves one view and lands on the item start edge nearest one viewport on; 'item' moves one item. A new value applies from the next flick.", + default: "{pages: 'view'}", + }, + ], + returns: [ + { + name: 'paging', + type: 'SnapPaging', + description: + "Snap paging for Carousel's hasSnap. The value is the same for the component's life, and Carousel keeps the value it first attached.", + }, + ], + usage: { + description: + "Gives a Carousel iOS paging on native snap's stops: pass the value as hasSnap={useSnapPaging()}. Under a finger and on a trackpad swipe, a flick moves one view, or one item with {pages: 'item'}, and the row rests on an item's start edge. A mouse wheel keeps native snapping. Only a carousel given the value loads the paging code.", + bestPractices: [ + { + guidance: true, + description: + 'Use it for a row read one view at a time, such as onboarding screens or a photo strip, where a fast flick must not skip past the next view.', + }, + { + guidance: true, + description: + "Pass {pages: 'item'} when several items show at once and each flick should move only one of them.", + }, + { + guidance: false, + description: + 'Use it for a row people scan quickly; plain hasSnap keeps native momentum, which can pass several items in one swipe.', + }, + ], + }, + relatedComponents: ['Carousel'], + relatedHooks: [], + importPath: '@astryxdesign/core/SnapPaging', + category: 'motion & gestures', +}; + +/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */ +export const docsDense = { + description: + "iOS paging for Carousel on native snap's stops: hasSnap={useSnapPaging()}. Finger or trackpad swipe: one view per flick ({pages: 'item'}: one item); mouse wheel keeps native snap. Only that carousel loads the pager.", + paramDescriptions: { + options: + "{pages: 'view' | 'item'}: what one flick moves. Default 'view'. A new value applies from the next flick.", + }, + returnDescriptions: { + paging: + "value for Carousel's hasSnap; same for the component's life; Carousel keeps the first value it attached.", + }, + usage: { + description: + "hasSnap={useSnapPaging()}: one view per flick under a finger or trackpad swipe, resting on an item start edge. {pages: 'item'}: one item. Mouse wheel stays native.", + bestPractices: [ + { + guidance: true, + description: + 'Use for rows read one view at a time (onboarding, photo strip).', + }, + { + guidance: true, + description: + "{pages: 'item'} when several items show and a flick should move one.", + }, + { + guidance: false, + description: + 'Use for rows scanned quickly; plain hasSnap keeps native momentum.', + }, + ], + }, +}; diff --git a/packages/core/src/hooks/usePager.test.ts b/packages/core/src/hooks/usePager.test.ts index 506e985b43ede..244b83f9dc0d4 100644 --- a/packages/core/src/hooks/usePager.test.ts +++ b/packages/core/src/hooks/usePager.test.ts @@ -855,6 +855,26 @@ describe('createPager', () => { expect(f.x()).toBe(-2 * WIDTH); }); + it('goTo with an offset ends there as a settle, and a still finger that catches it settles on the nearest page', async () => { + const f = setup({defaultIndex: 0}); + f.pager.goTo(2, {offset: 2.4 * WIDTH}); + await advance(0, f.clock); + const curve = solveAnimatedPageScroll({from: 0, to: 2.4 * WIDTH}); + await advance(150, f.clock); + expect(-f.x()).toBeCloseTo(curve.at(0.15), 0); + await settle(f); + expect(-f.x()).toBeCloseTo(2.4 * WIDTH, 0); + expect(f.calls).toEqual(['index:2:goTo', 'settle:2:0']); + f.pager.goTo(4, {offset: 3.6 * WIDTH}); + await advance(60, f.clock); + touch('touchstart', f.page, 300, 100, now); + await advance(paging.catchStopMs + 40, f.clock); + expect(f.pager.isSettling).toBe(false); + touch('touchend', f.page, 300, 100, now); + await settle(f); + expect(-f.x() / WIDTH).toBe(Math.round(-f.x() / WIDTH)); + }); + it('loops: past the last page goes forward to a virtual page, wrapped for callbacks', async () => { const f = setup({defaultIndex: 4, loop: true}); await drag(f, {from: 300, dx: -250, hold: 50}); diff --git a/packages/core/src/hooks/usePager.ts b/packages/core/src/hooks/usePager.ts index f3d360bb73748..f638c56bf8733 100644 --- a/packages/core/src/hooks/usePager.ts +++ b/packages/core/src/hooks/usePager.ts @@ -166,6 +166,12 @@ export interface PagerOptions { * @default 'viewport' */ pages?: 'viewport' | 'children'; + /** + * With `pages: 'children'`: the pages, measured by the owner in place of + * the children's rects. Snap paging moves the children themselves, so it + * reads their stops from layout. + */ + measurePages?: () => ReadonlyArray; /** Starting page. @default 0 */ defaultIndex?: number; /** @@ -202,6 +208,12 @@ export interface GoToOptions { animated?: boolean; /** @default 'goTo' */ reason?: PagerChangeReason; + /** + * The content offset (px) the move ends at, in place of the page's own. + * The page stays the target: a finger that catches the move settles on the + * nearest page. + */ + offset?: number; } export interface Pager { @@ -290,12 +302,18 @@ function toTrackCurve(curve: MotionCurve, sign: number): MotionCurve { }; } +/** The animator calls a pager makes on its track. */ +export type PagerAnimator = Pick< + Animator, + 'get' | 'getVelocity' | 'set' | 'play' | 'stop' +>; + /** What a pager runs on; tests pass their own clocked host and animator. */ export interface PagerEnvironment { /** The gesture host; the document's shared host by default. */ host?: GestureHost; /** The track's animator; `animatorFor(track)` by default. */ - animator?: Animator; + animator?: PagerAnimator; /** Timers for the catch delay; the viewport's window's by default. */ setTimeout?: (callback: () => void, ms: number) => unknown; clearTimeout?: (handle: unknown) => void; @@ -484,7 +502,7 @@ export function createPager( let options: PagerOptions = {...initial}; let viewport: HTMLElement | null = null; let trackElement: HTMLElement | null = null; - let animator: Animator | null = null; + let animator: PagerAnimator | null = null; let pageWidth = 0; let isRtl = false; // With `pages: 'children'`, each page's offset (px, ascending), once @@ -576,6 +594,10 @@ export function createPager( * scale: the rect's width over the track's used width. */ function measureChildOffsets(): ReadonlyArray { + if (options.measurePages != null) { + const measured = options.measurePages(); + return measured.length > 0 ? measured : [0]; + } const track = trackElement; if (viewport == null || track == null || track.children.length === 0) { return [0]; @@ -1094,7 +1116,7 @@ export function createPager( deferringCallbacks(() => goTo(index, goToOptions)); return; } - const {animated = true, reason = 'goTo'} = goToOptions; + const {animated = true, reason = 'goTo', offset} = goToOptions; let next = Math.round(index); if (isLooping()) { next = nearestLoopCopy(next, target, count()); @@ -1117,7 +1139,7 @@ export function createPager( } stopSettle(); setTarget(next, reason); - const to = offsetOf(next); + const to = offset ?? offsetOf(next); if (!animated || animator == null || from === to) { animator?.set({x: positionToX(to)}); rest(); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 0453e52c27a82..f3326ae9a3f74 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -30,6 +30,7 @@ export * from './IconButton'; export * from './Card'; export * from './ClickableCard'; export * from './Carousel'; +export * from './SnapPaging'; export * from './Calendar'; export * from './Center'; export * from './CodeBlock'; diff --git a/scripts/snap-paging-bundle.test.mjs b/scripts/snap-paging-bundle.test.mjs new file mode 100644 index 0000000000000..6187b08061406 --- /dev/null +++ b/scripts/snap-paging-bundle.test.mjs @@ -0,0 +1,124 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file snap-paging-bundle.test.mjs + * @input Core's source, bundled with the PR size report's esbuild options + * @output Proves snap paging's module boundary. Carousel alone bundles no + * pager code, and Carousel with `useSnapPaging` does. Importing the + * snap-paging module does no DOM work + * @position Node test over source, so it needs no build + */ + +import fs from 'node:fs'; +import {createRequire} from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import {afterAll, describe, expect, it} from 'vitest'; + +const REPO = path.resolve(import.meta.dirname, '..'); +const CORE_SRC = path.join(REPO, 'packages/core/src'); +const require = createRequire(path.join(REPO, 'package.json')); +const esbuild = require('esbuild'); + +/** + * The pager and the code only it runs on: its gestures, its settle's motion, + * and the gesture support beside them. Carousel's own parts carry other + * motion, such as a button's press, which is not the pager's. + */ +const PAGER_CODE = new RegExp( + `^packages/core/src/(${[ + 'hooks/usePager\\.ts', + 'SnapPaging/SnapPaging\\.ts', + 'gestures/', + 'motion/(animator|paging|presentation|projection|reducedMotionPlan|resolveMotion|resolveSnapPoint|roleValue|rubberBand|spring|themeTempo)\\.ts', + 'motion/uikit/(gestures|paging|scroll)\\.ts', + 'Layer/inputHold\\.ts', + 'utils/(clickGuard|isApplePlatform|primaryClick|selectionLock)\\.ts', + 'privateAttributes/(hapticSwitch|reducedMotion)\\.stylex\\.ts', + ].join('|')})`, +); + +const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-snap-paging-')); +afterAll(() => { + fs.rmSync(scratch, {recursive: true, force: true}); +}); + +/** + * The modules that put bytes in one import, built as the size report builds + * a component import. + */ +function modules(name, source) { + const entry = path.join(scratch, `${name}.mjs`); + fs.writeFileSync(entry, source); + const result = esbuild.buildSync({ + absWorkingDir: REPO, + entryPoints: [entry], + outdir: path.join(scratch, 'out'), + bundle: true, + minify: true, + format: 'esm', + platform: 'browser', + define: {'process.env.NODE_ENV': '"production"'}, + loader: {'.css': 'empty'}, + external: [ + 'react', + 'react/*', + 'react-dom', + 'react-dom/*', + '@stylexjs/stylex', + ], + metafile: true, + write: false, + logLevel: 'silent', + }); + const [output] = Object.values(result.metafile.outputs); + return Object.entries(output.inputs) + .filter(([, {bytesInOutput}]) => bytesInOutput > 0) + .map(([input]) => input); +} + +/** The pager code in one import. */ +function build(name, source) { + return modules(name, source).filter(input => PAGER_CODE.test(input)); +} + +const from = file => JSON.stringify(path.join(CORE_SRC, file)); + +describe('snap paging bundle', () => { + it('Carousel alone bundles no pager code', () => { + expect( + build('carousel', `export {Carousel} from ${from('Carousel/index.ts')};`), + ).toEqual([]); + }); + + it('Carousel with useSnapPaging bundles the pager', () => { + const pager = build( + 'carousel-paging', + `export {Carousel} from ${from('Carousel/index.ts')}; +export {useSnapPaging} from ${from('SnapPaging/index.ts')};`, + ); + expect(pager).toContain('packages/core/src/hooks/usePager.ts'); + }); + + it('lists every module the hook adds over Carousel alone as pager code', () => { + const carousel = new Set( + modules( + 'carousel-only', + `export {Carousel} from ${from('Carousel/index.ts')};`, + ), + ); + const added = modules( + 'carousel-hook', + `export {Carousel} from ${from('Carousel/index.ts')}; +export {useSnapPaging} from ${from('SnapPaging/index.ts')};`, + ).filter(input => !carousel.has(input)); + expect(added).toContain('packages/core/src/hooks/usePager.ts'); + expect(added.filter(input => !PAGER_CODE.test(input))).toEqual([]); + }); + + it('imports with no DOM: a server import does no DOM work', async () => { + expect(typeof globalThis.document).toBe('undefined'); + const module = await import('../packages/core/src/SnapPaging/index.ts'); + expect(Object.keys(module)).toEqual(['useSnapPaging']); + }); +}); diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs index e75b5fe77dbc1..8617cce829ea9 100644 --- a/scripts/touch-support-bundle.test.mjs +++ b/scripts/touch-support-bundle.test.mjs @@ -239,6 +239,9 @@ const GESTURE_USERS = new Set([ 'hooks: usePanGesture', // The snap-point drag, which moves an element on that pan. 'hooks: useDragToSnapPoints', + // Snap paging: the pager, under a finger and on a trackpad swipe. Carousel + // imports none of it. + 'SnapPaging', ]); /** Public imports that carry no gesture code, whatever the list above says. */