An open source design system that's fully customizable and agent ready
TypeScript
feat(Slider): every pointer drags a thumb by its travel, as UISlider does (#8190)
Christopher Chedeau723e045390c4
diff --git a/.changeset/slider-every-pointer-tracking.md b/.changeset/slider-every-pointer-tracking.mdnew file mode 100644index 0000000000..6d3a42b7d3--- /dev/null+++ b/.changeset/slider-every-pointer-tracking.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Slider: every pointer drags a thumb by its travel, as UISlider does. A press on a thumb no longer jumps the value to the pointer: once the pointer has moved 10 px, the value follows its further travel along the track. A finger or a pen claims the drag only along the track, so a swipe across the slider scrolls the page; a mouse claims in any direction. On a touch screen each thumb takes a finger or a pen through a 48 px target, capped at half the gap to a range's other thumb, and the held thumb lifts. After a finger's flick the thumb coasts on UISlider's measured spring for about 0.6 s, `onChange` firing through the coast, and `onChangeEnd` reports the value once it settles; a slow drag, a mouse drag and a pen drag end at the release. A tap on the track sets the value when the finger lifts, and a mouse click where it lands; a right click and a macOS ctrl-click change nothing. Under reduced motion the thumb does not lift and a tap's value applies at once.+@vjeuxdiff --git a/apps/storybook/stories/Slider.stories.tsx b/apps/storybook/stories/Slider.stories.tsxindex c9d78bf625..2b5e3b6403 100644--- a/apps/storybook/stories/Slider.stories.tsx+++ b/apps/storybook/stories/Slider.stories.tsx@@ -306,3 +306,89 @@ export const PressedState: Story = {);},};++export const TouchTracking: Story = {+ name: 'Touch tracking',+ parameters: {+ docs: {+ description: {+ story:+ 'Under a finger only the thumb takes a drag, through a touch target larger than it; a swipe from the track scrolls the page, and a tap on the track sets the value when the finger lifts. The value follows the finger’s travel past a 10 px start threshold, so the thumb never jumps to the finger, and a release coasts on before `onChangeEnd` reports the value.',+ },+ },+ },+ render: args => {+ const [value, setValue] = useState(30);+ const [range, setRange] = useState<[number, number]>([40, 40]);+ const [ends, setEnds] = useState<string[]>([]);+ const logEnd = (label: string) => (next: number | [number, number]) =>+ setEnds(previous => [+ ...previous.slice(-4),+ `${label} ${Array.isArray(next) ? next.join('–') : next}`,+ ]);+ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: 24}}>+ <Slider+ label="Brightness"+ value={value}+ onChange={setValue}+ onChangeEnd={logEnd('Brightness')}+ valueDisplay="text"+ max={args.max == null ? undefined : Number(args.max)}+ />+ <Slider+ label="Hours"+ value={range}+ onChange={setRange}+ onChangeEnd={logEnd('Hours')}+ valueDisplay="text"+ />+ <output data-testid="slider-change-end" aria-live="polite">+ {ends.length === 0 ? 'No change committed yet' : ends.join(', ')}+ </output>+ </div>+ );+ },+};++export const InScrollingList: Story = {+ name: 'In a scrolling list',+ parameters: {+ docs: {+ description: {+ story:+ 'Sliders in a scrolling list: a vertical swipe that starts on a thumb scrolls the list, a horizontal one drags the thumb, and inside the scroller the thumb lifts only after the content touch delay.',+ },+ },+ },+ render: () => {+ const [values, setValues] = useState(() =>+ Array.from({length: 12}, (_, index) => (index * 37) % 100),+ );+ return (+ <div+ data-testid="slider-list"+ style={{+ height: 360,+ overflowY: 'auto',+ display: 'flex',+ flexDirection: 'column',+ gap: 20,+ padding: 16,+ }}>+ {values.map((value, index) => (+ <Slider+ key={index}+ label={`Channel ${index + 1}`}+ value={value}+ onChange={(next: number) =>+ setValues(previous =>+ previous.map((current, i) => (i === index ? next : current)),+ )+ }+ />+ ))}+ </div>+ );+ },+};diff --git a/docs/specs/AST-094-touch-presentations/motion-roles.md b/docs/specs/AST-094-touch-presentations/motion-roles.mdindex 3aa6b3bbad..3d10cc9a9e 100644--- a/docs/specs/AST-094-touch-presentations/motion-roles.md+++ b/docs/specs/AST-094-touch-presentations/motion-roles.md@@ -16,6 +16,9 @@ Every motion role a registered table lists (`spec:AST-094` FR4, DEC-5): its kind| `springs.menuOpen` | spring | response 0.32 s, damping ratio 0.8 | `spec:AST-094` FR4 || `springs.quickChange` | spring | duration 0.5 s, bounce 0.15 | `spec:AST-094` FR4 || `springs.settle` | spring | duration 0.5 s, bounce 0 | `spec:AST-094` FR4 |+| `springs.sliderDrop` | spring | response 0.5 s, damping ratio 0.7 | `component:Slider` |+| `springs.sliderLift` | spring | response 0.215 s, damping ratio 0.6 | `component:Slider` |+| `springs.sliderRelease` | spring | response 0.4 s, damping ratio 1 | `component:Slider` || `springs.stateChange` | spring | response 0.55 s, damping ratio 1 | `spec:AST-094` FR4 || `springs.subMenuBack` | spring | response 0.4 s, damping ratio 1 | `spec:AST-094` FR4 || `springs.subMenuOpen` | spring | response 0.4 s, damping ratio 0.85 | `spec:AST-094` FR4 |diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.mdindex 830b769fac..c8b32b00a0 100644--- a/docs/specs/AST-094-touch-presentations/spec.md+++ b/docs/specs/AST-094-touch-presentations/spec.md@@ -23,6 +23,14 @@ affects_consumer_docs: []# Touch presentations feel native system spec+<!-- path-applicability:v1 -->++```json+{+ "paths": ["packages/core/src/motion/uikit/slider.ts"]+}+```+## IntentA person using an Astryx product on a phone or tablet gets controls, sheets,diff --git a/docs/specs/components/Slider/Slider.spec.md b/docs/specs/components/Slider/Slider.spec.mdindex d574648ea4..6c1da6ce42 100644--- a/docs/specs/components/Slider/Slider.spec.md+++ b/docs/specs/components/Slider/Slider.spec.md@@ -22,7 +22,19 @@ design_specs: [design:reduced-motion, design:user-states]architecture:[architecture:component-theming-surface, architecture:public-component-api]contributing: []-system_specs: [spec:AST-017, spec:AST-020, spec:AST-085, spec:AST-094]+system_specs:+ [+ spec:AST-017,+ spec:AST-017/FR60,+ spec:AST-020,+ spec:AST-020/FR9,+ spec:AST-085,+ spec:AST-094,+ spec:AST-094/FR9,+ spec:AST-094/FR41,+ spec:AST-094/FR42,+ spec:AST-094/FR43,+ ]---# Slider component contract@@ -56,10 +68,6 @@ an additive target for the interactive control surface.moves is when a touch flick's `onChangeEnd` fires, about 0.6 s after thelift, once the coast settles; an owner that acts at the release keeps doingso through `onChangeEnd` and receives it after the coast.-- Implementation gap: FR7 is not shipped. Every pointer still moves the- thumb's center to the pointer on press, a finger has no 48 px target, lift,- or coast, `onChangeEnd` fires at the release, and the `springs.sliderRelease`- motion role is not yet in the motion role table.- Controlled/uncontrolled behavior: unchanged; Slider remains controlled- Migration decision: an owner that moves `value` only from `onChangeEnd`moves it from `onChange` instead (FR5); an owner that needs the value at a@@ -96,15 +104,15 @@ modes, states, and usage remain documented in `Slider.doc.mjs`.## Behavioral and layout contract-| ID | Candidate invariant | Basis | Review state |-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- |-| FR1 | The current render places a filled range, one or two thumbs, and optional tick marks over the background track. | Current source, docs, and focused tests | Verified current behavior; no new behavior decided |-| FR2 | `Slider`, `Interactive control`, `Track`, and `Thumb` carry the `slider`, `slider-control`, `slider-track`, and `slider-thumb` targets respectively. | Current source, public docs, and DEC-1 | Approved additive target contract |-| FR3 | Filled range, tick marks, mark labels, and adjacent text value display are stable rendered parts without their own current Slider target. | Current source and public docs | Verified current asymmetry; not ratified as policy |-| FR4 | Label and status presentation continue to use Field and FieldStatus; value tooltips continue to use Tooltip. | Current source and focused tests | Verified composition boundary |-| FR5 | `onChangeEnd` fires once when an interaction ends — a pointer drag or track press is released or cancelled (after a finger's release, once its coast settles; FR7), or a keyboard step (arrow, Page, Home, End) completes — and carries the value the owner renders after its synchronous response to that interaction's `onChange` calls, including any clamp, snap, or rejection; it never carries a value Slider emitted that the owner did not render. A range reports both values the same way. | Maintainer decision (DEC-3) | Approved |-| FR6 | When both thumbs of a range share a value, a pointer press takes the thumb that can travel toward the pointer: a press on the track beside them takes the thumb on its side, and a press on the thumbs or on their shared value, such as its mark label, moves neither until the pointer moves, when the direction of that first movement picks the thumb, which takes the drag's focus, pressed state and value tooltip. Until then the upper thumb, drawn over the lower one, holds the press, its focus and its pressed state, so a press that never moves changes no value and leaves focus on the upper thumb. A drag that began on the shared thumbs and comes back past their value moves the other thumb: the dragged thumb stops against it and the other follows the pointer, so with both at 80 a drag to 95 and back to 50 ends at [50, 80]. | Current source and focused tests | Accepted contract |-| FR7 | Every pointer — a finger, a pen, or a mouse — drags a thumb by its travel. A press on a thumb changes no value. Once the pointer has moved `spec:AST-094/FR19`'s 10 px from where it pressed — a distance the pointer travels, not a zone around the thumb — the value moves by the pointer's further travel along the track over the track's length, from wherever the thumb was grabbed, so the thumb never jumps to the pointer; each move is written to the thumb with no component render (`spec:AST-094/FR9`). Between coincident range thumbs, FR6's first movement is the one that crosses the 10 px. A finger or a pen claims the drag only along the track, so a swipe across it scrolls the page; a mouse claims in any direction. Under a coarse primary pointer, after hydration (`spec:AST-094/FR13`), each thumb takes a finger or a pen through a 48 px touch target that grows toward a range's other thumb only to half the gap (`spec:AST-094/FR42`), and the held thumb lifts. After a finger lifts, the thumb coasts toward 0.4 of the release's momentum projection and settles on the `springs.sliderRelease` motion role, about 0.6 s, with `onChange` firing through the coast; the role is internal, with UISlider's measured value at `tempo` 1 and `'standard'`, and follows the theme's motion knobs (`spec:AST-094/FR4`). A mouse's or a pen's drag ends at its release, with no coast. A tap or a click on the track still sets the value: a finger's tap when it lifts, and a mouse press at once, where a primary click lands; a secondary click and a wheel or trackpad scroll change nothing (`spec:AST-094/FR43`). Under reduced motion the thumb does not lift, a tap's value applies at once, and the coast continues (`design:reduced-motion/DR2`). Implementation gap: not shipped yet (Compatibility and migration). | UIKit measurements and maintainer decision (DEC-4) | Approved |+| ID | Candidate invariant | Basis | Review state |+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- |+| FR1 | The current render places a filled range, one or two thumbs, and optional tick marks over the background track. | Current source, docs, and focused tests | Verified current behavior; no new behavior decided |+| FR2 | `Slider`, `Interactive control`, `Track`, and `Thumb` carry the `slider`, `slider-control`, `slider-track`, and `slider-thumb` targets respectively. | Current source, public docs, and DEC-1 | Approved additive target contract |+| FR3 | Filled range, tick marks, mark labels, and adjacent text value display are stable rendered parts without their own current Slider target. | Current source and public docs | Verified current asymmetry; not ratified as policy |+| FR4 | Label and status presentation continue to use Field and FieldStatus; value tooltips continue to use Tooltip. | Current source and focused tests | Verified composition boundary |+| FR5 | `onChangeEnd` fires once when an interaction ends — a pointer drag or track press is released or cancelled (after a finger's release, once its coast settles; FR7), or a keyboard step (arrow, Page, Home, End) completes — and carries the value the owner renders after its synchronous response to that interaction's `onChange` calls, including any clamp, snap, or rejection; it never carries a value Slider emitted that the owner did not render. A range reports both values the same way. | Maintainer decision (DEC-3) | Approved |+| FR6 | When both thumbs of a range share a value, a pointer press takes the thumb that can travel toward the pointer: a press on the track beside them takes the thumb on its side, and a press on the thumbs or on their shared value, such as its mark label, moves neither until the pointer moves, when the direction of that first movement picks the thumb, which takes the drag's focus, pressed state and value tooltip. Until then the upper thumb, drawn over the lower one, holds the press, its focus and its pressed state, so a press that never moves changes no value and leaves focus on the upper thumb. A drag that began on the shared thumbs and comes back past their value moves the other thumb: the dragged thumb stops against it and the other follows the pointer, so with both at 80 a drag to 95 and back to 50 ends at [50, 80]. | Current source and focused tests | Accepted contract |+| FR7 | Every pointer — a finger, a pen, or a mouse — drags a thumb by its travel. A press on a thumb changes no value. Once the pointer has moved `spec:AST-094/FR19`'s 10 px from where it pressed — a distance the pointer travels, not a zone around the thumb — the value moves by the pointer's further travel along the track over the track's length, from wherever the thumb was grabbed, so the thumb never jumps to the pointer; each move is written to the thumb with no component render (`spec:AST-094/FR9`). Between coincident range thumbs, FR6's first movement is the one that crosses the 10 px. A finger or a pen claims the drag only along the track, so a swipe across it scrolls the page; a mouse claims in any direction. Under a coarse primary pointer, after hydration (`spec:AST-094/FR13`), each thumb takes a finger or a pen through a 48 px touch target that grows toward a range's other thumb only to half the gap (`spec:AST-094/FR42`), and the held thumb lifts on the `springs.sliderLift` motion role and drops back on `springs.sliderDrop`. A finger's or a pen's drag that brings the value to either end plays UISlider's end haptic where the browser can vibrate, and a mouse's drag plays none; iOS Safari has no haptic for that moment (`spec:AST-094/FR23`). After a finger lifts, the thumb coasts toward 0.4 of the release's momentum projection and settles on the `springs.sliderRelease` motion role, about 0.6 s, with `onChange` firing through the coast; the three roles are internal, each with UISlider's measured value at `tempo` 1 and `'standard'`, and follow the theme's motion knobs (`spec:AST-094/FR4`). A mouse's or a pen's drag ends at its release, with no coast. A tap or a click on the track still sets the value: a finger's tap when it lifts, and a mouse press at once, where a primary click lands; a secondary click and a wheel or trackpad scroll change nothing (`spec:AST-094/FR43`). Under reduced motion the thumb does not lift, a tap's value applies at once, and the coast continues (`design:reduced-motion/DR2`). | UIKit measurements and maintainer decision (DEC-4) | Approved |### Observed current target asymmetry@@ -255,7 +263,7 @@ separately listed value tooltip retains Tooltip's target.| FR4 | Source inspection; focused tests cover label, status, and disabled-reason Tooltip only | Label, status, value tooltip, disabled reason | Shared composition or its accessible association disappears; value-tooltip composition still lacks focused coverage. | `audit:Slider/anatomy` || FR5 | Pending: `Slider.test.tsx` change-end cases driven by an owner that renders, clamps, or rejects the emitted value (not yet in the suite) | Single and range; pointer release before and after the owner re-renders; each keyboard step | `onChangeEnd` reports a value the owner did not render, fires more than once per interaction, or skips a completed keyboard step | `audit:Slider/accessibility` || FR6 | `Slider.test.tsx` coincident range thumbs cases | Both thumbs at the minimum, the maximum and mid-range; a track press on each side; a press on the thumbs moved either way; a press that never moves, on the thumbs and on the mark label of their value; a drag that passes back over the shared value; right to left | A press or drag on coincident thumbs moves neither thumb, moves the thumb that cannot travel toward the pointer, keeps its focus, pressed state or tooltip on a thumb the drag has left, or leaves a press that never moves on the lower thumb | `audit:Slider/anatomy` |-| FR7 | Pending: touch and fine-pointer browser tests in Chromium and WebKit (not yet in the suite) | Drag, threshold, grab offset, coast, slow release, track tap and swipe, mouse click, secondary click, wheel, close range thumbs, vertical, right to left, reduced motion | The thumb jumps to the pointer, a press moves the value, a swipe across is trapped, a drag waits on the owner's render, a mouse or pen release coasts, or `onChangeEnd` fires before a finger's coast stops | `audit:Slider/anatomy` |+| FR7 | `Slider.test.tsx`, `useSliderTouch.test.tsx`, and the touch and fine-pointer browser tests (`SliderTouch.interaction.browser.spec.ts`, `SliderFinePointer.interaction.browser.spec.ts`) in Chromium and WebKit | Drag, threshold, grab offset, coast, slow release, track tap and swipe, mouse click, secondary click, wheel, close range thumbs, vertical, right to left, reduced motion | The thumb jumps to the pointer, a press moves the value, a swipe across is trapped, a drag waits on the owner's render, a mouse or pen release coasts, or `onChangeEnd` fires before a finger's coast stops | `audit:Slider/anatomy` || Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and four current local targets | Missing, extra, prefixed, stale, or unclaimed mappings fail repository validation. | `audit:Slider/theming` |The focused Slider suite asserts the `slider-control` target's orientation anddiff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.jsonindex 1f74c6d75a..546a134e7c 100644--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json@@ -2221,8 +2221,6 @@"DR4","FR34","FR34",- "FR4",- "FR4","FR8","INV6","architecture:component-style-authoring",@@ -2232,8 +2230,6 @@"spec quote","spec:AST-094","spec:AST-094",- "spec:AST-094",- "spec:AST-094","spec:AST-094"],"packages/core/src/motion/uikit/timing.ts": [diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json b/packages/cli/test/__golden__/no-icon-set/search-icon-set.jsonindex 1fd75d8e92..6bf726fd1b 100644--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json@@ -3,7 +3,7 @@"type": "search","data": {"query": "icon set",- "matchCount": 373,+ "matchCount": 374,"results": [{"domain": "doc",diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txtindex 8267e31717..e51ca61ba7 100644--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt@@ -1,4 +1,4 @@-Results for "icon set" (20 of 373)+Results for "icon set" (20 of 374)name: authoring/building-blocks/templates/build-the-template/template-assets/template-iconssection: use-astryx-icondomain: docdiff --git a/packages/core/src/Slider/Slider.doc.mjs b/packages/core/src/Slider/Slider.doc.mjsindex 13c251385c..332e8a7472 100644--- a/packages/core/src/Slider/Slider.doc.mjs+++ b/packages/core/src/Slider/Slider.doc.mjs@@ -237,12 +237,14 @@ export const docs = {{name: 'containerClassName',type: 'string',- description: 'Class name for the field container. Same targeting as `containerXstyle`.',+ description:+ 'Class name for the field container. Same targeting as `containerXstyle`.',},{name: 'containerStyle',type: 'CSSProperties',- description: 'Inline styles for the field container. Same targeting as `containerXstyle`.',+ description:+ 'Inline styles for the field container. Same targeting as `containerXstyle`.',},{name: 'controlXstyle',@@ -295,7 +297,7 @@ export const docs = {],anatomy,description:- 'A draggable control for selecting a numeric value or range within defined bounds. Supports single value and range selection, tick marks, custom value formatting, and vertical orientation. Use it when users need to explore a continuous range, such as volume, price, or percentage.',+ 'A draggable control for selecting a numeric value or range within defined bounds. Supports single value and range selection, tick marks, custom value formatting, and vertical orientation. Use it when users need to explore a continuous range, such as volume, price, or percentage. Under a finger, on any touch device, it tracks as UISlider does: only the thumb takes a drag, through a target larger than it, the value follows the finger’s travel rather than jumping to it, a release coasts on before `onChangeEnd`, a swipe from the track scrolls the page, and a tap on the track or a mark sets the value when the finger lifts (the thumb springs there). A mouse drag on a thumb tracks the same way, past the same 10 px in any direction, with no lift or coast; a mouse press on the track moves the thumb there, and only a primary click presses. A pen drags as a finger does, claiming only along the track, and its drag ends at the release with no coast. A wheel or a trackpad scroll over the slider goes to whatever scrolls under it.',bestPractices: [{guidance: true,@@ -508,7 +510,7 @@ export const docsZh = {usage: {anatomy,description:- 'A draggable control for selecting a numeric value or range within defined bounds. Supports single value and range selection, tick marks, custom value formatting, and vertical orientation. Use it when users need to explore a continuous range, such as volume, price, or percentage.',+ 'A draggable control for selecting a numeric value or range within defined bounds. Supports single value and range selection, tick marks, custom value formatting, and vertical orientation. Use it when users need to explore a continuous range, such as volume, price, or percentage. Under a finger, on any touch device, it tracks as UISlider does: only the thumb takes a drag, through a target larger than it, the value follows the finger’s travel rather than jumping to it, a release coasts on before `onChangeEnd`, a swipe from the track scrolls the page, and a tap on the track or a mark sets the value when the finger lifts (the thumb springs there). A mouse drag on a thumb tracks the same way, past the same 10 px in any direction, with no lift or coast; a mouse press on the track moves the thumb there, and only a primary click presses. A pen drags as a finger does, claiming only along the track, and its drag ends at the release with no coast. A wheel or a trackpad scroll over the slider goes to whatever scrolls under it.',bestPractices: [{guidance: true,@@ -544,7 +546,7 @@ export const docsDense = {usage: {anatomy,description:- 'A draggable control for selecting a numeric value or range within defined bounds. Supports single value and range selection, tick marks, custom value formatting, and vertical orientation. Use it when users need to explore a continuous range, such as volume, price, or percentage.',+ 'A draggable control for selecting a numeric value or range within defined bounds. Supports single value and range selection, tick marks, custom value formatting, and vertical orientation. Use it when users need to explore a continuous range, such as volume, price, or percentage. Under a finger, on any touch device, it tracks as UISlider does: only the thumb takes a drag, through a target larger than it, the value follows the finger’s travel rather than jumping to it, a release coasts on before `onChangeEnd`, a swipe from the track scrolls the page, and a tap on the track or a mark sets the value when the finger lifts (the thumb springs there). A mouse drag on a thumb tracks the same way, past the same 10 px in any direction, with no lift or coast; a mouse press on the track moves the thumb there, and only a primary click presses. A pen drags as a finger does, claiming only along the track, and its drag ends at the release with no coast. A wheel or a trackpad scroll over the slider goes to whatever scrolls under it.',bestPractices: [{guidance: true,@@ -574,10 +576,12 @@ export const docsDense = {],},propDescriptions: {- containerXstyle: 'StyleX styles for the field container; no effect in InputGroup or horizontal-labels FormLayout. No root xstyle/className/style.',+ containerXstyle:+ 'StyleX styles for the field container; no effect in InputGroup or horizontal-labels FormLayout. No root xstyle/className/style.',containerClassName: 'Class name for the field container.',containerStyle: 'Inline styles for the field container.',- controlXstyle: 'StyleX styles for the visual control box (border, background, icons); not the native input.',+ controlXstyle:+ 'StyleX styles for the visual control box (border, background, icons); not the native input.',controlClassName: 'Class name for the visual control box.',controlStyle: 'Inline styles for the visual control box.',label: 'Label text (always rendered for a11y).',diff --git a/packages/core/src/Slider/Slider.test.tsx b/packages/core/src/Slider/Slider.test.tsxindex 7f46053fb4..c8bf725868 100644--- a/packages/core/src/Slider/Slider.test.tsx+++ b/packages/core/src/Slider/Slider.test.tsx@@ -60,6 +60,15 @@ beforeEach(() => {};});+/** A thumb's control (the track container), where the pointer handlers live. */+function controlOf(thumb: HTMLElement): HTMLElement {+ const control = thumb.closest<HTMLElement>('.astryx-slider-control');+ if (control == null) {+ throw new Error('no slider control');+ }+ return control;+}+describe('Slider', () => {// --- Aria labels ---@@ -110,44 +119,38 @@ describe('Slider', () => {expect(slider).toHaveAttribute('aria-valuenow', '72');});+ // The thumb and the fill are placed by their progress along the travel,+ // written inline as custom properties. CSS turns it into a translate in+ // the control's container units. jsdom computes neither, so a real browser+ // checks the geometry itself.+ const progressOf = (element: HTMLElement, name = '--_slider-progress') =>+ element.style.getPropertyValue(name);+it.each([- {value: 150, expectedValue: 100, expectedPosition: 'calc(100% - 10px)'},- {value: -50, expectedValue: 0, expectedPosition: 'calc(0% + 10px)'},+ {value: 150, expectedValue: 100, expectedProgress: '1'},+ {value: -50, expectedValue: 0, expectedProgress: '0'},])('clamps a controlled value of $value to $expectedValue',- ({value, expectedValue, expectedPosition}) => {+ ({value, expectedValue, expectedProgress}) => {render(<Slider label="Volume" value={value} min={0} max={100} />);const slider = screen.getByRole('slider');expect(slider).toHaveAttribute('aria-valuenow', String(expectedValue));- // Thumb positions via the logical `inset-inline-start` so it mirrors- // under RTL (see RTL Phase 4), offset by half a thumb so the extremes- // stay inside the component box.- expect(slider).toHaveStyle({insetInlineStart: expectedPosition});+ expect(progressOf(slider)).toBe(expectedProgress);},);- // Regression: #5050 — at min/max the thumb centred on the container edge,- // so half of it (10px of a 20px thumb) hung outside the component.it.each([- {value: 0, position: 'calc(0% + 10px)'},- {value: 50, position: 'calc(50% + 0px)'},- {value: 100, position: 'calc(100% - 10px)'},+ {value: 0, progress: '0'},+ {value: 25, progress: '0.25'},+ {value: 100, progress: '1'},])(- 'insets the thumb at value $value so it stays in bounds',- ({value, position}) => {- render(<Slider label="Volume" value={value} min={0} max={100} />);- expect(screen.getByRole('slider')).toHaveStyle({- insetInlineStart: position,- });- },- );-- it.each([- {value: 0, position: 'calc(0% + 10px)'},- {value: 100, position: 'calc(100% - 10px)'},- ])(- 'insets a vertical thumb at value $value so it stays in bounds',- ({value, position}) => {+ 'places the thumb by its progress at value $value, horizontal and vertical',+ ({value, progress}) => {+ const {unmount} = render(+ <Slider label="Volume" value={value} min={0} max={100} />,+ );+ expect(progressOf(screen.getByRole('slider'))).toBe(progress);+ unmount();render(<Sliderlabel="Volume"@@ -157,10 +160,37 @@ describe('Slider', () => {orientation="vertical"/>,);- expect(screen.getByRole('slider')).toHaveStyle({bottom: position});+ expect(progressOf(screen.getByRole('slider'))).toBe(progress);},);+ it('places a range fill between the two thumbs and a single fill from the start', () => {+ const {container, rerender} = render(+ <Slider label="Volume" value={40} min={0} max={200} />,+ );+ const fills = () =>+ Array.from(+ container.querySelectorAll<HTMLElement>('[aria-hidden="true"] [style]'),+ ).filter(element => progressOf(element, '--_slider-fill-end') !== '');+ expect(fills().length).toBeGreaterThan(0);+ for (const fill of fills()) {+ expect(progressOf(fill, '--_slider-fill-start')).toBe('0');+ expect(progressOf(fill, '--_slider-fill-end')).toBe('0.2');+ }+ rerender(+ <Slider+ label="Volume"+ value={[50, 150] as [number, number]}+ min={0}+ max={200}+ />,+ );+ for (const fill of fills()) {+ expect(progressOf(fill, '--_slider-fill-start')).toBe('0.25');+ expect(progressOf(fill, '--_slider-fill-end')).toBe('0.75');+ }+ });+it('reflects orientation and disabled state on the interactive control target', () => {render(<Slider@@ -171,7 +201,7 @@ describe('Slider', () => {isDisabled/>,);- const control = screen.getByRole('slider').parentElement;+ const control = controlOf(screen.getByRole('slider'));expect(control).not.toBeNull();expect(control).toHaveClass('astryx-slider-control');expect(control).toHaveAttribute('data-orientation', 'vertical');@@ -433,7 +463,7 @@ describe('Slider', () => {/>,);const slider = screen.getByRole('slider');- const trackContainer = slider.parentElement!;+ const trackContainer = controlOf(slider);trackContainer.getBoundingClientRect = () => ({left: 0,@@ -664,7 +694,7 @@ describe('Slider', () => {/>,);const slider = screen.getByRole('slider');- const trackContainer = slider.parentElement!;+ const trackContainer = controlOf(slider);trackContainer.getBoundingClientRect = () => ({left: 0,@@ -697,7 +727,7 @@ describe('Slider', () => {<Slider label="Volume" value={50} min={0} max={100} onChange={vi.fn()} />,);const slider = screen.getByRole('slider');- const trackContainer = slider.parentElement!;+ const trackContainer = controlOf(slider);trackContainer.getBoundingClientRect = () => ({left: 0,@@ -738,7 +768,7 @@ describe('Slider', () => {onChange={handleChange}/>,);- const track = screen.getByRole('slider').parentElement!;+ const track = controlOf(screen.getByRole('slider'));track.getBoundingClientRect = () => ({left: 0,top: 0,@@ -770,7 +800,7 @@ describe('Slider', () => {onChange={handleChange}/>,);- const track = screen.getByRole('slider').parentElement!;+ const track = controlOf(screen.getByRole('slider'));track.getBoundingClientRect = () => ({left: 0,top: 0,@@ -817,7 +847,7 @@ describe('Slider', () => {/>,);const thumb = screen.getByRole('slider');- const track = thumb.parentElement!;+ const track = controlOf(thumb);const realGetComputedStyle = window.getComputedStyle;const gcsSpy = vi.spyOn(window, 'getComputedStyle')@@ -855,7 +885,7 @@ describe('Slider', () => {/>,);const thumb = screen.getByRole('slider');- const track = thumb.parentElement!;+ const track = controlOf(thumb);const realGetComputedStyle = window.getComputedStyle;const gcsSpy = vi.spyOn(window, 'getComputedStyle')@@ -1035,7 +1065,7 @@ describe('Slider', () => {const h = {hidden: true} as const;function getTrack(): HTMLElement {- return screen.getByRole('slider').parentElement!;+ return controlOf(screen.getByRole('slider'));}it('shows the reason tooltip on hover when disabled with a reason', async () => {@@ -1202,7 +1232,7 @@ describe('Slider', () => {// The track has no layout in jsdom; pointer maths needs a real rect.const grabTrack = (thumb: HTMLElement) => {- const track = thumb.parentElement!;+ const track = controlOf(thumb);track.getBoundingClientRect = () => ({left: 0,top: 0,@@ -1362,6 +1392,27 @@ describe('Slider', () => {});});+describe('a press focuses the thumb it lands on', () => {+ // Coincident range thumbs rely on it: a press that never moves leaves+ // focus on the upper thumb, whatever pointer pressed it.+ for (const pointerType of ['mouse', 'touch', 'pen'] as const) {+ it(`for a ${pointerType}`, () => {+ render(<Slider label="Volume" value={50} onChange={() => {}} />);+ const thumb = screen.getByRole('slider');+ expect(document.activeElement).not.toBe(thumb);+ fireEvent.pointerDown(thumb, {+ pointerId: 1,+ pointerType,+ button: 0,+ isPrimary: true,+ clientX: 100,+ clientY: 10,+ });+ expect(document.activeElement).toBe(thumb);+ });+ }+});+describe('one pointer per drag', () => {// valueDisplay="none" keeps the thumb a direct child of the track, so the// mocked rect lands on it: 200 px wide, thumbs travel 10 px (0) to 190 px@@ -1388,7 +1439,7 @@ describe('one pointer per drag', () => {}function trackOf(thumb: HTMLElement): HTMLElement {- const track = thumb.parentElement!;+ const track = controlOf(thumb);track.getBoundingClientRect = () => ({left: 0,top: 0,@@ -1539,7 +1590,7 @@ describe('pressed state', () => {<Slider label="Volume" value={50} min={0} max={100} onChange={vi.fn()} />,);const thumb = screen.getByRole('slider');- const trackContainer = thumb.parentElement!;+ const trackContainer = controlOf(thumb);trackContainer.getBoundingClientRect = () => ({left: 0,top: 0,@@ -1639,10 +1690,16 @@ describe('pressed state', () => {toJSON: () => {},});+ // A mouse press on a thumb is the thumb's pan (spec:AST-094 FR43). So it+ // is a real mouse press: the gesture host takes only a known pointer.fireEvent.pointerDown(end, {clientX: 100,clientY: 10,pointerId: 1,+ pointerType: 'mouse',+ isPrimary: true,+ button: 0,+ buttons: 1,});expect(declaresPressedOverlay(end)).toBe(true);expect(declaresPressedOverlay(start)).toBe(false);@@ -1651,13 +1708,64 @@ describe('pressed state', () => {it('does not press a disabled slider', () => {render(<Slider label="Volume" value={50} isDisabled onChange={vi.fn()} />);const thumb = screen.getByRole('slider');- fireEvent.pointerDown(thumb.parentElement!, {+ fireEvent.pointerDown(controlOf(thumb), {clientX: 20,clientY: 10,pointerId: 1,});expect(declaresPressedOverlay(thumb)).toBe(false);});++ it('takes only a primary click: a right click or a macOS ctrl-click on the track neither moves the value nor presses (spec:AST-094 FR43)', () => {+ const handleChange = vi.fn();+ render(<Slider label="Volume" value={50} onChange={handleChange} />);+ const thumb = screen.getByRole('slider');+ const track = controlOf(thumb);+ track.getBoundingClientRect = () => ({+ left: 0,+ top: 0,+ right: 200,+ bottom: 20,+ width: 200,+ height: 20,+ x: 0,+ y: 0,+ toJSON: () => {},+ });+ const press = (+ pointerId: number,+ init: {button: number; ctrlKey?: boolean},+ ) => {+ fireEvent.pointerDown(track, {+ clientX: 20,+ clientY: 10,+ pointerId,+ pointerType: 'mouse',+ isPrimary: true,+ ...init,+ });+ fireEvent.pointerUp(track, {clientX: 20, clientY: 10, pointerId});+ };+ // A right click is the context request, not a press.+ press(1, {button: 2});+ expect(handleChange).not.toHaveBeenCalled();+ expect(declaresPressedOverlay(thumb)).toBe(false);+ // So is a ctrl-click on macOS.+ const platform = vi+ .spyOn(navigator, 'platform', 'get')+ .mockReturnValue('MacIntel');+ try {+ press(2, {button: 0, ctrlKey: true});+ expect(handleChange).not.toHaveBeenCalled();+ expect(declaresPressedOverlay(thumb)).toBe(false);+ } finally {+ platform.mockRestore();+ }+ // A primary click there still sets the value, toward the click.+ press(3, {button: 0});+ expect(handleChange).toHaveBeenCalledTimes(1);+ expect(handleChange.mock.calls[0][0]).toBeLessThan(50);+ });});describe('coincident range thumbs', () => {@@ -1677,6 +1785,20 @@ describe('coincident range thumbs', () => {});}+ // A mouse press on a thumb is the thumb's pan, so these are real mouse+ // presses: the gesture host takes only a known pointer. A drag starts once+ // the pointer has moved 10 px. The value then follows its further travel+ // over the control's 200 px, 2 px a value.+ const mouse = (clientX: number, buttons = 1) => ({+ clientX,+ clientY: 10,+ pointerId: 1,+ pointerType: 'mouse',+ isPrimary: true,+ button: 0,+ buttons,+ });+function ControlledRange({initial,onChange,@@ -1705,9 +1827,10 @@ describe('coincident range thumbs', () => {mockGroupRect();const [start, end] = screen.getAllByRole('slider');- // The press lands on the upper thumb, the one painted on top.- fireEvent.pointerDown(end, {clientX: 190, clientY: 10, pointerId: 1});- fireEvent.pointerMove(end, {clientX: 100, clientY: 10, pointerId: 1});+ // The press lands on the upper thumb, the one painted on top. 110 px+ // toward the minimum is 100 px past the threshold: 50 values.+ fireEvent.pointerDown(end, mouse(190));+ fireEvent.pointerMove(end, mouse(80));expect(onChange).toHaveBeenLastCalledWith([50, 100]);expect(start).toHaveAttribute('aria-valuenow', '50');@@ -1724,10 +1847,11 @@ describe('coincident range thumbs', () => {expect(start.compareDocumentPosition(end) & Node.DOCUMENT_POSITION_FOLLOWING,).toBeTruthy();- fireEvent.pointerDown(end, {clientX: 100, clientY: 10, pointerId: 1});+ fireEvent.pointerDown(end, mouse(100));expect(declaresPressedOverlay(end)).toBe(true);expect(declaresPressedOverlay(start)).toBe(false);- fireEvent.pointerUp(end, {clientX: 100, clientY: 10, pointerId: 1});+ fireEvent.pointerUp(end, mouse(100, 0));+ expect(onChange).not.toHaveBeenCalled();expect(start).toHaveAttribute('aria-valuenow', '50');expect(end).toHaveAttribute('aria-valuenow', '50');expect(document.activeElement).toBe(end);@@ -1772,26 +1896,26 @@ describe('coincident range thumbs', () => {mockGroupRect();const [start, end] = screen.getAllByRole('slider');- fireEvent.pointerDown(end, {clientX: 100, clientY: 10, pointerId: 1});- // On the shared value nothing says which way the drag goes yet: the- // pressed thumb keeps the press and nothing moves.+ fireEvent.pointerDown(end, mouse(100));expect(declaresPressedOverlay(end)).toBe(true);- expect(onChange).toHaveBeenLastCalledWith([50, 50]);+ expect(onChange).not.toHaveBeenCalled();- fireEvent.pointerMove(end, {clientX: 64, clientY: 10, pointerId: 1});+ // 50 px toward the minimum is 40 px past the threshold, 20 values down,+ // which only the lower thumb can follow.+ fireEvent.pointerMove(end, mouse(50));expect(onChange).toHaveBeenLastCalledWith([30, 50]);expect(declaresPressedOverlay(start)).toBe(true);expect(declaresPressedOverlay(end)).toBe(false);expect(document.activeElement).toBe(start);- // Back past the other thumb's value the drag still follows the pointer:- // the start thumb ends against the end thumb, which takes the drag.- fireEvent.pointerMove(end, {clientX: 154, clientY: 10, pointerId: 1});+ // Back past the shared value, 60 px past the threshold the other way.+ // The lower thumb stays at 50, and the upper one takes the drag to 80.+ fireEvent.pointerMove(end, mouse(150));expect(onChange).toHaveBeenLastCalledWith([50, 80]);expect(declaresPressedOverlay(end)).toBe(true);expect(declaresPressedOverlay(start)).toBe(false);expect(document.activeElement).toBe(end);- fireEvent.pointerUp(end, {clientX: 154, clientY: 10, pointerId: 1});+ fireEvent.pointerUp(end, mouse(150, 0));expect(declaresPressedOverlay(end)).toBe(false);});@@ -1802,24 +1926,26 @@ describe('coincident range thumbs', () => {);mockGroupRect();let [, end] = screen.getAllByRole('slider');- // A press on the thumbs a little below their value (79), dragged toward- // the maximum: the upper thumb follows.- fireEvent.pointerDown(end, {clientX: 152, clientY: 10, pointerId: 1});- expect(onChange).toHaveBeenLastCalledWith([80, 80]);- fireEvent.pointerMove(end, {clientX: 172, clientY: 10, pointerId: 1});+ // Pressed 2 px below the shared value (154 px), nothing moves; 30 px+ // toward the maximum is 20 px past the threshold, 10 values up.+ fireEvent.pointerDown(end, mouse(152));+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.pointerMove(end, mouse(182));expect(onChange).toHaveBeenLastCalledWith([80, 90]);- fireEvent.pointerUp(end, {clientX: 172, clientY: 10, pointerId: 1});+ fireEvent.pointerUp(end, mouse(182, 0));unmount();- // A press a little above it (81), dragged toward the minimum: the lower- // thumb follows.render(<ControlledRange initial={[80, 80]} onChange={onChange} />);mockGroupRect();const [start, upper] = screen.getAllByRole('slider');end = upper;- fireEvent.pointerDown(end, {clientX: 156, clientY: 10, pointerId: 1});- expect(onChange).toHaveBeenLastCalledWith([80, 80]);- fireEvent.pointerMove(end, {clientX: 64, clientY: 10, pointerId: 1});+ onChange.mockClear();+ // Pressed 2 px above it, the drag still waits for the first movement. A+ // move of 110 px toward the minimum is 100 px past the threshold, 50+ // values down.+ fireEvent.pointerDown(end, mouse(156));+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.pointerMove(end, mouse(46));expect(onChange).toHaveBeenLastCalledWith([30, 80]);expect(start).toHaveAttribute('aria-valuenow', '30');});@@ -1845,10 +1971,12 @@ describe('coincident range thumbs', () => {let spy = asRtl();let [, end] = screen.getAllByRole('slider');// Leftward is toward the maximum: the upper thumb follows.- fireEvent.pointerDown(end, {clientX: 100, clientY: 10, pointerId: 1});- fireEvent.pointerMove(end, {clientX: 46, clientY: 10, pointerId: 1});+ // Right to left the value grows leftward: 70 px left is 60 px past the+ // threshold, 30 values up, which the upper thumb takes.+ fireEvent.pointerDown(end, mouse(100));+ fireEvent.pointerMove(end, mouse(30));expect(onChange).toHaveBeenLastCalledWith([50, 80]);- fireEvent.pointerUp(end, {clientX: 46, clientY: 10, pointerId: 1});+ fireEvent.pointerUp(end, mouse(30, 0));spy.mockRestore();unmount();@@ -1858,8 +1986,9 @@ describe('coincident range thumbs', () => {spy = asRtl();const [start, upper] = screen.getAllByRole('slider');end = upper;- fireEvent.pointerDown(end, {clientX: 100, clientY: 10, pointerId: 1});- fireEvent.pointerMove(end, {clientX: 154, clientY: 10, pointerId: 1});+ // 70 px right is 30 values down: the lower thumb takes it, and focus.+ fireEvent.pointerDown(end, mouse(100));+ fireEvent.pointerMove(end, mouse(170));expect(onChange).toHaveBeenLastCalledWith([20, 50]);expect(document.activeElement).toBe(start);spy.mockRestore();@@ -1870,17 +1999,16 @@ describe('coincident range thumbs', () => {render(<ControlledRange initial={[80, 80]} onChange={onChange} />);mockGroupRect();const [, end] = screen.getAllByRole('slider');- // A press on the thumbs whose first step drifts toward the minimum (a- // touch contact settling, say) picks the lower thumb...- fireEvent.pointerDown(end, {clientX: 154, clientY: 10, pointerId: 1});- fireEvent.pointerMove(end, {clientX: 152, clientY: 10, pointerId: 1});- expect(onChange).toHaveBeenLastCalledWith([79, 80]);- // ...but a drag on toward the maximum still moves the range: once the- // pointer passes the shared value the upper thumb takes the drag, as on- // a press whose first step went that way.- fireEvent.pointerMove(end, {clientX: 188.2, clientY: 10, pointerId: 1});+ // 20 px toward the minimum, 10 past the threshold, picks the lower+ // thumb: 5 values down.+ fireEvent.pointerDown(end, mouse(154));+ fireEvent.pointerMove(end, mouse(134));+ expect(onChange).toHaveBeenLastCalledWith([75, 80]);+ // Back past the shared value to 38 px past the threshold the other way.+ // The lower thumb stops at 80, and the upper one takes the drag to 99.+ fireEvent.pointerMove(end, mouse(182));expect(onChange).toHaveBeenLastCalledWith([80, 99]);- fireEvent.pointerUp(end, {clientX: 188.2, clientY: 10, pointerId: 1});+ fireEvent.pointerUp(end, mouse(182, 0));});it('measures the first movement from a press on a mark label against the press, not the mark', () => {@@ -1944,9 +2072,9 @@ describe('coincident range thumbs', () => {document.getElementById(id)?.getAttribute('role') === 'tooltip',) ?? '',);- fireEvent.pointerDown(end, {clientX: 100, clientY: 10, pointerId: 1});- fireEvent.pointerMove(end, {clientX: 64, clientY: 10, pointerId: 1});- fireEvent.pointerUp(end, {clientX: 64, clientY: 10, pointerId: 1});+ fireEvent.pointerDown(end, mouse(100));+ fireEvent.pointerMove(end, mouse(64));+ fireEvent.pointerUp(end, mouse(64, 0));expect(document.activeElement).toBe(start);expect(tipOf(end)).not.toHaveAttribute('popover-open');});@@ -1990,8 +2118,9 @@ describe('coincident range thumbs', () => {mockGroupRect();const [, end] = screen.getAllByRole('slider');- fireEvent.pointerDown(end, {clientX: 10, clientY: 10, pointerId: 1});- fireEvent.pointerMove(end, {clientX: 100, clientY: 10, pointerId: 1});+ // 110 px toward the maximum is 100 px past the threshold: 50 values.+ fireEvent.pointerDown(end, mouse(10));+ fireEvent.pointerMove(end, mouse(120));expect(onChange).toHaveBeenLastCalledWith([0, 50]);});diff --git a/packages/core/src/Slider/Slider.tsx b/packages/core/src/Slider/Slider.tsxindex a75e7c275b..4b84739552 100644--- a/packages/core/src/Slider/Slider.tsx+++ b/packages/core/src/Slider/Slider.tsx@@ -4,8 +4,8 @@/*** @file Slider.tsx- * @input Uses React, useId, useRef, useCallback, useEffect, Field, Tooltip, useTooltip, VisuallyHidden- * @output Exports Slider and its props; unfilled marks share the track token; modifier-only key presses do not restore the thumb focus ring; a drag belongs to the pointer that started it; two coincident range thumbs separate toward the press or the first movement+ * @input Uses React, useId, useRef, useCallback, useEffect, Field, useTooltip, VisuallyHidden, the touch presentation resolver and useSliderTouch (UISlider's touch tracking)+ * @output Exports Slider and its props. Unfilled marks share the track token. Modifier-only key presses do not restore the thumb focus ring. A drag belongs to the pointer that started it. The thumbs and the filled range travel by `translate` in container units, so moving them never lays out. Padding on the control moves no part. The value tooltip anchors to a box that layout places at the value. A drag on a thumb is a pan for every pointer, tracked as UISlider does. Under a coarse primary pointer, each thumb's `::before` is its touch target. A finger's tap on the track sets the value on its lift. A mouse press on the track keeps the pointer handlers. Two coincident range thumbs separate toward the press or the first movement* @position Core implementation; consumed by index.ts, tested by Slider.test.tsx** SYNC: When modified, update these files to stay in sync:@@ -23,10 +23,15 @@ import {useRef,useState,useCallback,+ type CSSProperties,type FocusEvent,type KeyboardEvent,type PointerEvent,+ type ReactElement,+ type ReactNode,+ type Ref,} from 'react';+import {flushSync} from 'react-dom';import * as stylex from '@stylexjs/stylex';import {colorVars,@@ -38,7 +43,6 @@ import {typeScaleVars,} from '../theme/tokens.stylex';import {Field} from '../Field/Field';-import {Tooltip} from '../Tooltip/Tooltip';import {useTooltip} from '../Tooltip';import {VisuallyHidden} from '../VisuallyHidden';import type {InputStatus} from '../Field/types';@@ -53,6 +57,14 @@ import {} from '../Field/fieldParts';import type {SizeValue} from '../utils/types';import {themeProps} from '../utils/themeProps';+import {isPrimaryClick} from '../utils/primaryClick';+import {useTouchPresentation} from '../utils/touchPresentation';+import {slider as UIKIT_SLIDER} from '../motion/uikit/slider';+import {+ useSliderTouch,+ type SliderTouchModel,+ type SliderTouchParts,+} from './useSliderTouch';import {useMergedRefs} from '../hooks/useMergedRefs';import {useResolvedRequired} from '../hooks/useResolvedRequired';@@ -169,6 +181,35 @@ export type SliderProps = SliderSingleProps | SliderRangeProps;const TRACK_SIZE = 4;const THUMB_SIZE = 20;+/**+ * Where a thumb sits, as its progress along the travel (0 at `min`, 1 at+ * `max`), written inline on the thumb. CSS computes its translate from it+ * against the control's size, in container units. So moving the thumb+ * restyles and composites but never lays out, and the server renders the+ * right place. A value tooltip or text display still lays out as its text+ * changes.+ */+const THUMB_PROGRESS = '--_slider-progress';+/** A thumb's touch-target insets under a finger, which its `::before` draws. */+const HIT_INSET = {+ top: '--_slider-hit-top',+ bottom: '--_slider-hit-bottom',+ inlineStart: '--_slider-hit-start',+ inlineEnd: '--_slider-hit-end',+} as const;+/** Half a thumb: the inset of the thumb's travel at each end of the track. */+const THUMB_INSET_PX = THUMB_SIZE / 2;+/** The filled range's ends as progress, written inline on the fill parts. */+const FILL_START = '--_slider-fill-start';+const FILL_END = '--_slider-fill-end';++// The private progress properties a thumb and the fill parts publish inline.+type ThumbStyle = React.CSSProperties &+ Record<typeof THUMB_PROGRESS, number> &+ Partial<Record<(typeof HIT_INSET)[keyof typeof HIT_INSET], string>>;+type FillStyle = React.CSSProperties &+ Record<typeof FILL_START | typeof FILL_END, number>;+// =============================================================================// Styles// =============================================================================@@ -184,10 +225,43 @@ const styles = stylex.create({display: 'flex',alignItems: 'center',flexGrow: 1,- touchAction: 'none',+ // Under a finger (a coarse primary pointer) the control leaves the browser+ // its pans. So a swipe from the track or across a thumb scrolls the page.+ // The gesture host narrows that per element from the recognizers attached+ // to it (a thumb's pan keeps its own axis) and never widens it. A held+ // thumb's pan locks text selection and the callout until the lift. A+ // mouse or a trackpad keeps the control's `none`.+ touchAction: {+ default: 'none',+ '@media (pointer: coarse)': 'manipulation',+ },+ // The control's text is never selectable. WebKit applies only the+ // prefixed property. So both are written. A held finger on the track+ // then starts no selection either. The gesture host's lock leaves this+ // always-on suppression as it is.+ WebkitUserSelect: 'none',userSelect: 'none',isolation: 'isolate',},+ // Every part of the control sits in this box, which fills the control's+ // padding box. So padding on the control (a theme rule, `controlStyle`)+ // moves no part. The thumbs and the fill travel in container units of it+ // (`cqi` / `cqb`). Its size never depends on its content.+ travelBox: {+ position: 'absolute',+ inset: 0,+ containerType: 'size',+ },+ // Where layout places a thumb at its value: the value tooltip's position+ // anchor. CSS anchor positioning reads the anchor's layout box, which the+ // thumb's `translate` does not move in every engine. So the tooltip anchors+ // here while hover and focus stay on the thumb.+ valueAnchor: {+ position: 'absolute',+ width: THUMB_SIZE,+ height: THUMB_SIZE,+ pointerEvents: 'none',+ },trackContainerHorizontal: {height: THUMB_SIZE,// The whole track is the tap target (a click anywhere on it moves the@@ -246,26 +320,95 @@ const styles = stylex.create({bottom: 0,width: TRACK_SIZE,},- filledTrack: {+ // The filled range is a full-length bar moved into place inside two+ // clips, so it travels by translate alone. The clip has the track's shape+ // and rounds the start of a single slider's fill. The mover's start edge+ // cuts the fill at the range's start, and the fill's own end sits at the+ // range's end. Both ends of a range hide under its thumbs.+ fillClip: {position: 'absolute',- backgroundColor: colorVars['--color-accent'],+ overflow: 'hidden',borderRadius: radiusVars['--radius-full'],+ pointerEvents: 'none',},- filledTrackHorizontal: {+ fillClipHorizontal: {+ insetInlineStart: 0,+ insetInlineEnd: 0,height: TRACK_SIZE,top: '50%',transform: 'translateY(-50%)',},- filledTrackVertical: {+ fillClipVertical: {+ top: 0,+ bottom: 0,width: TRACK_SIZE,},+ fillMover: {+ position: 'absolute',+ inset: 0,+ overflow: 'hidden',+ },+ // A range's start is round, like the track's ends (the clip already+ // rounds a single slider's start). It shows through a disabled thumb's+ // translucent fill.+ fillMoverRangeStartHorizontal: {+ borderStartStartRadius: radiusVars['--radius-full'],+ borderEndStartRadius: radiusVars['--radius-full'],+ },+ fillMoverRangeStartVertical: {+ borderEndStartRadius: radiusVars['--radius-full'],+ borderEndEndRadius: radiusVars['--radius-full'],+ },+ fillMoverRangeHorizontal: {+ translate: {+ default: `calc(${THUMB_INSET_PX}px + var(${FILL_START}) * (100cqi - ${THUMB_SIZE}px)) 0`,+ ':dir(rtl)': `calc(-${THUMB_INSET_PX}px - var(${FILL_START}) * (100cqi - ${THUMB_SIZE}px)) 0`,+ },+ },+ fillMoverRangeVertical: {+ translate: `0 calc(-${THUMB_INSET_PX}px - var(${FILL_START}) * (100cqb - ${THUMB_SIZE}px))`,+ },+ filledTrack: {+ position: 'absolute',+ inset: 0,+ backgroundColor: colorVars['--color-accent'],+ },+ // The fill's end is round too, under the thumb.+ filledTrackHorizontal: {+ borderStartEndRadius: radiusVars['--radius-full'],+ borderEndEndRadius: radiusVars['--radius-full'],+ },+ filledTrackVertical: {+ borderStartStartRadius: radiusVars['--radius-full'],+ borderStartEndRadius: radiusVars['--radius-full'],+ },+ // A single slider's fill runs from the track's start to the thumb's center.+ filledTrackSingleHorizontal: {+ translate: {+ default: `calc(${THUMB_INSET_PX}px + var(${FILL_END}) * (100cqi - ${THUMB_SIZE}px) - 100cqi) 0`,+ ':dir(rtl)': `calc(100cqi - ${THUMB_INSET_PX}px - var(${FILL_END}) * (100cqi - ${THUMB_SIZE}px)) 0`,+ },+ },+ filledTrackSingleVertical: {+ translate: `0 calc(100cqb - ${THUMB_INSET_PX}px - var(${FILL_END}) * (100cqb - ${THUMB_SIZE}px))`,+ },+ // A range's fill runs from the lower thumb's center to the upper's. The+ // mover already sits at the lower one.+ filledTrackRangeHorizontal: {+ translate: {+ default: `calc((var(${FILL_END}) - var(${FILL_START})) * (100cqi - ${THUMB_SIZE}px) - 100cqi) 0`,+ ':dir(rtl)': `calc(100cqi - (var(${FILL_END}) - var(${FILL_START})) * (100cqi - ${THUMB_SIZE}px)) 0`,+ },+ },+ filledTrackRangeVertical: {+ translate: `0 calc(100cqb - (var(${FILL_END}) - var(${FILL_START})) * (100cqb - ${THUMB_SIZE}px))`,+ },thumb: {position: 'absolute',width: THUMB_SIZE,height: THUMB_SIZE,borderRadius: radiusVars['--radius-full'],backgroundColor: colorVars['--color-accent'],- transform: 'translate(-50%, -50%)',transitionProperty: 'background-color, box-shadow',transitionDuration: {default: durationVars['--duration-fast'],@@ -280,16 +423,42 @@ const styles = stylex.create({zIndex: 1,},thumbHorizontal: {- top: '50%',- // The thumb is positioned via logical `insetInlineStart`, which resolves- // from the right edge under RTL. The centering translate is a physical- // (screen-space) transform, so it must flip its X direction under RTL to- // keep the thumb centered on the value point.- transform: {- default: 'translate(-50%, -50%)',- ':is([dir="rtl"] *)': 'translate(50%, -50%)',+ // Centered by its offset, not by a transform: the touch lift scales the+ // thumb (`scale`), and CSS applies `transform` inside `scale`. So a+ // centering translate would grow with it and lift the thumb off the+ // track. UISlider's lens grows around its center.+ top: `calc(50% - ${THUMB_SIZE / 2}px)`,+ insetInlineStart: 0,+ // The thumb starts at the track's inline start (the right edge under+ // RTL). It travels by its progress along the track minus its own size,+ // so its center lands where `insetPosition` places the fill and the+ // marks. `translate` is physical, so it flips its sign under RTL.+ translate: {+ default: `calc(var(${THUMB_PROGRESS}) * (100cqi - ${THUMB_SIZE}px)) 0`,+ ':dir(rtl)': `calc(var(${THUMB_PROGRESS}) * (${THUMB_SIZE}px - 100cqi)) 0`,+ },+ },+ // A thumb's touch target under a finger (UISlider's hit area): the thumb's+ // own `::before`, invisible and centered on it, larger than it. So a touch+ // presentation renders no more elements than a mouse one. Each side grows+ // by the inset `thumbHitInsets` sets on the thumb.+ thumbHit: {+ '::before': {+ content: '""',+ position: 'absolute',+ top: `var(${HIT_INSET.top})`,+ bottom: `var(${HIT_INSET.bottom})`,+ insetInlineStart: `var(${HIT_INSET.inlineStart})`,+ insetInlineEnd: `var(${HIT_INSET.inlineEnd})`,},},+ thumbVertical: {+ bottom: 0,+ // Centered by its offset (see thumbHorizontal): the same in both+ // directions, since the thumb is symmetric.+ insetInlineStart: `calc(50% - ${THUMB_SIZE / 2}px)`,+ translate: `0 calc(var(${THUMB_PROGRESS}) * (${THUMB_SIZE}px - 100cqb))`,+ },thumbHover: {backgroundColor: {default: colorVars['--color-accent'],@@ -439,12 +608,6 @@ function insetPosition(percent: number): string {return cssLength(percent, THUMB_INSET - (percent / 100) * THUMB_SIZE);}-/** Distance between two inset positions; the inset itself cancels out. */-function insetSpan(fromPercent: number, toPercent: number): string {- const delta = toPercent - fromPercent;- return cssLength(delta, -(delta / 100) * THUMB_SIZE);-}-/** Inverse of `insetPosition`: an offset from the box start back to 0–1. */function travelFraction(offset: number, size: number): number {const travel = size - THUMB_SIZE;@@ -463,6 +626,51 @@ function cssLength(percent: number, px: number): string {return `calc(${round(percent)}% ${px < 0 ? '-' : '+'} ${Math.abs(round(px))}px)`;}+/**+ * A thumb's value tooltip: hover and focus on the thumb, position from a+ * thumb-sized anchor that layout places at the value (styles.valueAnchor).+ */+function SliderValueTooltip({+ content,+ placement,+ isOpen,+ anchorStyle,+ thumbRef,+ children,+}: {+ content: ReactNode;+ placement: 'above' | 'start';+ isOpen: boolean | undefined;+ anchorStyle: CSSProperties;+ thumbRef: Ref<HTMLDivElement> | undefined;+ children: (trigger: {+ ref: Ref<HTMLDivElement>;+ describedBy: string;+ }) => ReactElement;+}): ReactElement {+ const tooltip = useTooltip({+ placement,+ delay: 0,+ focusTrigger: 'always',+ isOpen,+ });+ const triggerRef = useMergedRefs<HTMLDivElement>(+ thumbRef,+ tooltip.interactionRef,+ );+ return (+ <>+ <span+ aria-hidden="true"+ ref={tooltip.positionRef}+ {...mergeProps(stylex.props(styles.valueAnchor), {style: anchorStyle})}+ />+ {children({ref: triggerRef, describedBy: tooltip.describedBy})}+ {tooltip.renderTooltip(content)}+ </>+ );+}+// =============================================================================// Component// =============================================================================@@ -551,9 +759,19 @@ export function Slider({ref, ...props}: SliderProps) {const requiredID = useId();const trackRef = useRef<HTMLDivElement>(null);+ const fillMoverRef = useRef<HTMLDivElement>(null);+ const fillRef = useRef<HTMLDivElement>(null);const draggingThumbRef = useRef<number | null>(null);const [draggingThumb, setDraggingThumb] = useState<number | null>(null);+ // The thumbs track as UISlider's for every pointer (useSliderTouch): a+ // drag on a thumb is a pan. Their touch targets show only under a coarse+ // primary pointer, after hydration: one touch model on every touch+ // device. A mouse press on the track keeps the pointer+ // handlers below.+ const isTouchPresentation = useTouchPresentation().isTouch;+ const hasTouchTargets = isTouchPresentation && !isDisabled;+// A thumb is a div[role="slider"], and `handlePointerDown` focuses it from// script after preventDefault — which Chromium treats as focus-visible, so// dragging with a mouse drew the keyboard ring (measured: `:focus-visible`@@ -578,7 +796,7 @@ export function Slider({ref, ...props}: SliderProps) {}, []);// Disabled-reason tooltip. This is a *separate* useTooltip instance from the- // per-thumb value bubble (the `<Tooltip>` component below): it anchors to the+ // per-thumb value bubble (SliderValueTooltip below): it anchors to the// track container and fires on hover/focus of the whole control. Disabled// controls swallow pointer events, so the thumb stays perceivable via// aria-disabled while pointer/keyboard handlers early-return on isDisabled.@@ -799,6 +1017,27 @@ export function Slider({ref, ...props}: SliderProps) {if (isDisabled) {return;}+ // Only a primary button presses: a right click or a macOS ctrl-click+ // is the platform's context request, and a pen's+ // barrel button presses nothing either.+ if (!isPrimaryClick(e)) {+ return;+ }+ // A press on a thumb belongs to the slider's gestures (useSliderTouch),+ // which pan it for every pointer. The thumb still takes focus from any+ // press, as it did. A finger's or a pen's tap on the track sets the+ // value when it lifts. So only a mouse press on the track goes on.+ const thumb = (e.target as Element).closest<HTMLElement>(+ '[role="slider"]',+ );+ if (thumb != null) {+ thumb.focus();+ setKeyboardFocusThumb(null);+ return;+ }+ if (e.pointerType === 'touch' || e.pointerType === 'pen') {+ return;+ }e.preventDefault();if (draggingThumbRef.current !== null) {return;@@ -959,6 +1198,105 @@ export function Slider({ref, ...props}: SliderProps) {[endDrag],);+ // The touch presentation's value model (useSliderTouch reads it fresh).+ const updateValueRef = useRef(updateValue);+ updateValueRef.current = updateValue;+ const touchModel: SliderTouchModel = {+ min,+ max,+ isRange,+ isHorizontal,+ isDisabled: isDisabled ?? false,+ thumbSize: THUMB_SIZE,+ values: () => valuesRef.current,+ // The value updateValue would report for this thumb.+ constrain: (index, raw) => {+ const next = clamp(snapToStep(raw, min, step), min, max);+ if (!isRange) {+ return next;+ }+ const minGap = minStepsBetweenThumbs * step;+ const [v0, v1] = valuesRef.current;+ return index === 0+ ? clamp(Math.min(next, v1 - minGap), min, max)+ : clamp(Math.max(next, v0 + minGap), min, max);+ },+ bounds: index => {+ if (!isRange) {+ return [min, max];+ }+ const minGap = minStepsBetweenThumbs * step;+ const [v0, v1] = valuesRef.current;+ return index === 0+ ? [min, clamp(v1 - minGap, min, max)]+ : [clamp(v0 + minGap, min, max), max];+ },+ change: (index, next, from) =>+ updateValueRef.current(index, next, true, from),+ // A finger paints the thumb pressed and opens its value tooltip.+ // `handlePointerDown` already focused it.+ press: index => {+ setDraggingThumb(index);+ // When a thumb of this slider holds focus, a drag handed to the other+ // thumb takes the focus along. Every press on a thumb focuses it.+ const thumbs =+ trackRef.current?.querySelectorAll<HTMLElement>('[role="slider"]');+ const active = trackRef.current?.ownerDocument.activeElement;+ if (index != null && thumbs != null && active != null) {+ const list = Array.from(thumbs);+ if (list.includes(active as HTMLElement) && list[index] !== active) {+ list[index]?.focus();+ }+ }+ },+ // The touch interaction ended, in the handler that ended it: the lift, a+ // cancel or the coast's last frame. The owner renders the last value+ // now, from that same handler. Then the controller can hand the parts+ // back to the stylesheet, and onChangeEnd carries the rendered value.+ commit: (index, next) => {+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the owner must render the interaction's last value before the parts return to the stylesheet and onChangeEnd reads it+ flushSync(() => {+ if (next !== null) {+ updateValueRef.current(index, next);+ }+ setDraggingThumb(null);+ });+ },+ reportEnd: () => fireChangeEnd(),+ // A tap on the track, from useSliderTouch. It takes a mark's value on a+ // mark, else the point along the travel. It moves the thumb a track+ // press moves.+ valueAt: (x, y) => {+ const mark = trackRef.current?.ownerDocument+ .elementFromPoint?.(x, y)+ ?.closest<HTMLElement>('[data-mark-value]');+ return mark != null+ ? Number(mark.dataset.markValue)+ : getValueFromPosition(x, y);+ },+ thumbFor: value => getClosestThumb(value),+ };+ useSliderTouch({+ isEnabled: !isDisabled,+ model: touchModel,+ thumbCount: values.length,+ thumbsWrapped: valueDisplay === 'tooltip' && !showsDisabledMessage,+ getParts: (): SliderTouchParts | null => {+ const control = trackRef.current;+ if (control == null) {+ return null;+ }+ return {+ control,+ thumbs: Array.from(+ control.querySelectorAll<HTMLElement>('[role="slider"]'),+ ),+ fillMover: fillMoverRef.current,+ fill: fillRef.current,+ };+ },+ });+// Keyboard handlerconst handleKeyDown = useCallback((thumbIndex: number, e: KeyboardEvent<HTMLDivElement>) => {@@ -1069,13 +1407,42 @@ export function Slider({ref, ...props}: SliderProps) {};// Render a thumb+ // Each thumb's touch target grows to UISlider's 48 pt around the thumb.+ // A range's two targets never reach into each other: on the side facing+ // the other thumb, the growth stops at half the gap. So a finger takes the+ // nearer thumb. Container units measure the travel, so the gap needs no+ // layout read.+ const hitGrowth = (UIKIT_SLIDER.thumbHitTarget - THUMB_SIZE) / 2;+ const thumbHitInsets = (thumbIndex: number) => {+ const full = `${-hitGrowth}px`;+ let facing = full;+ if (isRange && max > min) {+ const spread = (values[1] - values[0]) / (max - min);+ const travel = isHorizontal ? '100cqi' : '100cqb';+ facing = `calc(-1 * clamp(0px, (${spread} * (${travel} - ${THUMB_SIZE}px) - ${THUMB_SIZE}px) / 2, ${hitGrowth}px))`;+ }+ // Values grow toward the inline end, and upward on a vertical slider.+ const towardLower = isRange && thumbIndex === 1 ? facing : full;+ const towardUpper = isRange && thumbIndex === 0 ? facing : full;+ const [top, bottom, inlineStart, inlineEnd] = isHorizontal+ ? [full, full, towardLower, towardUpper]+ : [towardUpper, towardLower, full, full];+ return {+ [HIT_INSET.top]: top,+ [HIT_INSET.bottom]: bottom,+ [HIT_INSET.inlineStart]: inlineStart,+ [HIT_INSET.inlineEnd]: inlineEnd,+ };+ };+const renderThumb = (thumbIndex: number) => {const val = values[thumbIndex];const percent = getPercent(val, min, max);- const positionStyle = isHorizontal- ? {insetInlineStart: insetPosition(percent)}- : {bottom: insetPosition(percent), left: '50%'};+ const positionStyle: ThumbStyle = {+ [THUMB_PROGRESS]: percent / 100,+ ...(hasTouchTargets ? thumbHitInsets(thumbIndex) : null),+ };// In range mode each thumb keeps a short individual name that composes// with the group label (announced via the group's aria-labelledby), per@@ -1104,10 +1471,12 @@ export function Slider({ref, ...props}: SliderProps) {const tooltipPlacement = isHorizontal ? 'above' : 'start';const thumbElement = (+ trigger: {ref: Ref<HTMLDivElement>; describedBy: string} | null,+ ) => (<divkey={thumbIndex}{...(!isRange ? rest : undefined)}- ref={!isRange ? ref : undefined}+ ref={trigger != null ? trigger.ref : !isRange ? ref : undefined}id={!isRange ? id : undefined}role="slider"// A disabled thumb keeps its Tab stop (spec:AST-085 FR1).@@ -1125,7 +1494,11 @@ export function Slider({ref, ...props}: SliderProps) {!isRange ? joinAriaIDs(labelID, ariaLabelledByProp) : undefined}aria-describedby={- [!isRange ? ariaDescribedByProp : undefined, ariaDescribedBy]+ [+ !isRange ? ariaDescribedByProp : undefined,+ ariaDescribedBy,+ trigger?.describedBy,+ ].filter(Boolean).join(' ') || undefined}@@ -1145,14 +1518,13 @@ export function Slider({ref, ...props}: SliderProps) {}),stylex.props(styles.thumb,- isHorizontal- ? styles.thumbHorizontal- : rtlStyles.centerInline('50%'),+ isHorizontal ? styles.thumbHorizontal : styles.thumbVertical,!isDisabled && styles.thumbHover,!isDisabled && draggingThumb === thumbIndex && styles.thumbPressed,keyboardFocusThumb === thumbIndex &&focusOutlineStyles.focusVisible,isDisabled && styles.thumbDisabled,+ hasTouchTargets && styles.thumbHit,),undefined,positionStyle,@@ -1161,44 +1533,42 @@ export function Slider({ref, ...props}: SliderProps) {);if (useValueTooltip) {+ const anchorAt = `calc(${insetPosition(percent)} - ${THUMB_SIZE / 2}px)`;return (- <Tooltip+ <SliderValueTooltipkey={thumbIndex}content={displayValue(val)}placement={tooltipPlacement}- delay={0}- focusTrigger="always"// A drag keeps its own thumb's value showing and closes the other// thumb's, which a drag handed over from it may have forced open.isOpen={draggingThumb === null ? undefined : draggingThumb === thumbIndex- }>+ }+ anchorStyle={+ isHorizontal+ ? {+ insetInlineStart: anchorAt,+ top: `calc(50% - ${THUMB_SIZE / 2}px)`,+ }+ : {+ bottom: anchorAt,+ insetInlineStart: `calc(50% - ${THUMB_SIZE / 2}px)`,+ }+ }+ thumbRef={!isRange ? ref : undefined}>{thumbElement}- </Tooltip>+ </SliderValueTooltip>);}- return thumbElement;+ return thumbElement(null);};- // Filled track position — ends at the thumb centre, so it uses the same- // inset mapping as the thumb.- const filledStyle = (() => {- if (isRange) {- const [v0, v1] = values;- const p0 = getPercent(v0, min, max);- const p1 = getPercent(v1, min, max);- if (isHorizontal) {- return {insetInlineStart: insetPosition(p0), width: insetSpan(p0, p1)};- }- return {bottom: insetPosition(p0), height: insetSpan(p0, p1)};- }- const p = getPercent(values[0], min, max);- if (isHorizontal) {- return {insetInlineStart: '0%', width: insetPosition(p)};- }- return {bottom: '0%', height: insetPosition(p)};- })();+ // The filled range's ends as progress: it ends at the thumb centers. So it+ // uses the same inset travel as the thumbs (see styles.fillClip).+ const fillStart = isRange ? getPercent(values[0], min, max) / 100 : 0;+ const fillEnd = getPercent(values[isRange ? 1 : 0], min, max) / 100;+ const fillStyle: FillStyle = {[FILL_START]: fillStart, [FILL_END]: fillEnd};// Text value displayconst textDisplay =@@ -1305,95 +1675,132 @@ export function Slider({ref, ...props}: SliderProps) {controlClassName,controlStyle,)}>- {/* Background track */}- <div- aria-hidden="true"- {...mergeProps(- themeProps('slider-track', {orientation}),- stylex.props(- styles.track,- isHorizontal- ? styles.trackHorizontal- : [styles.trackVertical, rtlStyles.centerInline('0px')],- ),- )}- />-- {/* Filled track */}- <div- aria-hidden="true"- {...mergeProps(- stylex.props(- styles.filledTrack,- isHorizontal- ? styles.filledTrackHorizontal- : [styles.filledTrackVertical, rtlStyles.centerInline('0px')],- ),- {style: filledStyle},- )}- />+ <div {...stylex.props(styles.travelBox)}>+ {/* Background track */}+ <div+ aria-hidden="true"+ {...mergeProps(+ themeProps('slider-track', {orientation}),+ stylex.props(+ styles.track,+ isHorizontal+ ? styles.trackHorizontal+ : [styles.trackVertical, rtlStyles.centerInline('0px')],+ ),+ )}+ />- {/* Marks */}- {marks && (+ {/* Filled track */}<divaria-hidden="true"{...stylex.props(- styles.marksContainer,+ styles.fillClip,isHorizontal- ? styles.marksContainerHorizontal- : styles.marksContainerVertical,+ ? styles.fillClipHorizontal+ : [styles.fillClipVertical, rtlStyles.centerInline('0px')],)}>- {marks.map(mark => {- const percent = getPercent(mark.value, min, max);- const markPos = isHorizontal- ? {insetInlineStart: insetPosition(percent)}- : {bottom: insetPosition(percent)};- // Marks at or inside the filled region take the fill color:- // at or behind the thumb in single mode, between the thumbs- // in range mode.- const isFilled = isRange- ? mark.value >= values[0] && mark.value <= values[1]- : mark.value <= values[0];- return (- <div key={mark.value}>- <div- data-testid="slider-mark"- data-mark-value={mark.value}- {...mergeProps(- stylex.props(- styles.mark,- isHorizontal- ? styles.markHorizontal- : styles.markVertical,- isFilled && styles.markFilled,- ),- {style: markPos},- )}- />- {mark.label && (- <span- data-testid="slider-mark-label"+ <div+ ref={fillMoverRef}+ {...mergeProps(+ stylex.props(+ styles.fillMover,+ isRange &&+ (isHorizontal+ ? [+ styles.fillMoverRangeHorizontal,+ styles.fillMoverRangeStartHorizontal,+ ]+ : [+ styles.fillMoverRangeVertical,+ styles.fillMoverRangeStartVertical,+ ]),+ ),+ {style: fillStyle},+ )}>+ <div+ ref={fillRef}+ {...mergeProps(+ stylex.props(+ styles.filledTrack,+ isHorizontal+ ? styles.filledTrackHorizontal+ : styles.filledTrackVertical,+ isRange+ ? isHorizontal+ ? styles.filledTrackRangeHorizontal+ : styles.filledTrackRangeVertical+ : isHorizontal+ ? styles.filledTrackSingleHorizontal+ : styles.filledTrackSingleVertical,+ ),+ {style: fillStyle},+ )}+ />+ </div>+ </div>++ {/* Marks */}+ {marks && (+ <div+ aria-hidden="true"+ {...stylex.props(+ styles.marksContainer,+ isHorizontal+ ? styles.marksContainerHorizontal+ : styles.marksContainerVertical,+ )}>+ {marks.map(mark => {+ const percent = getPercent(mark.value, min, max);+ const markPos = isHorizontal+ ? {insetInlineStart: insetPosition(percent)}+ : {bottom: insetPosition(percent)};+ // Marks at or inside the filled region take the fill color:+ // at or behind the thumb in single mode, between the thumbs+ // in range mode.+ const isFilled = isRange+ ? mark.value >= values[0] && mark.value <= values[1]+ : mark.value <= values[0];+ return (+ <div key={mark.value}>+ <div+ data-testid="slider-mark"data-mark-value={mark.value}{...mergeProps(stylex.props(- styles.markLabel,+ styles.mark,isHorizontal- ? styles.markLabelHorizontal- : styles.markLabelVertical,+ ? styles.markHorizontal+ : styles.markVertical,+ isFilled && styles.markFilled,),{style: markPos},- )}>- {mark.label}- </span>- )}- </div>- );- })}- </div>- )}+ )}+ />+ {mark.label && (+ <span+ data-testid="slider-mark-label"+ data-mark-value={mark.value}+ {...mergeProps(+ stylex.props(+ styles.markLabel,+ isHorizontal+ ? styles.markLabelHorizontal+ : styles.markLabelVertical,+ ),+ {style: markPos},+ )}>+ {mark.label}+ </span>+ )}+ </div>+ );+ })}+ </div>+ )}- {/* Thumbs */}- {values.map((_, i) => renderThumb(i))}+ {/* Thumbs */}+ {values.map((_, i) => renderThumb(i))}+ </div></div>{textDisplay}diff --git a/packages/core/src/Slider/SliderDocComment.test.ts b/packages/core/src/Slider/SliderDocComment.test.tsnew file mode 100644index 0000000000..b89b9c87ae--- /dev/null+++ b/packages/core/src/Slider/SliderDocComment.test.ts@@ -0,0 +1,45 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SliderDocComment.test.ts+ * @input Slider.tsx's source, parsed with the TypeScript compiler+ * @output Checks that Slider's doc comment attaches to `export function+ * Slider`, with its summary and its example+ * @position Test for Slider's public documentation: the comment above the+ * component is its emitted declaration's description and the Storybook+ * docs page's introduction. So a helper declared between the two takes it+ */++import {readFileSync} from 'node:fs';+import path from 'node:path';+import ts from 'typescript';+import {describe, expect, it} from 'vitest';++describe('Slider’s doc comment', () => {+ it('attaches to the exported component, with its summary and example', () => {+ const file = path.resolve(__dirname, 'Slider.tsx');+ const source = ts.createSourceFile(+ file,+ readFileSync(file, 'utf8'),+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+ );+ const slider = source.statements.find(+ (statement): statement is ts.FunctionDeclaration =>+ ts.isFunctionDeclaration(statement) &&+ statement.name?.text === 'Slider',+ );+ expect(slider).toBeDefined();+ if (slider == null) {+ return;+ }+ // The comment that documents a declaration is the last JSDoc block+ // directly above it.+ const doc = ts.getJSDocCommentsAndTags(slider).filter(ts.isJSDoc).at(-1);+ expect(ts.getTextOfJSDocComment(doc?.comment)).toMatch(+ /^A slider component for selecting numeric values or ranges\./,+ );+ expect(doc?.tags?.some(tag => tag.tagName.text === 'example')).toBe(true);+ });+});diff --git a/packages/core/src/Slider/__tests__/SliderFinePointer.interaction.browser.spec.ts b/packages/core/src/Slider/__tests__/SliderFinePointer.interaction.browser.spec.tsnew file mode 100644index 0000000000..dc28c4318c--- /dev/null+++ b/packages/core/src/Slider/__tests__/SliderFinePointer.interaction.browser.spec.ts@@ -0,0 +1,378 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file SliderFinePointer.interaction.browser.spec.ts+ * @input The built Storybook's Slider stories in a desktop context (no touch,+ * not mobile: a fine primary pointer), driven by Playwright's mouse+ * @output Proofs that Slider's gestures attach for every pointer+ * (`spec:AST-094` FR43): a mouse drag on a thumb pans, claiming after+ * FR19's 10 px. Each gesture element keeps one passive `pointerdown`+ * listener and the gesture host listens on the page only during a press+ * (FR24). And the touch targets stay coarse-only.+ * @position Browser proof beside SliderTouch.interaction.browser.spec.ts,+ * which drives a finger under phone emulation.+ */++import {expect, test, type Locator, type Page} from '@playwright/test';+import {+ openStory,+ WHEEL_SKIP,+ webInputDriver,+ withStorybook,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++// A desktop context: the primary pointer is fine (a mouse).+test.use({+ isMobile: false,+ hasTouch: false,+ // WebKit takes wheel input only in a desktop context at scale 1.+ deviceScaleFactor: 1,+ viewport: {width: 800, height: 600},+});++/** UIKit's pan hysteresis, which governs every claim (`spec:AST-094` FR19). */+const HYSTERESIS = 10;++/** One listener registration, as the page recorded it. */+interface Registration {+ readonly type: string;+ readonly passive: boolean;+}++/**+ * Records every listener the page adds and removes, before its scripts run.+ * Then the gesture host's listeners can be read off each element and the+ * document.+ */+async function recordListeners(page: Page): Promise<void> {+ await page.addInitScript(() => {+ interface Entry {+ target: EventTarget;+ type: string;+ listener: unknown;+ capture: boolean;+ passive: boolean;+ removed: boolean;+ }+ const log: Entry[] = [];+ (window as unknown as {__listeners: Entry[]}).__listeners = log;+ const flags = (options: boolean | AddEventListenerOptions | undefined) =>+ typeof options === 'boolean'+ ? {capture: options, passive: false}+ : {+ capture: Boolean(options?.capture),+ passive: Boolean(options?.passive),+ };+ const add = EventTarget.prototype.addEventListener;+ const remove = EventTarget.prototype.removeEventListener;+ EventTarget.prototype.addEventListener = function (+ type: string,+ listener: EventListenerOrEventListenerObject | null,+ options?: boolean | AddEventListenerOptions,+ ) {+ log.push({+ target: this,+ type,+ listener,+ removed: false,+ ...flags(options),+ });+ return add.call(this, type, listener, options);+ };+ EventTarget.prototype.removeEventListener = function (+ type: string,+ listener: EventListenerOrEventListenerObject | null,+ options?: boolean | EventListenerOptions,+ ) {+ const {capture} = flags(options);+ for (const entry of log) {+ if (+ !entry.removed &&+ entry.target === this &&+ entry.type === type &&+ entry.listener === listener &&+ entry.capture === capture+ ) {+ entry.removed = true;+ }+ }+ return remove.call(this, type, listener, options);+ };+ });+}++/**+ * The passive pointer listeners live on `element` now: the gesture host's+ * (other features keep their own, such as the value tooltip's hover).+ */+async function pointerListenersOn(element: Locator): Promise<Registration[]> {+ return element.evaluate(node =>+ (+ window as unknown as {+ __listeners: {+ target: EventTarget;+ type: string;+ passive: boolean;+ removed: boolean;+ }[];+ }+ ).__listeners+ .filter(+ entry =>+ !entry.removed &&+ entry.passive &&+ entry.target === node &&+ entry.type.startsWith('pointer'),+ )+ .map(({type, passive}) => ({type, passive})),+ );+}++/**+ * The passive pointer listeners live on the document and the window now (the+ * gesture host's; Storybook's own tools add others), each with its+ * registration's index. So one added during a press can be told from a+ * listener of the same type that was already there.+ */+async function pageListeners(+ page: Page,+): Promise<{id: number; type: string}[]> {+ return page.evaluate(() =>+ (+ window as unknown as {+ __listeners: {+ target: EventTarget;+ type: string;+ passive: boolean;+ removed: boolean;+ }[];+ }+ ).__listeners.flatMap((entry, id) =>+ !entry.removed &&+ entry.passive &&+ (entry.target === document || entry.target === window) &&+ entry.type.startsWith('pointer')+ ? [{id, type: entry.type}]+ : [],+ ),+ );+}++async function openSlider(page: Page, storyId: string, name?: string) {+ await openStory(page, storybook(), storyId);+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ const thumb =+ name == null+ ? page.getByRole('slider').first()+ : page.getByRole('slider', {name});+ await expect(thumb).toBeVisible();+ const control = thumb.locator(+ 'xpath=ancestor::*[contains(@class, "astryx-slider-control")][1]',+ );+ const center = async () => {+ const box = await thumb.boundingBox();+ if (box == null) {+ throw new Error('no thumb box');+ }+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};+ };+ const value = async () => Number(await thumb.getAttribute('aria-valuenow'));+ const length = await control.evaluate(element =>+ parseFloat(getComputedStyle(element).width),+ );+ return {thumb, control, center, value, length};+}++test('under a fine pointer the thumb and the track each keep one passive pointerdown listener, the host listens on the page only during a press, and no touch target renders (spec:AST-094 FR24, FR43)', async ({+ page,+}) => {+ await recordListeners(page);+ const {thumb, control, center} = await openSlider(+ page,+ 'core-slider--touch-tracking',+ 'Brightness',+ );+ // The thumb's pan and the track's tap attach for a mouse too (FR43): each+ // element listens with one passive pointerdown and nothing else (FR24).+ await expect+ .poll(async () => pointerListenersOn(thumb))+ .toEqual([{type: 'pointerdown', passive: true}]);+ expect(await pointerListenersOn(control)).toEqual([+ {type: 'pointerdown', passive: true},+ ]);+ // The 48 px touch target, the thumb's `::before`, stays coarse-only.+ expect(+ await thumb.evaluate(+ element => getComputedStyle(element, '::before').content,+ ),+ ).toBe('none');+ // At rest the host adds nothing to the page. A press adds its page+ // listeners, and the release removes them.+ const atRest = await pageListeners(page);+ const restIds = new Set(atRest.map(({id}) => id));+ const at = await center();+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ const added = (await pageListeners(page))+ .filter(({id}) => !restIds.has(id))+ .map(({type}) => type);+ expect(added).toEqual(expect.arrayContaining(['pointermove', 'pointerup']));+ await page.mouse.up();+ await expect.poll(async () => pageListeners(page)).toEqual(atRest);+});++test('a mouse drag on a thumb pans: the value holds through the 10 px hysteresis, then follows the pointer’s travel over the track length (spec:AST-094 FR43, FR19)', async ({+ page,+}) => {+ const {control, center, value, length} = await openSlider(+ page,+ 'core-slider--default',+ );+ // The host writes the track's touch-action for every pointer (FR18), so+ // its mark shows that the slider's gestures are attached.+ await expect+ .poll(async () =>+ control.evaluate(element =>+ element.getAttribute('data-astryx-touch-action'),+ ),+ )+ .toBe('manipulation');+ const start = await value();+ const at = await center();+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ // Inside the hysteresis nothing claims the drag. So the value holds.+ await page.mouse.move(at.x + HYSTERESIS - 4, at.y, {steps: 3});+ expect(await value()).toBe(start);+ // Past it the value follows the travel beyond the claim, as UISlider's.+ // The value renders after the move's frame. So the reads wait for it.+ for (const travel of [30, 60]) {+ await page.mouse.move(at.x + travel, at.y, {steps: 5});+ await expect+ .poll(value)+ .toBe(Math.round(start + ((travel - HYSTERESIS) * 100) / length));+ }+ await page.mouse.up();+});++test('a right click on the track moves nothing and paints nothing: only a primary click presses (spec:AST-094 FR43)', async ({+ page,+}) => {+ const {thumb, control, value} = await openSlider(+ page,+ 'core-slider--default',+ );+ await expect+ .poll(async () =>+ control.evaluate(element =>+ element.getAttribute('data-astryx-touch-action'),+ ),+ )+ .toBe('manipulation');+ const paint = async () =>+ thumb.evaluate(element => getComputedStyle(element).backgroundImage);+ const start = await value();+ const box = await control.boundingBox();+ if (box == null) {+ throw new Error('no control');+ }+ const at = {x: box.x + box.width * 0.2, y: box.y + box.height / 2};+ await page.mouse.move(at.x, at.y);+ // A right click is the page's context request (FR43), not a press.+ await page.mouse.down({button: 'right'});+ expect(await paint()).toBe('none');+ await page.mouse.up({button: 'right'});+ expect(await value()).toBe(start);+ // A primary click there still sets the value.+ await page.mouse.click(at.x, at.y);+ expect(await value()).toBeLessThan(start);+});++test('a wheel or a trackpad’s scroll over a thumb leaves the value and the page keeps it, in either direction: a control’s thumb is no pan', async ({+ page,+}) => {+ const driver = await webInputDriver(page);+ test.skip(!driver.wheels, WHEEL_SKIP);+ await recordListeners(page);+ const {thumb, control, center, value} = await openSlider(+ page,+ 'core-slider--default',+ );+ await expect+ .poll(async () =>+ control.evaluate(element =>+ element.getAttribute('data-astryx-touch-action'),+ ),+ )+ .toBe('manipulation');+ // The thumb listens for no wheel (spec:AST-094 FR24).+ expect(+ await thumb.evaluate(node =>+ (+ window as unknown as {+ __listeners: {target: EventTarget; type: string; removed: boolean}[];+ }+ ).__listeners.some(+ entry =>+ !entry.removed && entry.target === node && entry.type === 'wheel',+ ),+ ),+ ).toBe(false);+ // Every wheel reaches the page unprevented: the page scrolls as it would.+ await page.evaluate(() => {+ const w = window as unknown as {__wheels: boolean[]};+ w.__wheels = [];+ window.addEventListener(+ 'wheel',+ event => {+ w.__wheels.push(event.defaultPrevented);+ },+ {passive: true},+ );+ });+ const prevented = async () =>+ page.evaluate(() =>+ (window as unknown as {__wheels: boolean[]}).__wheels.some(Boolean),+ );+ /** A wheel gesture ends after a quiet spell (100 ms): wait it out. */+ const settle = async () => page.waitForTimeout(250);+ const start = await value();+ const at = await center();+ // A wheel's vertical notch, a horizontal notch (Shift and the wheel) and+ // a trackpad's horizontal scroll: none moves the value.+ await driver.wheel({x: at.x, y: at.y, dy: 100});+ await settle();+ await driver.wheel({x: at.x, y: at.y, dx: -100});+ await settle();+ for (let step = 0; step < 10; step += 1) {+ await driver.wheel({x: at.x, y: at.y, dx: -6});+ }+ await settle();+ expect(await value()).toBe(start);+ expect(await prevented()).toBe(false);+});++test('a mouse drag that starts off the travel still moves the thumb, by its travel along it (spec:AST-094 FR43)', async ({+ page,+}) => {+ const {center, value, length} = await openSlider(+ page,+ 'core-slider--default',+ );+ const start = await value();+ const at = await center();+ await page.mouse.move(at.x, at.y);+ await page.mouse.down();+ // The first 12 px run straight across the travel. A mouse's pan claims+ // after the same 10 px in any direction: a mouse has no page scroll to+ // yield to.+ await page.mouse.move(at.x, at.y + 12, {steps: 3});+ // Then 60 px along it: the threshold lies across the travel. So all 60+ // count.+ await page.mouse.move(at.x + 60, at.y + 12, {steps: 6});+ await expect.poll(value).toBe(Math.round(start + (60 * 100) / length));+ await page.mouse.up();+});diff --git a/packages/core/src/Slider/__tests__/SliderGeometry.a11y.chromium.spec.ts b/packages/core/src/Slider/__tests__/SliderGeometry.a11y.chromium.spec.tsnew file mode 100644index 0000000000..c69905e6a2--- /dev/null+++ b/packages/core/src/Slider/__tests__/SliderGeometry.a11y.chromium.spec.ts@@ -0,0 +1,486 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SliderGeometry.a11y.chromium.spec.ts+ * @input Built Slider stories in real Chromium, under LTR, RTL and mixed-direction regions, and vertical+ * @output Browser evidence that thumbs and fills sit where their values put them and never leave the control, padding included. The value tooltip anchors to a box that layout places at the value. A drag of a slider that displays no value lays out nothing per move+ * @position Slider geometry proof. jsdom computes neither container units nor translate, so placement is checked here+ */++import {expect, test, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++// Which direction the slider's own region reads in (Storybook's direction+// global sets it on the story's wrapper), and how the page around it is set.+// The mixed cases are where a flip keyed on any RTL ancestor, rather than on+// the element's own direction, puts thumbs outside the control.+const REGIONS = [+ {name: 'LTR page', page: 'ltr', region: 'ltr', rtl: false},+ {name: 'RTL page', page: 'rtl', region: 'rtl', rtl: true},+ {name: 'LTR region of an RTL page', page: 'rtl', region: 'ltr', rtl: false},+ {name: 'RTL region of an LTR page', page: 'ltr', region: 'rtl', rtl: true},+] as const;++const TOLERANCE = 1;++async function mount(+ page: Page,+ storyId: string,+ pageDir: string,+ regionDir: string,+) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${storyId}&viewMode=story&globals=direction:${regionDir}`,+ );+ await page.locator('.astryx-slider-control').first().waitFor();+ await page.evaluate(pageDirection => {+ document.documentElement.dir = pageDirection;+ }, pageDir);+ await page.evaluate(+ async () =>+ new Promise(resolve => requestAnimationFrame(() => resolve(null))),+ );+}++interface Geometry {+ control: {left: number; right: number};+ thumbs: {left: number; right: number; center: number}[];+ fill: {left: number; right: number} | null;+}++async function measure(page: Page): Promise<Geometry> {+ return page.evaluate(() => {+ const control = document.querySelector<HTMLElement>(+ '.astryx-slider-control',+ );+ if (!control) {+ throw new Error('missing slider control');+ }+ const c = control.getBoundingClientRect();+ const thumbs = Array.from(+ control.querySelectorAll<HTMLElement>('[role="slider"]'),+ ).map(thumb => {+ const r = thumb.getBoundingClientRect();+ return {left: r.left, right: r.right, center: (r.left + r.right) / 2};+ });+ // The painted fill is the bar clipped by its mover and by the fill clip.+ const bar = Array.from(+ control.querySelectorAll<HTMLElement>('[style*="--_slider-fill-end"]'),+ ).at(-1);+ let fill: {left: number; right: number} | null = null;+ if (bar) {+ let left = -Infinity;+ let right = Infinity;+ for (+ let node: HTMLElement | null = bar;+ node && node !== control;+ node = node.parentElement+ ) {+ const r = node.getBoundingClientRect();+ left = Math.max(left, r.left);+ right = Math.min(right, r.right);+ }+ fill = right > left ? {left, right} : {left, right: left};+ }+ return {control: {left: c.left, right: c.right}, thumbs, fill};+ });+}++function expectInside(g: Geometry, label: string) {+ for (const thumb of g.thumbs) {+ expect(thumb.left, `${label}: thumb left edge`).toBeGreaterThanOrEqual(+ g.control.left - TOLERANCE,+ );+ expect(thumb.right, `${label}: thumb right edge`).toBeLessThanOrEqual(+ g.control.right + TOLERANCE,+ );+ }+}++for (const region of REGIONS) {+ test(`a single slider's thumb and fill follow its value: ${region.name}`, async ({+ page,+ }) => {+ await mount(page, 'core-slider--default', region.page, region.region);+ const thumb = page.getByRole('slider');+ const startEdge = (g: Geometry) =>+ region.rtl ? g.control.right : g.control.left;++ // The story starts at 50: the thumb is centred on the control.+ let g = await measure(page);+ expectInside(g, 'value 50');+ const mid = (g.control.left + g.control.right) / 2;+ expect(Math.abs(g.thumbs[0].center - mid)).toBeLessThanOrEqual(TOLERANCE);++ await thumb.focus();+ await page.keyboard.press('Home');+ g = await measure(page);+ expectInside(g, 'value 0');+ // At the minimum the thumb sits flush with the start edge, inside it.+ const atMin = region.rtl ? g.thumbs[0].right : g.thumbs[0].left;+ expect(Math.abs(atMin - startEdge(g))).toBeLessThanOrEqual(TOLERANCE);++ await page.keyboard.press('End');+ g = await measure(page);+ expectInside(g, 'value 100');+ const endEdge = region.rtl ? g.control.left : g.control.right;+ const atMax = region.rtl ? g.thumbs[0].left : g.thumbs[0].right;+ expect(Math.abs(atMax - endEdge)).toBeLessThanOrEqual(TOLERANCE);++ // The fill runs from the start edge to the thumb's center.+ const fill = g.fill;+ if (fill == null) {+ throw new Error('missing fill');+ }+ const fillStart = region.rtl ? fill.right : fill.left;+ const fillEnd = region.rtl ? fill.left : fill.right;+ expect(Math.abs(fillStart - startEdge(g))).toBeLessThanOrEqual(TOLERANCE);+ expect(Math.abs(fillEnd - g.thumbs[0].center)).toBeLessThanOrEqual(+ TOLERANCE,+ );+ });++ test(`a range's thumbs and fill follow its values: ${region.name}`, async ({+ page,+ }) => {+ await mount(page, 'core-slider--range', region.page, region.region);+ const g = await measure(page);+ expectInside(g, 'range 20-80');+ expect(g.thumbs).toHaveLength(2);+ const [lower, upper] = g.thumbs;+ // The lower value sits nearer the region's start edge.+ if (region.rtl) {+ expect(lower.center).toBeGreaterThan(upper.center);+ } else {+ expect(lower.center).toBeLessThan(upper.center);+ }+ // The fill spans exactly between the two thumbs' centers.+ const fill = g.fill;+ if (fill == null) {+ throw new Error('missing fill');+ }+ const span = [lower.center, upper.center].sort((a, b) => a - b);+ expect(Math.abs(fill.left - span[0])).toBeLessThanOrEqual(TOLERANCE);+ expect(Math.abs(fill.right - span[1])).toBeLessThanOrEqual(TOLERANCE);+ });+}++// Moving the thumbs and the fill is a translate in container units. So a+// drag of a slider that displays no value lays out nothing per move. A+// value tooltip or text display still lays out as its text changes.+interface VerticalGeometry {+ control: {top: number; bottom: number};+ thumb: {top: number; bottom: number; center: number};+ fill: {top: number; bottom: number} | null;+}++async function measureVertical(page: Page): Promise<VerticalGeometry> {+ return page.evaluate(() => {+ const control = document.querySelector<HTMLElement>(+ '.astryx-slider-control',+ );+ const thumbEl = control?.querySelector<HTMLElement>('[role="slider"]');+ if (!control || !thumbEl) {+ throw new Error('missing slider control or thumb');+ }+ const c = control.getBoundingClientRect();+ const t = thumbEl.getBoundingClientRect();+ const bar = Array.from(+ control.querySelectorAll<HTMLElement>('[style*="--_slider-fill-end"]'),+ ).at(-1);+ let fill: {top: number; bottom: number} | null = null;+ if (bar) {+ let top = -Infinity;+ let bottom = Infinity;+ for (+ let node: HTMLElement | null = bar;+ node && node !== control;+ node = node.parentElement+ ) {+ const r = node.getBoundingClientRect();+ top = Math.max(top, r.top);+ bottom = Math.min(bottom, r.bottom);+ }+ fill = bottom > top ? {top, bottom} : {top: bottom, bottom};+ }+ return {+ control: {top: c.top, bottom: c.bottom},+ thumb: {top: t.top, bottom: t.bottom, center: (t.top + t.bottom) / 2},+ fill,+ };+ });+}++test("a vertical slider's thumb stays inside the control and its fill follows the value", async ({+ page,+}) => {+ await mount(page, 'core-slider--vertical-orientation', 'ltr', 'ltr');+ const thumb = page.getByRole('slider');+ await thumb.focus();++ // At the minimum the thumb sits flush with the bottom edge, inside it+ // (#5050: half of it used to hang below the control).+ await page.keyboard.press('Home');+ let g = await measureVertical(page);+ expect(Math.abs(g.thumb.bottom - g.control.bottom)).toBeLessThanOrEqual(+ TOLERANCE,+ );+ expect(g.thumb.top).toBeGreaterThanOrEqual(g.control.top - TOLERANCE);++ // At the maximum it sits flush with the top edge.+ await page.keyboard.press('End');+ g = await measureVertical(page);+ expect(Math.abs(g.thumb.top - g.control.top)).toBeLessThanOrEqual(TOLERANCE);+ expect(g.thumb.bottom).toBeLessThanOrEqual(g.control.bottom + TOLERANCE);++ // The fill runs from the bottom edge up to the thumb's center.+ const fill = g.fill;+ if (fill == null) {+ throw new Error('missing fill');+ }+ expect(Math.abs(fill.bottom - g.control.bottom)).toBeLessThanOrEqual(+ TOLERANCE,+ );+ expect(Math.abs(fill.top - g.thumb.center)).toBeLessThanOrEqual(TOLERANCE);+});++test('a drag lays out nothing per move when no value is displayed', async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-slider--default&viewMode=story&args=valueDisplay:none`,+ );+ const thumb = page.getByRole('slider');+ await thumb.waitFor();+ const box = await thumb.boundingBox();+ if (box == null) {+ throw new Error('no thumb');+ }+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('Performance.enable');+ const layouts = async () => {+ const {metrics} = await cdp.send('Performance.getMetrics');+ return metrics.find(metric => metric.name === 'LayoutCount')?.value ?? 0;+ };+ const x = box.x + box.width / 2;+ const y = box.y + box.height / 2;+ await page.mouse.move(x, y);+ await page.mouse.down();+ // The press itself may restyle (pressed paint, focus). Count the moves.+ await page.mouse.move(x + 2, y);+ await page.evaluate(+ async () =>+ new Promise(resolve => requestAnimationFrame(() => resolve(null))),+ );+ const before = await layouts();+ for (let i = 2; i <= 60; i++) {+ await page.mouse.move(x + i * 2, y);+ await page.evaluate(+ async () =>+ new Promise(resolve => requestAnimationFrame(() => resolve(null))),+ );+ }+ const after = await layouts();+ await page.mouse.up();+ expect(Number(await thumb.getAttribute('aria-valuenow'))).toBeGreaterThan(50);+ expect(after - before).toBe(0);+});++/**+ * The value tooltip's position anchor, measured as layout places it: by its+ * offsets, which no transform or `translate` moves. CSS anchor positioning+ * reads the anchor's box, and not every engine follows a `translate` on it.+ * Firefox anchors to the untranslated box, so the anchor itself must sit at+ * the value.+ */+async function measureTooltipAnchor(page: Page) {+ return page.evaluate(() => {+ const control = document.querySelector<HTMLElement>(+ '.astryx-slider-control',+ );+ const thumb = control?.querySelector<HTMLElement>('[role="slider"]');+ if (control == null || thumb == null) {+ throw new Error('missing slider');+ }+ const t = thumb.getBoundingClientRect();+ const anchors = Array.from(control.querySelectorAll<HTMLElement>('*'))+ .filter(element => {+ const name = getComputedStyle(element).getPropertyValue('anchor-name');+ return name !== '' && name !== 'none';+ })+ .map(element => {+ let x = 0;+ let y = 0;+ for (+ let node: HTMLElement | null = element;+ node != null;+ node = node.offsetParent as HTMLElement | null+ ) {+ x += node.offsetLeft;+ y += node.offsetTop;+ }+ return {+ x: x - window.scrollX + element.offsetWidth / 2,+ y: y - window.scrollY + element.offsetHeight / 2,+ };+ });+ const tooltip = Array.from(+ document.querySelectorAll<HTMLElement>('[role="tooltip"]'),+ ).find(element => element.getBoundingClientRect().width > 0);+ const tip = tooltip?.getBoundingClientRect();+ return {+ thumb: {x: (t.left + t.right) / 2, y: (t.top + t.bottom) / 2},+ anchors,+ tooltip: tip == null ? null : {x: (tip.left + tip.right) / 2},+ };+ });+}++for (const region of REGIONS) {+ test(`the value tooltip anchors where layout places the value: ${region.name}`, async ({+ page,+ }) => {+ await mount(page, 'core-slider--default', region.page, region.region);+ const thumb = page.getByRole('slider');+ await thumb.focus();+ let m = await measureTooltipAnchor(page);+ // At 50, away from the viewport's edges, the open tooltip is centred on+ // the thumb.+ expect(m.tooltip, 'the value tooltip is open').not.toBeNull();+ expect(Math.abs((m.tooltip?.x ?? 0) - m.thumb.x)).toBeLessThanOrEqual(+ TOLERANCE,+ );+ for (const key of ['Home', 'End', 'ArrowLeft']) {+ await page.keyboard.press(key);+ await page.evaluate(+ async () =>+ new Promise(resolve => requestAnimationFrame(() => resolve(null))),+ );+ m = await measureTooltipAnchor(page);+ expect(m.anchors, `${key}: one anchor`).toHaveLength(1);+ expect(+ Math.abs(m.anchors[0].x - m.thumb.x),+ `${key}: the anchor's layout box is centred on the thumb`,+ ).toBeLessThanOrEqual(TOLERANCE);+ expect(Math.abs(m.anchors[0].y - m.thumb.y)).toBeLessThanOrEqual(+ TOLERANCE,+ );+ }+ });+}++test('the value tooltip of a vertical slider anchors where layout places the value', async ({+ page,+}) => {+ await mount(page, 'core-slider--vertical-orientation', 'ltr', 'ltr');+ const thumb = page.getByRole('slider');+ await thumb.focus();+ for (const key of ['Home', 'End']) {+ await page.keyboard.press(key);+ await page.evaluate(+ async () =>+ new Promise(resolve => requestAnimationFrame(() => resolve(null))),+ );+ const m = await measureTooltipAnchor(page);+ expect(m.anchors, `${key}: one anchor`).toHaveLength(1);+ expect(Math.abs(m.anchors[0].x - m.thumb.x)).toBeLessThanOrEqual(TOLERANCE);+ expect(Math.abs(m.anchors[0].y - m.thumb.y)).toBeLessThanOrEqual(TOLERANCE);+ }+});++// The parts sit in the control's padding box (the track and the marks+// always did). So inline padding on the control, from a theme rule or+// `controlStyle`, moves nothing.+test('padding on the control keeps the thumb on the track, the fill and the marks', async ({+ page,+}) => {+ await mount(page, 'core-slider--with-marks', 'ltr', 'ltr');+ await page.addStyleTag({+ content: '.astryx-slider-control { padding-inline: 12px !important; }',+ });+ const thumb = page.getByRole('slider');+ await thumb.focus();+ await page.keyboard.press('End');+ await page.evaluate(+ async () =>+ new Promise(resolve => requestAnimationFrame(() => resolve(null))),+ );+ const g = await measure(page);+ expectInside(g, 'padded, at max');+ expect(Math.abs(g.thumbs[0].right - g.control.right)).toBeLessThanOrEqual(+ TOLERANCE,+ );+ expect(+ Math.abs((g.fill?.right ?? 0) - g.thumbs[0].center),+ ).toBeLessThanOrEqual(TOLERANCE);+ const lastMark = await page.evaluate(() => {+ const marks = Array.from(+ document.querySelectorAll<HTMLElement>('[data-testid="slider-mark"]'),+ );+ const r = marks.at(-1)?.getBoundingClientRect();+ return r == null ? null : (r.left + r.right) / 2;+ });+ expect(lastMark).not.toBeNull();+ expect(Math.abs((lastMark ?? 0) - g.thumbs[0].center)).toBeLessThanOrEqual(+ TOLERANCE,+ );+});++// Desktop keeps the pointer model: no touch targets, and the control's own+// touch-action and user-select. None of the touch presentation's inline+// styles show. The gesture host sets those only under a finger, while it is+// down.+test('a desktop slider keeps its pointer styles: no touch targets, no inline touch styles', async ({+ page,+}) => {+ await mount(page, 'core-slider--default', 'ltr', 'ltr');+ // Present and painted first: the thumb this test reads has its box.+ const thumbBox = await page.getByRole('slider').boundingBox();+ expect(thumbBox?.width ?? 0).toBeGreaterThan(0);+ expect(thumbBox?.height ?? 0).toBeGreaterThan(0);+ // A fine primary pointer in this context (a context without touch can still+ // match coarse under some configurations).+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ const styles = await page.evaluate(() => {+ const control = document.querySelector<HTMLElement>(+ '.astryx-slider-control',+ );+ const thumb = control?.querySelector<HTMLElement>('[role="slider"]');+ if (control == null || thumb == null) {+ throw new Error('missing slider');+ }+ const computed = getComputedStyle(control);+ return {+ hit: getComputedStyle(thumb, '::before').content,+ touchAction: computed.touchAction,+ userSelect: computed.userSelect,+ inline: [control, thumb].map(element =>+ ['touch-action', 'user-select', '-webkit-user-select'].map(name =>+ element.style.getPropertyValue(name),+ ),+ ),+ };+ });+ expect(styles.hit).toBe('none');+ expect(styles.touchAction).toBe('none');+ expect(styles.userSelect).toBe('none');+ expect(styles.inline.flat().filter(Boolean)).toEqual([]);+});diff --git a/packages/core/src/Slider/__tests__/SliderTouch.interaction.browser.spec.ts b/packages/core/src/Slider/__tests__/SliderTouch.interaction.browser.spec.tsnew file mode 100644index 0000000000..6cc65e1c60--- /dev/null+++ b/packages/core/src/Slider/__tests__/SliderTouch.interaction.browser.spec.ts@@ -0,0 +1,1493 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SliderTouch.interaction.browser.spec.ts+ * @input The built Slider stories ("Default", "Touch tracking", "In a+ * scrolling list"), real touch input and the interaction harness+ * @output Proofs of Slider's touch presentation: the 48 px target, the lift,+ * the travel past 10 px, the ends and the coast. They cover a track tap on+ * its lift, a slow or resting release, a catch, Reduce Motion, coincident+ * thumbs, RTL and a list's vertical swipe. The coast keeps moving through+ * a blocked main thread, and a drag lays out nothing per move.+ * @position Browser layer of Slider's touch presentation. The unit layers+ * are useSliderTouch.test.tsx and motion/uikit/slider.test.ts.+ */++import {expect, test, type Locator, type Page} from '@playwright/test';+import {+ blockMainThread,+ busyWindowProof,+ castStoryboard,+ compareCurve,+ CONTROL_RGB,+ countBetween,+ drag,+ flick,+ frames,+ holdAnimations,+ markElement,+ openStory,+ type Point,+ releaseAnimations,+ sampleCurve,+ springStep,+ startBusyControl,+ startScreencast,+ tap,+ type TouchDriver,+ touchDriver,+ type TouchScript,+ traceRendering,+ trackMarker,+ waitForRest,+ withStorybook,+ writeEvidence,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++/** UISlider, from the constants table (motion/uikit/slider.ts). */+const UISLIDER = {+ hysteresis: 10,+ hitTarget: 48,+ liftScale: 1.55,+ lift: {response: 0.215, dampingFraction: 0.6},+ release: {response: 0.4, dampingFraction: 1},+ projectionRate: 0.996,+ projectionShare: 0.4,+} as const;+/** Slider's thumb, px: its travel is the track minus one thumb. */+const THUMB = 20;+/** UISlider's touch target, px (`slider.thumbHitTarget`). */+const HIT_TARGET = 48;+/**+ * A thumb's touch target, in client px: the `::before` the touch+ * presentation draws around the thumb, or null where it draws none.+ */+async function touchTarget(thumb: Locator) {+ return thumb.evaluate(element => {+ const before = getComputedStyle(element, '::before');+ if (before.content === 'none' || before.content === 'normal') {+ return null;+ }+ // An absolute `::before` sits in the thumb's padding box.+ const box = element.getBoundingClientRect();+ const left = box.left + element.clientLeft;+ const top = box.top + element.clientTop;+ const px = (value: string) => parseFloat(value) || 0;+ return {+ left: left + px(before.left),+ top: top + px(before.top),+ right: left + element.clientWidth - px(before.right),+ bottom: top + element.clientHeight - px(before.bottom),+ };+ });+}++/**+ * A point on a whole CSS pixel. WebKit reports touch and pointer coordinates+ * in whole pixels (a tap scripted at x 50.42 arrives at 50; Chromium keeps+ * the fraction). So a case that computes a value from where a tap lands taps+ * a whole pixel, the coordinate every engine delivers as scripted.+ */+const onPixel = (point: {x: number; y: number}) => ({+ x: Math.round(point.x),+ y: Math.round(point.y),+});++interface Opened {+ driver: TouchDriver;+ thumb: Locator;+ control: Locator;+ /** The thumb's center, client px. */+ center: () => Promise<Point>;+ value: () => Promise<number>;+ /** The control's layout length along the travel, px. */+ length: number;+}++async function openSlider(+ page: Page,+ storyId: string,+ {+ name,+ args,+ direction,+ }: {+ name?: string;+ args?: Readonly<Record<string, string>>;+ direction?: 'rtl';+ } = {},+): Promise<Opened> {+ if (direction == null) {+ await openStory(page, storybook(), storyId, args);+ } else {+ await page.goto(+ `${storybook()}/iframe.html?id=${storyId}&viewMode=story&globals=direction:${direction}`,+ );+ await page.locator('#storybook-root > *').first().waitFor();+ await frames(page, 2);+ }+ const driver = await touchDriver(page);+ const thumb =+ name == null+ ? page.getByRole('slider').first()+ : page.getByRole('slider', {name});+ await expect(thumb).toBeVisible();+ // The touch presentation draws the touch targets after hydration, under a+ // coarse primary pointer (this phone emulation), on every engine.+ await expect.poll(async () => touchTarget(thumb)).not.toBeNull();+ const control = thumb.locator(+ 'xpath=ancestor::*[contains(@class, "astryx-slider-control")][1]',+ );+ // The touch presentation is live once its controller has attached. The+ // gesture host then marks the track with the touch-action its tap needs.+ // Any author rule outranks that rule, and the marked value is in force.+ await expect+ .poll(async () =>+ control.evaluate(element =>+ element.getAttribute('data-astryx-touch-action'),+ ),+ )+ .toBe('manipulation');+ expect(+ await control.evaluate(element => getComputedStyle(element).touchAction),+ ).toBe('manipulation');+ const length = await control.evaluate(element =>+ parseFloat(getComputedStyle(element).width),+ );+ const center = async () => {+ const box = await thumb.boundingBox();+ if (box == null) {+ throw new Error('no thumb box');+ }+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};+ };+ const value = async () => Number(await thumb.getAttribute('aria-valuenow'));+ return {driver, thumb, control, center, value, length};+}++interface Leg {+ /** Where the finger goes. */+ readonly to: Point;+ readonly durationMs: number;+ /** Rest after the leg (no events), ms. */+ readonly restMs?: number;+}++/**+ * One finger: press at `from`, move through `legs` at `hz`, lift. Returns+ * the script and the event index of each leg's last move (every frame+ * moves. So event indices follow frame indices. The press is event 0).+ */+function legs(+ from: Point,+ path: ReadonlyArray<Leg>,+ {hz = 60, liftAfterMs = 4}: {hz?: number; liftAfterMs?: number} = {},+): {script: TouchScript; ends: number[]} {+ const moves: {t: number; fingers: {id: number; x: number; y: number}[]}[] = [+ {t: 0, fingers: [{id: 0, ...from}]},+ ];+ const ends: number[] = [];+ let t = 0;+ let at = from;+ for (const leg of path) {+ const steps = Math.max(1, Math.round((leg.durationMs * hz) / 1000));+ for (let i = 1; i <= steps; i++) {+ moves.push({+ t: t + (leg.durationMs * i) / steps,+ fingers: [+ {+ id: 0,+ x: at.x + ((leg.to.x - at.x) * i) / steps,+ y: at.y + ((leg.to.y - at.y) * i) / steps,+ },+ ],+ });+ }+ ends.push(moves.length - 1);+ t += leg.durationMs + (leg.restMs ?? 0);+ at = leg.to;+ }+ moves.push({t: t + liftAfterMs, fingers: []});+ return {script: moves, ends};+}++/** Plays `script`, reading `read()` two frames after each event in `at`. */+async function playReading<T>(+ page: Page,+ driver: TouchDriver,+ script: TouchScript,+ at: ReadonlyArray<number>,+ read: () => Promise<T>,+): Promise<T[]> {+ const readings: T[] = [];+ await driver.play(script, {+ onEvent: async (_step, index) => {+ if (at.includes(index)) {+ await frames(page, 2);+ readings.push(await read());+ }+ },+ });+ return readings;+}++/**+ * The fill's mover. Only a coast animates it (a drag writes its styles and+ * the lift scales the thumb alone). So an animation inside it is the coast.+ */+function fillOf(thumb: Locator): Locator {+ return thumb+ .locator('xpath=ancestor::*[contains(@class, "astryx-slider-control")][1]')+ .locator('[style*="--_slider-fill-end"]')+ .first();+}++/**+ * UISlider's release coast, critically damped: where the thumb is `t` s after+ * the lift, starting at `from` with `velocity` toward `to` (px, px/s).+ */+function coastAt(from: number, to: number, velocity: number, t: number) {+ const omega = (2 * Math.PI) / UISLIDER.release.response;+ const offset = from - to;+ return to + (offset + (velocity + omega * offset) * t) * Math.exp(-omega * t);+}++/** WWDC18's projection, px of finger travel. */+function project(velocity: number): number {+ return (+ ((velocity / 1000) * UISLIDER.projectionRate) /+ (1 - UISLIDER.projectionRate)+ );+}++/** The value UISlider reports for `travel` px of finger past touch-down. */+function trackedValue(+ start: number,+ travel: number,+ length: number,+ range = 100,+): number {+ const translation = Math.max(0, Math.abs(travel) - UISLIDER.hysteresis);+ return start + (Math.sign(travel) * translation * range) / length;+}++test('a tap on the track sets the value when it lifts and the thumb springs there; the thumb takes a finger through a target larger than it', async ({+ page,+}) => {+ const {driver, thumb, center, value, length} = await openSlider(+ page,+ 'core-slider--default',+ );+ const start = await value();+ const at = await center();+ const hit = await touchTarget(thumb);+ expect(hit == null ? 0 : hit.right - hit.left).toBeCloseTo(+ UISLIDER.hitTarget,+ 0,+ );+ expect(hit == null ? 0 : hit.bottom - hit.top).toBeCloseTo(+ UISLIDER.hitTarget,+ 0,+ );+ // 20 px beside the thumb's center, inside its 48 px touch target: the+ // thumb takes the finger and lifts, and a tap there changes nothing.+ const beside = {x: at.x + 20, y: at.y};+ const [scale] = await playReading(+ page,+ driver,+ tap(beside, {holdMs: 500}),+ [0],+ async () => {+ await page.waitForTimeout(400);+ return thumb.evaluate(element => getComputedStyle(element).scale);+ },+ );+ expect(Number(scale)).toBeCloseTo(UISLIDER.liftScale, 2);+ await frames(page, 4);+ expect(await value()).toBe(start);+ // Far on the track: nothing while the finger is down. On the lift the+ // value is the tap's, and the thumb springs there. A drag is not the only+ // pointer way (WCAG 2.5.7), though UISlider itself ignores the tap.+ const far = onPixel({x: at.x + length * 0.3, y: at.y});+ const [held] = await playReading(+ page,+ driver,+ tap(far, {holdMs: 300}),+ [0],+ async () => {+ await page.waitForTimeout(150);+ return value();+ },+ );+ expect(held).toBe(start);+ const box = await thumb+ .locator('xpath=ancestor::*[contains(@class, "astryx-slider-control")][1]')+ .boundingBox();+ if (box == null) {+ throw new Error('no control');+ }+ const expected = Math.round(+ ((far.x - box.x - THUMB / 2) / (box.width - THUMB)) * 100,+ );+ // Mid-spring the thumb is on its way (a compositor animation), not there.+ await page.waitForTimeout(60);+ expect(+ await thumb.evaluate(element => element.getAnimations().length),+ ).toBeGreaterThan(0);+ await waitForRest(thumb);+ await frames(page, 4);+ expect(await value()).toBe(expected);+});++test('the value follows the pan’s travel over the track length, past the 10 px hysteresis', async ({+ page,+}, testInfo) => {+ const {driver, center, value, length} = await openSlider(+ page,+ 'core-slider--default',+ );+ const start = await value();+ const at = await center();+ const travels = [6, 10, 30, 60, 90];+ let previous = 0;+ const path: Leg[] = travels.map(travel => {+ const leg = {+ to: {x: at.x + travel, y: at.y},+ durationMs: Math.max(17, (travel - previous) * 8),+ restMs: 120,+ };+ previous = travel;+ return leg;+ });+ const {script, ends} = legs(at, path);+ const values = await playReading(page, driver, script, ends, value);+ const readings = travels.map((travel, i) => ({+ travel,+ value: values[i],+ expected: Math.round(trackedValue(start, travel, length)),+ }));+ await page.waitForTimeout(800);+ await writeEvidence(+ 'tracking/slider-pan-travel',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {length, readings},+ null,+ 1,+ ),+ },+ testInfo,+ );+ for (const reading of readings) {+ expect(reading.value, JSON.stringify(reading)).toBe(reading.expected);+ }+});++test('past an end the value waits for the finger to come back', async ({+ page,+}) => {+ const {driver, center, value, length} = await openSlider(+ page,+ 'core-slider--default',+ );+ const start = await value();+ const at = await center();+ // To the max end and 60 px past it, then 40 px back: still at the max.+ const toEnd = ((100 - start) / 100) * length + UISLIDER.hysteresis;+ const past = {x: at.x + toEnd + 60, y: at.y};+ const back = {x: past.x - 40, y: at.y};+ const {script, ends} = legs(at, [+ {to: past, durationMs: 500, restMs: 100},+ {to: back, durationMs: 300, restMs: 200},+ ]);+ const values = await playReading(page, driver, script, ends, value);+ expect(values).toEqual([100, 100]);+});++test('a release coasts on UIKit’s spring to 0.4 of the momentum projection, then onChangeEnd reports', async ({+ page,+}, testInfo) => {+ const {driver, thumb, center, value, length} = await openSlider(+ page,+ 'core-slider--touch-tracking',+ {name: 'Brightness'},+ );+ // The release velocity is the script's 300 px/s only where the page gets+ // the script's timestamps. Injected touches carry their real dispatch+ // times. A scheduling gap of 40 ms or more before the lift then reads as a+ // resting finger. The release filter's stillness reset rightly starts no+ // coast then.+ test.skip(+ !driver.scriptedTimestamps,+ 'the release velocity needs the scripted timestamps (README: engine limits)',+ );+ const at = await center();+ const velocity = 300;+ // A steady 300 px/s for 120 ms (36 px), lifted while moving.+ const script = flick(at, {velocity: {x: velocity, y: 0}, durationMs: 120});+ const lastMove = script.length - 2;+ const [liftValue] = await playReading(+ page,+ driver,+ script,+ [lastMove],+ value,+ );+ // The thumb runs two animations from the lift: the drop's scale and the+ // coast's translate. The coast starts a few ms later, 2–3 ms here and more+ // under load. The harness counts sample times from the earliest held+ // start, so the samples are taken at the coast's own times: its offset+ // plus 0, 20, …+ const coast = (await holdAnimations(page, thumb)).find(held =>+ held.keyframes.some(keyframe => 'translate' in keyframe),+ );+ expect(coast, 'the coast plays on the compositor').toBeDefined();+ const coastOffset = coast?.offsetMs ?? 0;+ const times = Array.from({length: 31}, (_, i) => coastOffset + i * 20);+ const samples = await sampleCurve(thumb, times);+ await releaseAnimations(page);+ await waitForRest(thumb);+ await frames(page, 4);+ const range = 100;+ const travel = length - THUMB;+ const pxPerValue = travel / range;+ const finalValue = await value();+ // The release velocity is exactly the script's 300 px/s, and the target+ // follows from UIKit's projection.+ const target = Math.round(+ liftValue + (UISLIDER.projectionShare * project(velocity) * range) / length,+ );+ const fromPx = samples[0].transform.translateX;+ const toPx = fromPx + (target - liftValue) * pxPerValue;+ // The finger velocity in the thumb's px per second: travel ÷ length of it.+ const v0 =+ toPx === fromPx+ ? 0+ : ((velocity / length) * range * pxPerValue) / (toPx - fromPx);+ const comparison = compareCurve(+ samples.map(sample => ({+ t: sample.t - coastOffset,+ value: sample.transform.translateX,+ })),+ ms =>+ fromPx ++ (toPx - fromPx) *+ springStep(+ {+ response: UISLIDER.release.response,+ dampingFraction: 1,+ initialVelocity: v0,+ },+ ms,+ ),+ // Snapping the target to a whole value moves the end by up to half a+ // step.+ 0.75,+ );+ await writeEvidence(+ 'curves/slider-coast',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {+ velocity,+ length,+ liftValue,+ target,+ finalValue,+ comparison,+ },+ null,+ 1,+ ),+ },+ testInfo,+ );+ expect(finalValue).toBe(target);+ expect(finalValue).toBeGreaterThan(liftValue);+ expect(+ comparison.maxError,+ JSON.stringify(comparison.worst),+ ).toBeLessThanOrEqual(0.75);+ await expect(page.getByTestId('slider-change-end')).toHaveText(+ `Brightness ${target}`,+ );+ // Handed back: no inline translate left, the thumb where the CSS puts it.+ expect(await thumb.evaluate(element => element.style.translate)).toBe('');+});++test('the lifted thumb grows around its own center, as UISlider’s lens does', async ({+ page,+}) => {+ // UIKit's lens grows from 24 to 39 pt with its center fixed on the track+ // (UIKit lab, iOS 26.2 simulator). The thumb's centering must not scale+ // with the lift.+ for (const {storyId, name, args} of [+ {storyId: 'core-slider--touch-tracking', name: 'Brightness', args: {}},+ {+ storyId: 'core-slider--vertical-orientation',+ name: undefined,+ args: {valueDisplay: 'none'},+ },+ ]) {+ const {driver, thumb, center} = await openSlider(page, storyId, {+ name,+ args,+ });+ const rest = await thumb.boundingBox();+ if (rest == null) {+ throw new Error('no thumb');+ }+ const at = await center();+ const box = async () => {+ const b = await thumb.boundingBox();+ if (b == null) {+ throw new Error('no thumb');+ }+ return b;+ };+ const [midLift, lifted] = await playReading(+ page,+ driver,+ tap(at, {holdMs: 700}),+ [0],+ async () => {+ await page.waitForTimeout(60);+ const mid = await box();+ await page.waitForTimeout(450);+ return [mid, await box()] as const;+ },+ ).then(readings => readings[0]);+ for (const [label, b] of [+ ['mid-lift', midLift],+ ['lifted', lifted],+ ] as const) {+ expect(+ b.width,+ `${storyId} ${label}: the thumb is lifted`,+ ).toBeGreaterThan(rest.width + 2);+ expect(+ Math.abs(b.x + b.width / 2 - (rest.x + rest.width / 2)),+ `${storyId} ${label}: x center`,+ ).toBeLessThanOrEqual(0.5);+ expect(+ Math.abs(b.y + b.height / 2 - (rest.y + rest.height / 2)),+ `${storyId} ${label}: y center`,+ ).toBeLessThanOrEqual(0.5);+ }+ await page.waitForTimeout(700);+ }+});++test('a slow release does not coast: the value stays where the finger left it', async ({+ page,+}) => {+ const {driver, thumb, center, value} = await openSlider(+ page,+ 'core-slider--touch-tracking',+ {name: 'Brightness'},+ );+ const at = await center();+ // Past the 10 px threshold, then the last moves at 6 px/s. The projection,+ // 0.4 × 0.0996 s × 6 px/s or about 0.24 px, is under half a step.+ const quick = {x: at.x + 40, y: at.y};+ const {script, ends} = legs(+ at,+ [+ {to: quick, durationMs: 200},+ {to: {x: quick.x + 1.2, y: at.y}, durationMs: 200},+ ],+ {hz: 60},+ );+ const [atLift] = await playReading(page, driver, script, [ends[1]], value);+ await page.waitForTimeout(600);+ expect(await value()).toBe(atLift);+ // No coast ran: no translate animation, and the thumb is back on its CSS+ // position (the drop of its lift still runs on scale).+ expect(+ await thumb.evaluate(+ element =>+ element+ .getAnimations()+ .filter(animation =>+ (animation.effect as KeyframeEffect | null)+ ?.getKeyframes()+ .some(frame => 'translate' in frame),+ ).length,+ ),+ ).toBe(0);+ expect(await thumb.evaluate(element => element.style.translate)).toBe('');+ await expect(page.getByTestId('slider-change-end')).toHaveText(+ `Brightness ${atLift}`,+ );+});++test('a drag that rests 40 ms before the lift does not coast: the release filter’s stillness reset (AST-100 FR2)', async ({+ page,+}) => {+ const {driver, center, value} = await openSlider(+ page,+ 'core-slider--touch-tracking',+ {name: 'Brightness'},+ );+ const at = await center();+ // 60 px at 300 px/s, then 300 ms without a move. UIKit keeps the last+ // motion through a silent rest (a 312 ms rest still coasted 12.56 pt).+ // The one release filter every gesture shares reads zero once the finger+ // has been still for its stillness interval (40 ms, AST-100 FR2). So the+ // value stays where the finger left it.+ const {script, ends} = legs(+ at,+ [{to: {x: at.x + 60, y: at.y}, durationMs: 200, restMs: 300}],+ {hz: 60},+ );+ const [atLift] = await playReading(page, driver, script, [ends[0]], value);+ await page.waitForTimeout(900);+ expect(await value()).toBe(atLift);+});++test('Reduce Motion: no lift; a release keeps coasting and a track tap sets the value at once, with no cross-fade (design:reduced-motion DR2)', async ({+ page,+}) => {+ await page.emulateMedia({reducedMotion: 'reduce'});+ const {driver, thumb, center} = await openSlider(+ page,+ 'core-slider--touch-tracking',+ {name: 'Brightness'},+ );+ /** The thumb's opacity, scale, position and value each frame for `ms`. */+ const watch = async (ms: number) =>+ thumb.evaluate(async (element, duration) => {+ const samples: {+ t: number;+ opacity: number;+ scale: number;+ x: number;+ value: number;+ }[] = [];+ const start = performance.now();+ while (performance.now() - start < duration) {+ await new Promise(requestAnimationFrame);+ const style = getComputedStyle(element);+ samples.push({+ t: performance.now() - start,+ opacity: Number(style.opacity),+ scale: style.scale === 'none' ? 1 : Number(style.scale),+ x: element.getBoundingClientRect().x,+ value: Number(element.getAttribute('aria-valuenow')),+ });+ }+ return samples;+ }, ms);+ type Sample = Awaited<ReturnType<typeof watch>>[number];+ const opacities = (samples: ReadonlyArray<Sample>) =>+ samples.map(sample => sample.opacity);+ // A held thumb keeps its size: the press shows in its paint alone (DR1).+ const at = await center();+ const [held] = await playReading(+ page,+ driver,+ tap(at, {holdMs: 400}),+ [0],+ async () => watch(250),+ );+ expect(Math.max(...held.map(sample => sample.scale))).toBe(1);+ await frames(page, 6);+ // A flick's release: the momentum that continues the throw is direct+ // movement. So the thumb keeps travelling frame by frame past the lift's+ // value, at full opacity (DR2).+ const from = await center();+ const script = flick(from, {velocity: {x: 400, y: 0}, durationMs: 100});+ const [release] = await playReading(+ page,+ driver,+ script,+ [script.length - 1],+ async () => watch(500),+ );+ expect(Math.min(...opacities(release))).toBe(1);+ expect(Math.max(...release.map(sample => sample.scale))).toBe(1);+ const positions = new Set(release.map(sample => Math.round(sample.x * 4)));+ expect(positions.size).toBeGreaterThan(4);+ expect(release[release.length - 1].value).toBeGreaterThan(release[0].value);+ await frames(page, 6);+ // A tap on the track: an in-place value change. So the thumb lands on the+ // tap's value at once, at full opacity, with no travel between (DR2).+ const control = thumb.locator(+ 'xpath=ancestor::*[contains(@class, "astryx-slider-control")][1]',+ );+ const box = await control.boundingBox();+ if (box == null) {+ throw new Error('no control');+ }+ const target = onPixel({+ x: box.x + box.width * 0.1,+ y: box.y + box.height / 2,+ });+ const expected = Math.round(+ ((target.x - box.x - THUMB / 2) / (box.width - THUMB)) * 100,+ );+ const tapScript = tap(target);+ const [tapped] = await playReading(+ page,+ driver,+ tapScript,+ [tapScript.length - 1],+ async () => watch(320),+ );+ expect(Math.min(...opacities(tapped))).toBe(1);+ // At once: within two frames of the lift the value is the tap's. The thumb+ // never stands anywhere between its old place and its new one.+ expect(tapped[1].value).toBe(expected);+ const landed = tapped[tapped.length - 1].x;+ expect(+ tapped.slice(1).every(sample => Math.abs(sample.x - landed) < 0.5),+ ).toBe(true);+});++test('range thumbs closer than their touch targets split the gap: neither thumb’s hit area takes a touch on the other thumb (spec:AST-094 FR42)', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-slider--touch-tracking');+ // The touch driver emulates a touch screen: the touch targets render under+ // its coarse pointer.+ await touchDriver(page);+ const lower = page.getByRole('slider', {name: 'Minimum value'});+ const upper = page.getByRole('slider', {name: 'Maximum value'});+ await expect.poll(async () => touchTarget(lower)).not.toBeNull();+ await expect.poll(async () => touchTarget(upper)).not.toBeNull();+ const control = lower.locator(+ 'xpath=ancestor::*[contains(@class, "astryx-slider-control")][1]',+ );+ const length = await control.evaluate(element =>+ parseFloat(getComputedStyle(element).width),+ );+ // One step of the 0–100 range, in px along the travel.+ const pxPerStep = (length - THUMB) / 100;+ /** Puts the upper thumb `steps` above the lower one, with the keyboard. */+ const spread = async (steps: number) => {+ await upper.focus();+ await page.keyboard.press('Home');+ for (let i = 0; i < steps; i++) {+ await page.keyboard.press('ArrowRight');+ }+ await frames(page, 2);+ };+ const rectOf = async (locator: Locator) => {+ const box = await locator.boundingBox();+ if (box == null) {+ throw new Error('no box');+ }+ return {+ left: box.x,+ right: box.x + box.width,+ top: box.y,+ bottom: box.y + box.height,+ };+ };+ const targetOf = async (locator: Locator) => {+ const target = await touchTarget(locator);+ if (target == null) {+ throw new Error('no touch target');+ }+ return target;+ };+ const boxes = async () => ({+ lower: await rectOf(lower),+ upper: await rectOf(upper),+ lowerHit: await targetOf(lower),+ upperHit: await targetOf(upper),+ });+ /** Which thumb a touch at (x, y) lands on. */+ const thumbAt = async (x: number, y: number) =>+ page.evaluate(+ ([px, py]) => {+ const hit = document.elementFromPoint(px, py);+ const thumb = hit?.closest('[role="slider"]');+ return thumb == null+ ? null+ : Array.from(document.querySelectorAll('[role="slider"]')).indexOf(+ thumb,+ );+ },+ [x, y] as const,+ );+ const indexOfLower = await lower.evaluate(element =>+ Array.from(document.querySelectorAll('[role="slider"]')).indexOf(element),+ );+ // Present and painted first: both thumbs and both touch targets have+ // boxes. Where the thumbs have room, with centers at least a target apart,+ // each target is UISlider's full 48 px square. So the narrowed cases below+ // measure targets that exist.+ await expect(lower).toBeVisible();+ await expect(upper).toBeVisible();+ await spread(Math.round(80 / pxPerStep));+ {+ const roomy = await boxes();+ const lowerCenter = (roomy.lower.left + roomy.lower.right) / 2;+ const upperCenter = (roomy.upper.left + roomy.upper.right) / 2;+ expect(upperCenter - lowerCenter).toBeGreaterThanOrEqual(HIT_TARGET);+ for (const [thumbBox, hitBox] of [+ [roomy.lower, roomy.lowerHit],+ [roomy.upper, roomy.upperHit],+ ] as const) {+ expect(+ Math.abs(thumbBox.right - thumbBox.left - THUMB),+ ).toBeLessThanOrEqual(1);+ expect(+ Math.abs(hitBox.right - hitBox.left - HIT_TARGET),+ ).toBeLessThanOrEqual(1);+ expect(+ Math.abs(hitBox.bottom - hitBox.top - HIT_TARGET),+ ).toBeLessThanOrEqual(1);+ expect(+ Math.abs(+ (hitBox.left + hitBox.right) / 2 -+ (thumbBox.left + thumbBox.right) / 2,+ ),+ ).toBeLessThanOrEqual(1);+ }+ }+ // Overlapping thumbs (centers 14 px apart, under the 20 px thumb): a+ // finger on the lower thumb's exposed side takes the lower thumb.+ await spread(Math.max(1, Math.round(14 / pxPerStep)));+ let b = await boxes();+ const y = (b.lower.top + b.lower.bottom) / 2;+ expect(await thumbAt(b.lower.left + 3, y)).toBe(indexOfLower);+ // Thumbs 30 px apart (a 10 px gap, under the targets' 28 px of growth):+ // each hit area stops at half the gap. So the two meet in the middle.+ await spread(Math.max(1, Math.round(30 / pxPerStep)));+ b = await boxes();+ const middle = (b.lower.right + b.upper.left) / 2;+ expect(b.lowerHit.right).toBeLessThanOrEqual(middle + 0.5);+ expect(b.upperHit.left).toBeGreaterThanOrEqual(middle - 0.5);+ expect(b.lowerHit.right).toBeLessThanOrEqual(b.upper.left + 0.5);+ expect(b.upperHit.left).toBeGreaterThanOrEqual(b.lower.right - 0.5);+ expect(await thumbAt(middle - 2, y)).toBe(indexOfLower);+ expect(await thumbAt(middle + 2, y)).toBe(indexOfLower + 1);+});++test('a finger landing on a coasting thumb stops it where it is', async ({+ page,+}) => {+ // A scale of a thousand values: a value is a third of a px. So the coast+ // stays more than a value from its end for about 450 ms.+ const range = 1000;+ const {driver, thumb, control, center, value} = await openSlider(+ page,+ 'core-slider--touch-tracking',+ {name: 'Brightness', args: {max: String(range)}},+ );+ test.skip(+ !driver.scriptedTimestamps,+ 'the coast target needs the scripted release velocity (README: engine limits)',+ );+ expect(await thumb.getAttribute('aria-valuemin')).toBe('0');+ expect(await thumb.getAttribute('aria-valuemax')).toBe(String(range));+ // From the minimum, a fast throw: a coast over about 40% of the track,+ // never clamped.+ await thumb.focus();+ await page.keyboard.press('Home');+ await expect.poll(value).toBe(0);+ // The track's length as the slider measures it when the throw begins: the+ // story's value text beside the track takes width with each digit. So the+ // track is longer at 0 than it was at the story's first value.+ const length = await control.evaluate(element =>+ parseFloat(getComputedStyle(element).width),+ );+ const start = await value();+ const at = await center();+ const velocity = 1500;+ const throwScript = flick(at, {+ velocity: {x: velocity, y: 0},+ durationMs: 60,+ });+ // Where to aim: the coast this throw makes on the track as it is now.+ const aimLift = Math.round(+ trackedValue(start, (velocity * 60) / 1000, length, range),+ );+ const aimTarget = Math.round(+ aimLift + (UISLIDER.projectionShare * project(velocity) * range) / length,+ );+ const thumbPxPerValue = (length - THUMB) / range;+ const coastValue = (seconds: number) =>+ coastAt(+ aimLift * thumbPxPerValue,+ aimTarget * thumbPxPerValue,+ (velocity * (length - THUMB)) / length,+ seconds,+ ) / thumbPxPerValue;+ // The page reads its own moments, just before the slider handles them: a+ // capture listener on the window runs first. At the lift it reads the+ // value and the track's length. At the catch it reads whether the catch+ // landed on the thumb and whether the coast still ran. It also reads the+ // thumb's translate and box in the frame the catch lands in, and the+ // track's length then. The slider reads that frame in the same task.+ await thumb.evaluate(element => {+ type Marks = {+ liftAt?: number;+ liftValue?: number;+ liftLength?: number;+ catchAt?: number;+ coasting?: boolean;+ presentedPx?: number;+ drawnCenter?: number;+ trackLength?: number;+ onThumb?: boolean;+ };+ const marks: Marks = {};+ (window as unknown as {__sliderCatch: Marks}).__sliderCatch = marks;+ const track = element.closest('.astryx-slider-control');+ const fill = track?.querySelector('[style*="--_slider-fill-end"]');+ let presses = 0;+ window.addEventListener(+ 'pointerdown',+ event => {+ presses += 1;+ if (presses === 2) {+ marks.catchAt = performance.now();+ marks.presentedPx = Math.abs(+ parseFloat(getComputedStyle(element).translate) || 0,+ );+ const drawn = element.getBoundingClientRect();+ marks.drawnCenter = drawn.left + drawn.width / 2;+ marks.trackLength =+ track == null ? 0 : parseFloat(getComputedStyle(track).width);+ marks.onThumb = element.contains(event.target as Node);+ marks.coasting =+ fill+ ?.getAnimations({subtree: true})+ .some(animation => animation.playState === 'running') === true;+ }+ },+ {capture: true, passive: true},+ );+ window.addEventListener(+ 'pointerup',+ () => {+ if (marks.liftAt != null) {+ return;+ }+ marks.liftAt = performance.now();+ marks.liftValue = Number(element.getAttribute('aria-valuenow'));+ marks.liftLength =+ track == null ? 0 : parseFloat(getComputedStyle(track).width);+ },+ {capture: true, passive: true},+ );+ });+ // A finger lands 220 ms after the throw's lift has gone out, where the+ // coast has carried the thumb by then. Its own play starts once the+ // throw's has dispatched the lift. So a dispatch that stalls before the+ // lift delays the catch with it rather than sending it right behind. There+ // the thumb is within its 48 px target of that point from about 120 ms+ // after the lift to the coast's end. So a catch the page handles up to+ // about 100 ms early or 240 ms late still lands on it while the coast+ // moves.+ const catchMs = 220;+ const aimX = at.x + (coastValue(catchMs / 1000) - start) * thumbPxPerValue;+ await driver.play(throwScript);+ await page.waitForTimeout(catchMs);+ await driver.play(tap({x: aimX, y: at.y}, {holdMs: 200}));+ await page.waitForTimeout(700);+ const marks = await page.evaluate(+ () =>+ (+ window as unknown as {+ __sliderCatch: {+ liftAt?: number;+ liftValue?: number;+ liftLength?: number;+ catchAt?: number;+ coasting?: boolean;+ presentedPx?: number;+ drawnCenter?: number;+ trackLength?: number;+ onThumb?: boolean;+ };+ }+ ).__sliderCatch,+ );+ const {liftAt, liftValue, liftLength} = marks;+ const {catchAt, presentedPx, drawnCenter, trackLength} = marks;+ if (+ liftAt == null ||+ liftValue == null ||+ liftLength == null ||+ catchAt == null ||+ presentedPx == null ||+ drawnCenter == null ||+ trackLength == null+ ) {+ throw new Error(+ `the page saw no lift or no catch: ${JSON.stringify(marks)}`,+ );+ }+ // The value the catch's frame draws, on the track as it is then. The+ // story's value text took a digit during the coast and narrowed the+ // track, and the coast follows the track's own length.+ const presented = presentedPx / ((trackLength - THUMB) / range);+ // The coast's end, as the slider computes it at the lift: the value text+ // took digits during the drag. So the track was shorter than at the start.+ const target = Math.round(+ liftValue ++ (UISLIDER.projectionShare * project(velocity) * range) / liftLength,+ );+ expect(target).toBeLessThan(range);+ // The catch landed on the thumb while the coast moved: a value or more past+ // the lift and short of the coast's end. Otherwise this runner handed the+ // page the catch too early or too late, and a stop could not be told from+ // the coast.+ expect(+ marks.onThumb === true &&+ marks.coasting === true &&+ presented >= liftValue + 1 &&+ presented <= target - 1,+ `the page handled the catch ${(catchAt - liftAt).toFixed(0)} ms after the lift (${marks.onThumb === true ? 'on' : 'off'} the thumb, ${marks.coasting === true ? `the coast at ${presented.toFixed(2)} of ${liftValue} to ${target}` : 'no coast running'}): outside its moving window, the runner's timing, not the stop`,+ ).toBe(true);+ // The stop is where the catch's frame presents the thumb, to the nearest+ // value. It never jumps to a value the coast's model read at another+ // moment.+ const caught = await value();+ expect(+ Math.abs(caught - presented),+ `stopped at ${caught}, the catch's frame presents ${presented.toFixed(2)}`,+ ).toBeLessThanOrEqual(0.5);+ // And the thumb rests where it was drawn when the finger landed, to half a+ // value step. The stop and the stylesheet's position follow the track's+ // own length.+ const rest = await thumb.evaluate(element => {+ const rect = element.getBoundingClientRect();+ const track = element+ .closest('.astryx-slider-control')+ ?.getBoundingClientRect();+ return {+ center: rect.left + rect.width / 2,+ length: track?.width ?? 0,+ };+ });+ expect(+ Math.abs(rest.center - drawnCenter),+ `rests at ${rest.center.toFixed(2)} px, drawn at ${drawnCenter.toFixed(2)} px when caught`,+ ).toBeLessThanOrEqual((rest.length - THUMB) / range / 2);+ // The interrupted coast reports where it stopped, then the catching touch+ // ends there too, and nothing moves on (after the minimum Home set).+ await expect(page.getByTestId('slider-change-end')).toHaveText(+ `Brightness 0, Brightness ${caught}, Brightness ${caught}`,+ );+ expect(await thumb.evaluate(element => element.style.translate)).toBe('');+});++test('a finger held on a thumb or on the track starts no selection: the thumb’s pan refuses one until the lift, and the track’s own style keeps it unselectable', async ({+ page,+}) => {+ const {driver, thumb, center} = await openSlider(+ page,+ 'core-slider--touch-tracking',+ {name: 'Brightness'},+ );+ const control = thumb.locator(+ 'xpath=ancestor::*[contains(@class, "astryx-slider-control")][1]',+ );+ // The thumb's pan brings the gesture host's selection lock. Where iOS+ // WebKit's touch-callout query holds, it writes `user-select: none` inline+ // on the held element. An engine keeps the standard or the prefixed form+ // in its CSSOM. Elsewhere it cancels the `selectstart` a long press fires,+ // with no style write.+ const refusesSelection = async () =>+ thumb.evaluate(node => {+ if (CSS.supports('(-webkit-touch-callout: none)')) {+ const {style} = node as HTMLElement;+ return (+ (style.getPropertyValue('user-select') ||+ style.getPropertyValue('-webkit-user-select')) === 'none'+ );+ }+ const event = new Event('selectstart', {bubbles: true, cancelable: true});+ node.dispatchEvent(event);+ return event.defaultPrevented;+ });+ const at = await center();+ const [onThumb] = await playReading(+ page,+ driver,+ tap(at, {holdMs: 600}),+ [0],+ async () => {+ await page.waitForTimeout(300);+ return refusesSelection();+ },+ );+ expect(onThumb).toBe(true);+ await frames(page, 4);+ expect(await refusesSelection()).toBe(false);+ const box = await control.boundingBox();+ if (box == null) {+ throw new Error('no control');+ }+ // A finger held on the track does nothing. So the track's tap takes no+ // lock (spec:AST-094 FR41). The control's own style keeps its text+ // unselectable, and the hold selects nothing.+ const onTrack = {x: box.x + box.width * 0.9, y: box.y + box.height / 2};+ const [held] = await playReading(+ page,+ driver,+ tap(onTrack, {holdMs: 600}),+ [0],+ async () => {+ await page.waitForTimeout(300);+ return control.evaluate(node => {+ const style = getComputedStyle(node);+ return {+ inline: (node as HTMLElement).style.getPropertyValue('user-select'),+ // WebKit applies only the prefixed property (it reads the+ // standard one back as `text`); Chromium reports both.+ computed:+ style.getPropertyValue('-webkit-user-select') ||+ style.getPropertyValue('user-select'),+ selected: String(getSelection() ?? ''),+ };+ });+ },+ );+ expect(held).toEqual({inline: '', computed: 'none', selected: ''});+});++test('a finger lifted outside the tracking bounds coasts back to the lift value', async ({+ page,+}) => {+ const {driver, center, value} = await openSlider(+ page,+ 'core-slider--default',+ );+ const at = await center();+ // Drag right 40 px, then 150 px up (outside the 70 px tracking margin),+ // and lift while moving right at 400 px/s.+ const right = {x: at.x + 40, y: at.y};+ const up = {x: right.x, y: at.y - 150};+ const out = {x: up.x + 20, y: up.y};+ const {script, ends} = legs(+ at,+ [+ {to: right, durationMs: 300},+ {to: up, durationMs: 300, restMs: 100},+ {to: out, durationMs: 50},+ ],+ {hz: 120},+ );+ const [atLift] = await playReading(page, driver, script, [ends[2]], value);+ await page.waitForTimeout(900);+ // Outside the tracking bounds the release does not project: the value+ // settles where the finger left it.+ expect(await value()).toBe(atLift);+});++test('coincident range thumbs: the first movement picks the thumb that can follow it', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-slider--touch-tracking');+ const driver = await touchDriver(page);+ const low = page.getByRole('slider', {name: 'Minimum value'});+ const high = page.getByRole('slider', {name: 'Maximum value'});+ await expect.poll(async () => touchTarget(high)).not.toBeNull();+ expect(await low.getAttribute('aria-valuenow')).toBe(+ await high.getAttribute('aria-valuenow'),+ );+ const box = await high.boundingBox();+ if (box == null) {+ throw new Error('no thumb');+ }+ const at = {x: box.x + box.width / 2, y: box.y + box.height / 2};+ await driver.play(+ drag(at, {x: at.x - 60, y: at.y}, {durationMs: 400, hz: 60, restMs: 150}),+ );+ await page.waitForTimeout(800);+ expect(Number(await low.getAttribute('aria-valuenow'))).toBeLessThan(40);+ expect(await high.getAttribute('aria-valuenow')).toBe('40');+});++test('a vertical swipe from a thumb scrolls the list; a horizontal one drags it', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-slider--in-scrolling-list');+ const driver = await touchDriver(page);+ test.skip(+ !driver.drivesNativeGestures,+ 'these touches cannot scroll natively in this engine (README: engine limits)',+ );+ const list = page.getByTestId('slider-list');+ const thumb = page.getByRole('slider', {name: 'Channel 2'});+ // Present and painted first: the swipe below must leave this thumb's value.+ await expect(thumb).toBeVisible();+ await expect.poll(async () => touchTarget(thumb)).not.toBeNull();+ const before = await thumb.getAttribute('aria-valuenow');+ const box = await thumb.boundingBox();+ if (box == null) {+ throw new Error('no thumb');+ }+ const at = {x: box.x + box.width / 2, y: box.y + box.height / 2};+ await driver.play(+ drag(at, {x: at.x, y: at.y - 120}, {durationMs: 200, hz: 60}),+ );+ await page.waitForTimeout(600);+ expect(await list.evaluate(element => element.scrollTop)).toBeGreaterThan(40);+ expect(await thumb.getAttribute('aria-valuenow')).toBe(before);+ // Let the list's own deceleration finish: a finger on a moving list+ // brakes it and the control does not track that touch. The list must come+ // to rest (two reads 100 ms apart agree). If it never does, the test fails+ // here instead of dragging on a moving list.+ await expect+ .poll(+ async () => {+ const first = await list.evaluate(element => element.scrollTop);+ await page.waitForTimeout(100);+ return (await list.evaluate(element => element.scrollTop)) === first;+ },+ {timeout: 4000, intervals: [0]},+ )+ .toBe(true);+ // Where the list rests: the horizontal drag below must not move it.+ const top = await list.evaluate(element => element.scrollTop);+ // A thumb in view after the scroll.+ const listBox = await list.boundingBox();+ const visible = page.getByRole('slider', {name: 'Channel 6'});+ await expect(visible).toBeVisible();+ const visibleBefore = await visible.getAttribute('aria-valuenow');+ const next = await visible.boundingBox();+ if (next == null || listBox == null) {+ throw new Error('no thumb');+ }+ expect(next.y).toBeGreaterThan(listBox.y);+ expect(next.y + next.height).toBeLessThan(listBox.y + listBox.height);+ const from = {x: next.x + next.width / 2, y: next.y + next.height / 2};+ await driver.play(+ drag(+ from,+ {x: from.x + 70, y: from.y},+ {durationMs: 300, hz: 60, restMs: 150},+ ),+ );+ await page.waitForTimeout(800);+ expect(await list.evaluate(element => element.scrollTop)).toBe(top);+ expect(Number(await visible.getAttribute('aria-valuenow'))).toBeGreaterThan(+ Number(visibleBefore),+ );+});++test('right to left: dragging toward the inline end raises the value', async ({+ page,+}) => {+ const {driver, center, value, length} = await openSlider(+ page,+ 'core-slider--default',+ {direction: 'rtl'},+ );+ const start = await value();+ const at = await center();+ const {script, ends} = legs(at, [+ {to: {x: at.x - 60, y: at.y}, durationMs: 400, restMs: 150},+ ]);+ const [reached] = await playReading(page, driver, script, ends, value);+ expect(reached).toBe(Math.round(trackedValue(start, 60, length)));+});++test(+ 'the coast keeps advancing every frame while the main thread is blocked',+ {tag: '@storyboard'},+ async ({page}, testInfo) => {+ // A fast throw with room ahead: about 90 px of coast, never clamped.+ const {driver, thumb, center} = await openSlider(+ page,+ 'core-slider--touch-tracking',+ {name: 'Brightness'},+ );+ test.skip(+ !driver.scriptedTimestamps,+ 'WebKit stamps an injected touch when it arrives, so a stalled dispatch bunches the throw, and its cast moves in 2 px steps (README: engine limits)',+ );+ await markElement(thumb);+ // A compositor-only control in the same screencast: the coast is judged+ // against what this machine's compositor presented in the block.+ await startBusyControl(page);+ const cast = await startScreencast(page);+ const at = await center();+ // Block mid-flight, once the coast itself runs: the harness cannot judge+ // an animation that has not started. The page waits from before the+ // release, frame by frame, until the coast in the fill has run three+ // frames. Nothing else animates there, since the lift scales the thumb+ // alone. It blocks from that frame, so no round trip to the test sits+ // between the coast's start and the block.+ const blocking = blockMainThread(page, 400, {+ during: fillOf(thumb),+ minProgressMs: 48,+ });+ // A moderate iPhone flick, 900 px/s over 60 ms, with the script's own+ // timestamps.+ await driver.play(flick(at, {velocity: {x: 900, y: 0}, durationMs: 60}));+ const block = await blocking;+ await page.waitForTimeout(150);+ const castFrames = await cast.stop();+ const tracked = await trackMarker(page, castFrames);+ const control = await trackMarker(page, castFrames, {rgb: CONTROL_RGB});+ // Judged until 2 px from rest: two of the cast's 1 px position steps.+ const proof = busyWindowProof(tracked, block, {+ axis: 'x',+ settledWithin: 2,+ control,+ });+ await writeEvidence(+ 'busy-main-thread/slider-coast',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {+ block,+ proof,+ frames: tracked.map(f => ({+ t: +(f.t - block.from).toFixed(1),+ x: f.box?.x ?? null,+ })),+ },+ null,+ 1,+ ),+ },+ testInfo,+ );+ // A cast is the screen's own frames: the harness applies no clip to it.+ const film = await castStoryboard(page, castFrames, {+ name: 'slider-coast-busy-main-thread',+ zero: block.from,+ from: block.from - 40,+ to: proof.judged.to + 40,+ columns: 8,+ cellScale: 0.5,+ data: t => ({x: tracked.find(f => f.t === t)?.box?.x ?? -1}),+ });+ await film.write(testInfo, {block, judged: proof.judged});+ testInfo.annotations.push({+ type: 'busy-main-thread',+ description: proof.summary,+ });+ expect(proof.verdict.failures, proof.summary).toEqual([]);+ },+);++test('every touch screen gets the same touch model, whatever its engine: touch targets, the lift, the travel and a tap that sets the value on its lift', async ({+ page,+}) => {+ const {driver, thumb, center, value, length} = await openSlider(+ page,+ 'core-slider--touch-tracking',+ {name: 'Brightness'},+ );+ // Nothing here is iOS's engine (no -webkit-touch-callout, as on Android's+ // Chromium): the touch presentation keys on the coarse pointer alone.+ expect(+ await page.evaluate(() => CSS.supports('(-webkit-touch-callout: none)')),+ ).toBe(false);+ const control = thumb.locator(+ 'xpath=ancestor::*[contains(@class, "astryx-slider-control")][1]',+ );+ // A held thumb lifts.+ const at = await center();+ const [scale] = await playReading(+ page,+ driver,+ tap(at, {holdMs: 500}),+ [0],+ async () => {+ await page.waitForTimeout(400);+ return thumb.evaluate(element => Number(getComputedStyle(element).scale));+ },+ );+ expect(scale).toBeCloseTo(UISLIDER.liftScale, 2);+ await waitForRest(thumb);+ // A drag moves the value by the travel past the threshold, not to the+ // finger.+ const start = await value();+ const from = await center();+ const script = drag(+ from,+ {x: from.x - 70, y: from.y},+ {durationMs: 500, hz: 60, restMs: 200},+ );+ const [dragged] = await playReading(+ page,+ driver,+ script,+ [script.length - 2],+ value,+ );+ expect(dragged).toBe(Math.round(trackedValue(start, -70, length)));+ await waitForRest(thumb);+ // A tap on the track sets the value when it lifts. (The control's width+ // follows the value text beside it. So it is read now.)+ const box = await control.boundingBox();+ if (box == null) {+ throw new Error('no control');+ }+ const target = onPixel({+ x: box.x + box.width * 0.85,+ y: box.y + box.height / 2,+ });+ const [held] = await playReading(+ page,+ driver,+ tap(target, {holdMs: 300}),+ [0],+ async () => {+ await page.waitForTimeout(150);+ return value();+ },+ );+ expect(held).toBe(await value());+ await waitForRest(thumb);+ await frames(page, 4);+ expect(await value()).toBe(+ Math.round(((target.x - box.x - THUMB / 2) / (box.width - THUMB)) * 100),+ );+});++test('a drag lays out nothing per move, and the coast neither lays out nor paints', async ({+ page,+ browserName,+}) => {+ test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');+ const {driver, thumb, center, value} = await openSlider(+ page,+ 'core-slider--default',+ {+ args: {valueDisplay: 'none'},+ },+ );+ const at = await center();+ const before = await value();+ let moves = {from: 0, to: 0};+ let coast = {from: 0, to: 0};+ const {script, ends} = legs(+ at,+ [+ {to: {x: at.x + 90, y: at.y}, durationMs: 500},+ {to: {x: at.x + 110, y: at.y}, durationMs: 50},+ ],+ {hz: 60},+ );+ const trace = await traceRendering(page, async () => {+ const played = await driver.play(script);+ moves = {+ from: played[3].dispatchedAt,+ to: played[ends[0]].dispatchedAt,+ };+ const start = played[played.length - 1].dispatchedAt;+ await waitForRest(thumb);+ coast = {from: start, to: Date.now()};+ });+ // The drag moved the thumb, so "nothing laid out" measures a real drag.+ expect(await value()).toBeGreaterThan(before + 20);+ const duringMoves = countBetween(trace, moves.from, moves.to);+ expect(duringMoves.Layout ?? 0, JSON.stringify(duringMoves)).toBe(0);+ const duringCoast = countBetween(trace, coast.from + 80, coast.to - 120);+ expect(duringCoast.Layout ?? 0, JSON.stringify(duringCoast)).toBe(0);+ expect(duringCoast.Paint ?? 0, JSON.stringify(duringCoast)).toBe(0);+});diff --git a/packages/core/src/Slider/sliderTouchBundle.test.ts b/packages/core/src/Slider/sliderTouchBundle.test.tsnew file mode 100644index 0000000000..b443f2a2d2--- /dev/null+++ b/packages/core/src/Slider/sliderTouchBundle.test.ts@@ -0,0 +1,115 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file sliderTouchBundle.test.ts+ * @input Slider's source files and the modules they import+ * @output Checks that Slider reaches its touch layer (the controller, the+ * gesture recognizers, the animator) only through sliderTouchController.ts,+ * imported from one site+ * @position Test for the touch layer's module boundary. A build can swap+ * that one module for a desktop build without the touch layer. That keeps+ * touch code out of a fine-pointer bundle+ * (`architecture:component-style-authoring` INV6)+ */++import {existsSync, readFileSync} from 'node:fs';+import path from 'node:path';+import {describe, expect, it} from 'vitest';++const SRC = path.resolve(__dirname, '..');++/**+ * The relative modules `file` loads when it runs: its value imports and+ * re-exports, not `import type` / `export type`, not `import()`.+ */+function staticImports(file: string): string[] {+ const text = readFileSync(file, 'utf8');+ const pattern =+ /^\s*(?:import|export)\s+(type\s+)?(?:[^'";]*?\s+from\s+)?['"](\.[^'"]+)['"]/gm;+ const specifiers: string[] = [];+ for (const match of text.matchAll(pattern)) {+ if (match[1] == null) {+ specifiers.push(match[2]);+ }+ }+ return specifiers;+}++function resolve(from: string, specifier: string): string {+ const base = path.resolve(path.dirname(from), specifier);+ for (const candidate of [+ base,+ `${base}.ts`,+ `${base}.tsx`,+ path.join(base, 'index.ts'),+ path.join(base, 'index.tsx'),+ ]) {+ if (/\.(ts|tsx)$/.test(candidate) && existsSync(candidate)) {+ return candidate;+ }+ }+ throw new Error(`cannot resolve ${specifier} from ${from}`);+}++/**+ * Every module `entry` loads statically, as paths relative to src, with the+ * modules that import each one; `stop` is listed but not walked into.+ */+function staticGraph(entry: string, stop?: string): Map<string, Set<string>> {+ const importers = new Map<string, Set<string>>();+ const stack: [string, string | null][] = [[path.join(SRC, entry), null]];+ while (stack.length > 0) {+ const [file, from] = stack.pop() as [string, string | null];+ const key = path.relative(SRC, file);+ const known = importers.get(key);+ if (known != null) {+ if (from != null) {+ known.add(from);+ }+ continue;+ }+ importers.set(key, new Set(from == null ? [] : [from]));+ if (key === stop) {+ continue;+ }+ for (const specifier of staticImports(file)) {+ stack.push([resolve(file, specifier), key]);+ }+ }+ return importers;+}++const TOUCH_ONLY =+ /^(gestures\/(GestureHost|GestureArena|PressTracker|\w+GestureRecognizer)|motion\/animator)\.ts$/;++const LAYER = 'Slider/sliderTouchController.ts';++describe('Slider’s touch layer is one module, imported from one site', () => {+ it('imports sliderTouchController.ts from useSliderTouch.ts alone', () => {+ const graph = staticGraph('Slider/index.ts');+ expect([...(graph.get(LAYER) ?? [])]).toEqual(['Slider/useSliderTouch.ts']);+ });++ it('reaches no recognizer, gesture host or animator but through it', () => {+ const graph = staticGraph('Slider/index.ts', LAYER);+ expect(graph.has('Slider/Slider.tsx')).toBe(true);+ expect([...graph.keys()].filter(file => TOUCH_ONLY.test(file))).toEqual([]);+ });++ it('reads the UIKit gesture groups it uses, never their union', () => {+ // One export per recognizer group lets a touch module bundle only the+ // groups it reads; `UIKIT_GESTURES` carries every group.+ const text = readFileSync(path.join(SRC, LAYER), 'utf8');+ expect(text).not.toMatch(/\bUIKIT_GESTURES\b/);+ expect(text).toMatch(+ /import \{[^}]*\bUIKIT_PAN\b[^}]*\} from '\.\.\/motion\/uikit\/gestures'/,+ );+ });++ it('finds them from the layer itself (the walk sees them)', () => {+ const graph = staticGraph(LAYER);+ expect(graph.has('gestures/GestureHost.ts')).toBe(true);+ expect(graph.has('gestures/PanGestureRecognizer.ts')).toBe(true);+ expect(graph.has('motion/animator.ts')).toBe(true);+ });+});diff --git a/packages/core/src/Slider/sliderTouchController.ts b/packages/core/src/Slider/sliderTouchController.tsnew file mode 100644index 0000000000..7423076681--- /dev/null+++ b/packages/core/src/Slider/sliderTouchController.ts@@ -0,0 +1,1209 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file sliderTouchController.ts+ * @input The slider's control (and its size), thumbs, fill parts and value+ * model; the gesture recognizers, the animator and the UIKit slider table+ * @output Exports `SliderTouchController`, `sliderCoastCurve` and the+ * `SliderTouchModel` and `SliderTouchParts` types+ * @position Internal to Slider: useSliderTouch attaches it while enabled.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Slider/useSliderTouch.ts+ * - /packages/core/src/Slider/Slider.tsx+ * - /packages/core/src/Slider/useSliderTouch.test.tsx+ */++import {getGestureHost} from '../gestures/GestureHost';+import type {GestureRecognizer} from '../gestures/GestureRecognizer';+import {playHaptic} from '../gestures/haptics';+import {PanGestureRecognizer} from '../gestures/PanGestureRecognizer';+import {+ PRESS_PROFILES,+ createPressTracker,+ type ControlEvent,+} from '../gestures/PressTracker';+import type {SwipeGestureRecognizer} from '../gestures/SwipeGestureRecognizer';+import {lockSelection} from '../gestures/selectionLock';+import {TapGestureRecognizer} from '../gestures/TapGestureRecognizer';+import type {PointerKind} from '../gestures/types';+import {isRtlElement} from '../hooks/isRtlElement';+import {+ createAnimator,+ type Animator,+ type MotionCurve,+ type MotionHandle,+} from '../motion/animator';+import {projectDistance} from '../motion/projection';+import {resolveMotion} from '../motion/resolveMotion';+import {solveSpring, toSpring, type SpringDescription} from '../motion/spring';+import {+ SLIDER_DROP_SPRING,+ SLIDER_LIFT_SPRING,+ SLIDER_RELEASE_SPRING,+ registerSpringsTable,+} from '../motion/uikit/springs';+import {UIKIT_CONTROL, UIKIT_PAN} from '../motion/uikit/gestures';+import {slider as UIKIT_SLIDER} from '../motion/uikit/slider';+import {observeResize} from '../utils/sharedResizeObserver';++/** Frames of a coast before it reports values (the touch hand-off limit). */+const HAND_OFF_FRAMES = 3;++/** A coast shorter than this (px) and slower than 1 px/s is not played. */+const MIN_COAST_PX = 0.5;++/** The parts the controller moves. */+export interface SliderTouchParts {+ readonly control: HTMLElement;+ readonly thumbs: ReadonlyArray<HTMLElement>;+ /** The fill's mover (a range's start) and the fill itself. */+ readonly fillMover: HTMLElement | null;+ readonly fill: HTMLElement | null;+}++/** What the controller needs from Slider. Read fresh on every use. */+export interface SliderTouchModel {+ readonly min: number;+ readonly max: number;+ readonly isRange: boolean;+ readonly isHorizontal: boolean;+ readonly isDisabled: boolean;+ /** The thumb's size along the travel, px: the travel is inset by half of it. */+ readonly thumbSize: number;+ /** The values the owner rendered. */+ values(): ReadonlyArray<number>;+ /** What thumb `index` becomes for `raw`: snapped, clamped, kept apart. */+ constrain(index: number, raw: number): number;+ /** The range thumb `index` may cover, unsnapped (its ends and the gap). */+ bounds(index: number): readonly [number, number];+ /**+ * `onChange` for thumb `index`. `from` holds the start values when one+ * move changes both range thumbs, as a drag passed between coincident+ * thumbs does.+ */+ change(index: number, value: number, from?: ReadonlyArray<number>): void;+ /** Thumb `index` is under a finger (pressed paint, focus, tooltip), or none. */+ press(index: number | null): void;+ /**+ * The interaction ended. Report thumb `index`'s last `value` through+ * `onChange`, or null when the interaction ends on no value of its own.+ * Report it even when a frame's report already carried it: these handlers+ * run outside React's events, so that report's render can be pending.+ * Release the pressed paint. Then have the owner render it all now, so the+ * parts can return to the stylesheet and `onChangeEnd` carries what the+ * owner rendered.+ */+ commit(index: number, value: number | null): void;+ /** `onChangeEnd`, with the values the owner rendered. */+ reportEnd(): void;+ /**+ * The value a press at client point (`x`, `y`) on the track means: a+ * mark's value on a mark, else the point along the travel.+ */+ valueAt(x: number, y: number): number;+ /** The thumb a track press at `value` moves. */+ thumbFor(value: number): number;+}++/** The travel's geometry, read once when a finger lands. */+interface Geometry {+ /** The track's length along the travel, CSS px. */+ readonly length: number;+ /** The thumb's travel: the track minus one thumb. */+ readonly travel: number;+ readonly axis: 'x' | 'y';+ /** Screen direction of increasing value along `axis`. */+ readonly sign: 1 | -1;+ /** The control's client rect, for the release's inside test. */+ readonly rect: DOMRect;+}++interface Coast {+ handles: ReadonlyArray<MotionHandle>;+ readonly target: number;+ frames: number;+ raf: number;+ /** The coast in the thumb's px along `travel`, from `at`. */+ curve: MotionCurve;+ travel: number;+ readonly at: number;+ readonly touchRelease: boolean;+}++interface Interaction {+ /** The thumb whose touch target holds the finger. */+ readonly owner: number;+ /** The thumb whose value moves (a coincident pair may hand it over). */+ index: number;+ /** The track as last measured: its length can change mid-gesture. */+ geometry: Geometry;+ /** The value when the pan began. Null until it does. */+ startValue: number | null;+ /**+ * Where the pan's threshold lies along the axis, px from the touch-down+ * point. For a finger, it is the hysteresis on the side the pan began. For+ * a mouse, whose pan begins in any direction, it is the threshold's+ * projection on the axis.+ */+ beganOffset: number;+ /** The last value reported (or rendered when the finger landed). */+ value: number;+ /** Whether the finger is inside the control's tracking bounds. */+ isInside: boolean;+ /** The end the value sits at, for the once-per-entry haptic. */+ atEnd: 'min' | 'max' | null;+ /** The value changed during this interaction. */+ changed: boolean;+ coast: Coast | null;+ /** The pan ended or was cancelled (the release is under way or done). */+ released: boolean;+ /**+ * A mouse holds the thumb: it pans as a finger does, with no lift and no+ * coast, as a mouse drag behaved before.+ */+ readonly isMouse: boolean;+ /**+ * A finger's release coasts. A mouse's or a pen's drag ends at its release,+ * with no coast.+ */+ readonly coasts: boolean;+ /**+ * The drag began on two range thumbs that share a value. It picks its+ * thumb by its first movement and may pass to the other thumb.+ */+ readonly beganCoincident: boolean;+}++/**+ * The release coast as a curve in the thumb's own px, clamped to the+ * thumb's range. It is a spring from `from` to `to` with `velocity` (px/s).+ * Its value stops at an end instead of passing it, as UISlider clamps its+ * value and the thumb follows it.+ */+export function sliderCoastCurve({+ from,+ to,+ velocity,+ lower,+ upper,+ spring: description = SLIDER_RELEASE_SPRING,+}: {+ from: number;+ to: number;+ velocity: number;+ lower: number;+ upper: number;+ /** The release spring, as the thumb's theme resolves it. */+ spring?: SpringDescription;+}): MotionCurve {+ const spring = solveSpring(toSpring(description), {+ from,+ to,+ velocity,+ });+ const lo = Math.min(lower, upper);+ const hi = Math.max(lower, upper);+ const duration = Math.min(Math.max(spring.settleTime(0.05), 1 / 120), 3);+ return {+ duration,+ at: t => (t >= duration ? to : Math.min(Math.max(spring.value(t), lo), hi)),+ velocity: t => {+ if (t >= duration) {+ return 0;+ }+ const value = spring.value(t);+ return value <= lo || value >= hi ? 0 : spring.velocity(t);+ },+ };+}++/**+ * Where the browser draws an element's translate on one axis in this frame,+ * px: its computed style, which follows the running animation. Null when it+ * draws none.+ */+function drawnTranslate(element: HTMLElement, axis: 'x' | 'y'): number | null {+ const translate =+ element.ownerDocument.defaultView?.getComputedStyle(element).translate ??+ '';+ if (translate === '' || translate === 'none') {+ return null;+ }+ const [x = '0', y = '0'] = translate.split(' ');+ const px = parseFloat(axis === 'x' ? x : y);+ return Number.isFinite(px) ? px : null;+}++/** UISlider's touch tracking for one Slider (both thumbs of a range). */+export class SliderTouchController {+ private model: SliderTouchModel;+ private readonly getParts: () => SliderTouchParts | null;+ private readonly interactions = new Map<number, Interaction>();+ private readonly animators = new Map<HTMLElement, Animator>();+ /** The owner unmounted the slider: a cancel reports nothing then. */+ private disposed = false;+ /** Thumbs whose current touch is a mouse: Slider's own handlers take it. */+ private readonly mouseOwners = new Set<number>();+ /** The track's tap (see handleTrackTap). Null while detached. */+ private trackTap: TapGestureRecognizer | null = null;++ constructor(+ model: SliderTouchModel,+ getParts: () => SliderTouchParts | null,+ ) {+ this.model = model;+ this.getParts = getParts;+ }++ setModel(model: SliderTouchModel): void {+ this.model = model;+ }++ /**+ * Attaches the recognizers to the thumbs for every pointer. Under a+ * coarse primary pointer each thumb's `::before` is its touch target.+ */+ attach(): () => void {+ this.disposed = false;+ const parts = this.getParts();+ const targets = parts?.thumbs ?? [];+ if (parts == null || targets.length === 0) {+ return () => {};+ }+ // The coast plays a motion role: register the springs table, once.+ registerSpringsTable();+ const host = getGestureHost(parts.control.ownerDocument);+ const detachers: (() => void)[] = [];+ targets.forEach((hit, owner) => {+ const tracker = createPressTracker({+ getBounds: () =>+ this.getParts()?.control.getBoundingClientRect() ?? null,+ view: hit,+ highlightDelay: PRESS_PROFILES.control.highlightDelay,+ quickTapFlash: PRESS_PROFILES.control.quickTapFlash,+ onControlEvent: (event, touch) =>+ this.handleControlEvent(owner, event, touch.pointerType),+ onHighlightChange: isHighlighted =>+ this.handleHighlight(owner, isHighlighted),+ vetoesAncestorRecognizer: recognizer => this.vetoes(recognizer),+ isEnabled: () => !this.model.isDisabled,+ });+ const pan = new PanGestureRecognizer({+ name: `slider-thumb-${owner}`,+ direction: this.model.isHorizontal ? 'horizontal' : 'vertical',+ maximumNumberOfTouches: 1,+ cancelsTouchesInView: false,+ allowedPointerTypes: ['touch', 'pen'],+ // A held thumb does something, so a held finger never starts a text+ // selection or the callout on it. The gesture host takes this lock+ // for each held press and releases it on the lift.+ selectionLock: lockSelection,+ });+ // A mouse drag on a thumb is a pan too, claimed after the same+ // hysteresis but in any direction. A mouse has no page scroll to yield+ // to, so a drag that starts off the travel still moves the thumb.+ const mousePan = new PanGestureRecognizer({+ name: `slider-thumb-${owner}-mouse`,+ maximumNumberOfTouches: 1,+ cancelsTouchesInView: false,+ allowedPointerTypes: ['mouse'],+ });+ const removeListener = pan.addListener(current =>+ this.handlePan(owner, current),+ );+ const removeMouseListener = mousePan.addListener(current =>+ this.handlePan(owner, current),+ );+ detachers.push(+ host.attachConsumer(hit, tracker),+ host.attach(hit, pan),+ host.attach(hit, mousePan),+ removeListener,+ removeMouseListener,+ () => tracker.dispose(),+ );+ });+ // A tap on the track (or a mark) sets the value when it lifts. So a drag+ // is not the only pointer way to operate the slider (WCAG 2.2 SC 2.5.7).+ // UISlider ignores track taps. This departs from it.+ // A touch that moves past the tap's allowance, or that the page takes to+ // scroll, is no tap.+ const tap = new TapGestureRecognizer({+ name: 'slider-track-tap',+ allowedPointerTypes: ['touch', 'pen'],+ cancelsTouchesInView: false,+ // A touch that travels as far as a thumb's pan needs to begin is a+ // swipe, not a tap (UITapGestureRecognizer would allow 45 pt).+ allowableMovement: UIKIT_PAN.hysteresis.value,+ // A finger held on the track does nothing. So the tap takes no+ // selection lock: the control's own `user-select: none` already keeps+ // its text unselectable.+ });+ this.trackTap = tap;+ const removeTapListener = tap.addListener(current => {+ if (current.state === 'ended') {+ this.handleTrackTap(current);+ }+ });+ detachers.push(host.attach(parts.control, tap), removeTapListener, () => {+ this.trackTap = null;+ });+ // A layout can change the track's length mid-gesture, as when a value+ // label beside it takes a digit. The drawn parts follow before the next+ // paint, so nothing jumps at the hand-back.+ detachers.push(+ observeResize(parts.control, () => this.followTrackLength()),+ );+ return () => {+ // Interactions end first, so the cancel the recognizers send as they+ // detach finds nothing left to report.+ const ended = this.endSilently();+ for (const detach of detachers) {+ detach();+ }+ this.cancelLater(ended);+ };+ }++ /** Stops every interaction and animation without reporting (unmount). */+ dispose(): void {+ this.disposed = true;+ this.endSilently();+ for (const animator of this.animators.values()) {+ animator.dispose();+ }+ this.animators.clear();+ }++ /**+ * Ends every live interaction without a word to the owner, and returns+ * them. It runs from an Effect cleanup, where `onChange`, `onChangeEnd` and+ * a synchronous render have no place. A coast stops where it is drawn, and+ * the parts return to the stylesheet at the value the owner last rendered.+ */+ private endSilently(): ReadonlyArray<Interaction> {+ if (this.interactions.size === 0) {+ return [];+ }+ const ended = [...this.interactions.values()];+ const view = this.getParts()?.control.ownerDocument.defaultView;+ for (const interaction of this.interactions.values()) {+ const coast = interaction.coast;+ if (coast != null) {+ interaction.coast = null;+ view?.cancelAnimationFrame(coast.raf);+ for (const handle of coast.handles) {+ handle.stop();+ }+ }+ interaction.released = true;+ }+ this.interactions.clear();+ this.mouseOwners.clear();+ this.handBack();+ return ended;+ }++ /**+ * Ends the interactions a detach cancelled while the slider stays mounted,+ * as when it is disabled mid-drag. Each releases its pressed paint. If any+ * changed the value, `onChangeEnd` reports once. This waits until the+ * cleanup's task ends, and an unmount in the same commit drops it.+ */+ private cancelLater(ended: ReadonlyArray<Interaction>): void {+ if (ended.length === 0) {+ return;+ }+ queueMicrotask(() => {+ if (this.disposed) {+ return;+ }+ for (const interaction of ended) {+ this.model.commit(interaction.index, null);+ }+ if (ended.some(interaction => interaction.changed)) {+ this.model.reportEnd();+ }+ });+ }++ /**+ * After the owner rendered an ended interaction's final value, the thumb+ * and the fill go back to the positions Slider's CSS gives them. Parts that+ * a coast of another thumb still drives stay with it.+ */+ private handBack(): void {+ for (const [element, animator] of this.animators) {+ if (+ [...this.interactions.values()].some(+ interaction =>+ (interaction.coast != null || !interaction.released) &&+ this.partsOf(interaction).has(element),+ )+ ) {+ continue;+ }+ // Ends the animator's translate at identity, then removes the inline+ // property. So the class's progress-driven translate shows again.+ animator.set({x: 0, y: 0});+ element.style.removeProperty('translate');+ // A Reduced Motion cross-fade wrote the opacity: end it at 1 and hand it+ // back too (a caught fade stops part-way).+ if (element.style.getPropertyValue('opacity') !== '') {+ animator.set({opacity: 1});+ element.style.removeProperty('opacity');+ }+ }+ }++ // -- events ----------------------------------------------------------------++ private handleControlEvent(+ owner: number,+ event: ControlEvent,+ pointerType: PointerKind,+ ): void {+ if (event === 'touchDown') {+ // A mouse press holds the thumb too. Its highlight never lifts+ // the thumb (handleHighlight).+ const isMouse = pointerType === 'mouse';+ if (isMouse) {+ this.mouseOwners.add(owner);+ } else {+ this.mouseOwners.delete(owner);+ }+ this.begin(owner, isMouse, pointerType === 'touch');+ return;+ }+ const interaction = this.interactions.get(owner);+ if (interaction == null) {+ return;+ }+ switch (event) {+ case 'touchDragInside':+ case 'touchDragEnter':+ interaction.isInside = true;+ return;+ case 'touchDragOutside':+ case 'touchDragExit':+ interaction.isInside = false;+ return;+ case 'touchUpInside':+ case 'touchUpOutside':+ interaction.isInside = event === 'touchUpInside';+ // A press that never became a pan ends here (a tap or a hold).+ if (interaction.startValue == null) {+ this.finish(interaction, true);+ }+ return;+ case 'touchCancel':+ // The browser took the touch to scroll, or the press was cancelled+ // before the pan began. A begun pan reports its own cancel.+ if (interaction.startValue == null) {+ this.finish(interaction, false);+ }+ return;+ default:+ return;+ }+ }++ private handleHighlight(owner: number, isHighlighted: boolean): void {+ if (this.mouseOwners.has(owner)) {+ return;+ }+ const interaction = this.interactions.get(owner);+ const index = interaction?.index ?? owner;+ if (isHighlighted && interaction != null && !interaction.released) {+ this.lift(index);+ } else if (!isHighlighted && interaction == null) {+ this.drop(index);+ }+ }++ private handlePan(owner: number, pan: PanGestureRecognizer): void {+ const interaction = this.interactions.get(owner);+ if (interaction == null || interaction.released) {+ return;+ }+ switch (pan.state) {+ case 'began':+ interaction.startValue = interaction.value;+ {+ const total = pan.totalTranslation();+ const along = total[interaction.geometry.axis];+ const distance = Math.hypot(total.x, total.y);+ interaction.beganOffset = interaction.isMouse+ ? distance > 0+ ? (pan.hysteresis * along) / distance+ : 0+ : (along < 0 ? -1 : 1) * pan.hysteresis;+ }+ if (!interaction.isMouse) {+ this.lift(interaction.index);+ }+ this.track(interaction, pan);+ return;+ case 'changed':+ this.track(interaction, pan);+ return;+ case 'ended':+ interaction.released = true;+ this.release(interaction, pan);+ return;+ case 'cancelled':+ interaction.released = true;+ this.finish(interaction, true);+ return;+ case 'possible':+ case 'failed':+ return;+ }+ }++ /** UISlider's veto: an ancestor's pan or swipe along the travel. */+ private vetoes(recognizer: GestureRecognizer): boolean {+ // A touch on a thumb is the thumb's: a tap there changes nothing.+ if (recognizer === this.trackTap) {+ return true;+ }+ const horizontal = this.model.isHorizontal;+ // Told apart by kind, never by class: a screen-edge pan is a pan.+ if (recognizer.kind === 'swipe') {+ return (recognizer as SwipeGestureRecognizer).directions.some(+ direction =>+ horizontal+ ? direction === 'left' || direction === 'right'+ : direction === 'up' || direction === 'down',+ );+ }+ if (recognizer.kind === 'pan' || recognizer.kind === 'screenEdgePan') {+ const {x, y} = (recognizer as PanGestureRecognizer).translation();+ return horizontal+ ? Math.abs(x) >= Math.abs(y)+ : Math.abs(y) >= Math.abs(x);+ }+ return false;+ }++ // -- the interaction -------------------------------------------------------++ private begin(owner: number, isMouse = false, coasts = false): void {+ const parts = this.getParts();+ if (parts == null || this.model.isDisabled) {+ return;+ }+ // A finger on a coasting thumb stops it where it is: the coast ends on+ // that value, which the owner renders and onChangeEnd reports.+ for (const other of [...this.interactions.values()]) {+ if (other.coast != null) {+ this.finish(other, true, this.stopCoast(other));+ }+ }+ const geometry = this.measure(parts);+ const values = this.model.values();+ const value = values[owner] ?? this.model.min;+ this.interactions.set(owner, {+ owner,+ index: owner,+ geometry,+ startValue: null,+ beganOffset: 0,+ value,+ isInside: true,+ atEnd: this.endOf(value),+ changed: false,+ coast: null,+ released: false,+ isMouse,+ coasts,+ beganCoincident: this.model.isRange && values[0] === values[1],+ });+ this.model.press(owner);+ }++ private track(interaction: Interaction, pan: PanGestureRecognizer): void {+ const {geometry} = interaction;+ const {min, max, isRange} = this.model;+ // A collapsed track has no length to map the travel onto.+ if (geometry.length <= 0) {+ return;+ }+ // UISlider counts the translation from the threshold itself (the+ // touch-down point plus the hysteresis, taken along the axis). So the+ // travel of the event that crossed it already counts.+ const translation =+ (pan.totalTranslation()[geometry.axis] - interaction.beganOffset) *+ geometry.sign;+ const startValue = interaction.startValue ?? interaction.value;+ const raw =+ startValue ++ (translation / geometry.length) * (max - min) * UIKIT_SLIDER.trackingGain;+ // A drag that began on two range thumbs sharing a value: its first+ // movement, which crosses the threshold, picks the thumb that can follow+ // it. The thumb on top cannot pass the other. Coming back past the other+ // thumb's value hands the drag to that thumb, which moves on. A drag that+ // began apart stops at the other thumb.+ let from: ReadonlyArray<number> | undefined;+ if (isRange && interaction.beganCoincident && raw !== startValue) {+ const values = this.model.values();+ const current = interaction.index;+ const index =+ values[0] === values[1] && !interaction.changed+ ? raw < startValue+ ? 0+ : 1+ : current === 1 && raw < (values[0] ?? raw)+ ? 0+ : current === 0 && raw > (values[1] ?? raw)+ ? 1+ : current;+ if (index !== current) {+ // Passing back over the other thumb leaves this one against it,+ // however far the move went, and the other moves on: one change+ // reports both.+ if (interaction.changed) {+ const against = this.model.constrain(current, values[index] ?? raw);+ interaction.value = against;+ this.place(interaction);+ const next = [...values];+ next[current] = against;+ from = next;+ }+ this.drop(current);+ interaction.index = index;+ interaction.value = values[index] ?? interaction.value;+ if (!interaction.isMouse) {+ this.lift(index);+ }+ this.model.press(index);+ }+ }+ this.record(interaction, this.model.constrain(interaction.index, raw), {+ from,+ });+ this.place(interaction);+ }++ /**+ * Writes the moving thumb's and the fill's positions for the+ * interaction's value straight to their translates: one visual update per+ * move, with no component render. The parts go back to+ * the stylesheet when the interaction ends (`handBack`).+ */+ private place(interaction: Interaction): void {+ const {geometry} = interaction;+ const {min, max} = this.model;+ const range = max - min;+ const pxPerValue = range > 0 ? geometry.travel / range : 0;+ const px = (interaction.value - min) * pxPerValue;+ for (const {element, at} of this.partMaps(interaction)) {+ this.animatorFor(element).set({[geometry.axis]: geometry.sign * at(px)});+ }+ }++ /**+ * Records a new value and plays the end haptic on entering an end.+ * Reports it through `onChange` unless the interaction's end commits it.+ * Returns whether the value changed.+ */+ private record(+ interaction: Interaction,+ value: number,+ {+ commits = false,+ from,+ }: {commits?: boolean; from?: ReadonlyArray<number>} = {},+ ): boolean {+ if (value === interaction.value) {+ return false;+ }+ interaction.value = value;+ interaction.changed = true;+ if (!commits) {+ this.model.change(interaction.index, value, from);+ }+ const end = this.endOf(value);+ // UISlider's end haptic belongs to a finger's or a pen's drag and its+ // coast. A mouse and a track tap play none.+ if (+ end != null &&+ end !== interaction.atEnd &&+ !interaction.isMouse &&+ interaction.startValue != null+ ) {+ playHaptic(UIKIT_SLIDER.endHaptic);+ }+ interaction.atEnd = end;+ return true;+ }++ private report(interaction: Interaction, value: number): void {+ this.record(interaction, value);+ }++ private release(interaction: Interaction, pan: PanGestureRecognizer): void {+ // A mouse's or a pen's drag ends at its release, where the pointer lets+ // go: only a finger's release coasts. A pen's+ // thumb, lifted while held, drops back first.+ if (!interaction.coasts) {+ if (!interaction.isMouse) {+ this.drop(interaction.index);+ }+ this.model.press(null);+ this.finish(interaction, true);+ return;+ }+ const {geometry, index} = interaction;+ const {min, max} = this.model;+ const range = max - min;+ this.drop(index);+ this.model.press(null);+ const location = pan.location();+ const expansion = UIKIT_CONTROL.trackingExpansion.value;+ const inside =+ location.x >= geometry.rect.left - expansion &&+ location.x <= geometry.rect.right + expansion &&+ location.y >= geometry.rect.top - expansion &&+ location.y <= geometry.rect.bottom + expansion;+ interaction.isInside = inside;+ // Finger velocity along increasing value, px/s.+ const velocity = pan.velocity()[geometry.axis] * geometry.sign;+ const projected = inside+ ? UIKIT_SLIDER.releaseProjectionShare *+ projectDistance(velocity, UIKIT_SLIDER.releaseProjectionRate)+ : 0;+ const from = interaction.value;+ // Value per px of finger travel. A collapsed track maps none, so it+ // coasts nowhere.+ const valuePerPx =+ geometry.length > 0+ ? (range * UIKIT_SLIDER.trackingGain) / geometry.length+ : 0;+ const target = this.model.constrain(index, from + projected * valuePerPx);+ // In the thumb's px: the value's velocity mapped onto the travel.+ const pxPerValue = range > 0 ? geometry.travel / range : 0;+ const valueVelocity = velocity * valuePerPx;+ this.coastTo(interaction, target, valueVelocity * pxPerValue, true);+ }++ /**+ * A tap on the track: the thumb the tap's value picks springs there, on+ * the release spring from rest. It reports as a coast does, and+ * `onChangeEnd` follows. A tap on the thumb's own value changes nothing.+ */+ private handleTrackTap(tap: TapGestureRecognizer): void {+ const parts = this.getParts();+ if (parts == null || this.model.isDisabled || this.interactions.size > 0) {+ return;+ }+ const {x, y} = tap.location();+ const raw = this.model.valueAt(x, y);+ const index = this.model.thumbFor(raw);+ const target = this.model.constrain(index, raw);+ const value = this.model.values()[index] ?? this.model.min;+ if (target === value) {+ return;+ }+ const interaction: Interaction = {+ owner: index,+ index,+ geometry: this.measure(parts),+ startValue: null,+ beganOffset: 0,+ value,+ isInside: true,+ atEnd: this.endOf(value),+ changed: false,+ coast: null,+ released: true,+ isMouse: false,+ coasts: false,+ beganCoincident: false,+ };+ this.interactions.set(index, interaction);+ // A tap's value change happens in place. So under Reduce Motion it+ // applies at once, with no spring and no cross-fade.+ const thumb = parts.thumbs[index];+ if (thumb != null && this.animatorFor(thumb).reducedMotion() !== 'off') {+ this.finish(interaction, true, target);+ return;+ }+ this.coastTo(interaction, target, 0, false);+ }++ /**+ * Springs the interaction's thumb from its value to `target`, on the+ * compositor and clamped, starting at `velocityPx` (px/s along the+ * travel). `onChange` follows from the coast's fourth frame, and the+ * interaction ends (`onChangeEnd`) on its last. `touchRelease` means a+ * finger's release started it. Then the coast continues the throw and+ * keeps moving under Reduce Motion. A tap's spring never runs there+ * (`handleTrackTap` sets the value at once).+ */+ private coastTo(+ interaction: Interaction,+ target: number,+ velocityPx: number,+ touchRelease: boolean,+ ): void {+ const {geometry, index} = interaction;+ const {min, max} = this.model;+ const range = max - min;+ const pxPerValue = range > 0 ? geometry.travel / range : 0;+ const from = interaction.value;+ const fromPx = (from - min) * pxPerValue;+ const toPx = (target - min) * pxPerValue;+ const [lowerValue, upperValue] = this.model.bounds(index);+ const curve = sliderCoastCurve({+ from: fromPx,+ to: toPx,+ velocity: velocityPx,+ lower: (lowerValue - min) * pxPerValue,+ upper: (upperValue - min) * pxPerValue,+ // The coast plays the `springs.sliderRelease` role, resolved as it+ // starts.+ spring: resolveMotion(this.getParts()?.control, SLIDER_RELEASE_SPRING),+ });+ const moves =+ Math.abs(toPx - fromPx) >= MIN_COAST_PX ||+ Math.max(Math.abs(curve.at(0.05) - fromPx), 0) >= MIN_COAST_PX;+ if (!moves) {+ this.finish(interaction, true, target);+ return;+ }+ const at = performance.now();+ const handles = this.playCoast(interaction, curve, touchRelease, at);+ if (handles.length === 0) {+ this.finish(interaction, true, target);+ return;+ }+ const coast: Coast = {+ handles,+ target,+ frames: 0,+ raf: 0,+ curve,+ travel: geometry.travel,+ at,+ touchRelease,+ };+ interaction.coast = coast;+ const view = this.getParts()?.control.ownerDocument.defaultView;+ const step = () => {+ if (interaction.coast !== coast) {+ return;+ }+ coast.frames += 1;+ if (coast.frames > HAND_OFF_FRAMES) {+ const {axis, travel} = interaction.geometry;+ const px = Math.abs(coast.handles[0]?.value(axis) ?? 0);+ const value =+ range > 0 && travel > 0+ ? min + (px / travel) * range+ : interaction.value;+ this.report(interaction, this.model.constrain(index, value));+ }+ coast.raf = view?.requestAnimationFrame(step) ?? 0;+ };+ coast.raf = view?.requestAnimationFrame(step) ?? 0;+ this.endCoastWithThumb(interaction, coast);+ }++ /** Ends the coast when its thumb's motion finishes, not when it stops. */+ private endCoastWithThumb(interaction: Interaction, coast: Coast): void {+ const thumbHandle = coast.handles[0];+ void thumbHandle?.finished.then(finished => {+ if (+ interaction.coast !== coast ||+ coast.handles[0] !== thumbHandle ||+ !finished+ ) {+ return;+ }+ this.getParts()?.control.ownerDocument.defaultView?.cancelAnimationFrame(+ coast.raf,+ );+ interaction.coast = null;+ this.finish(interaction, true, coast.target);+ });+ }++ /**+ * After the track's length changed: every live interaction measures it+ * again. A drag writes its parts for the new length, and a coast plays+ * on from where its curve is now, scaled to the new travel.+ */+ private followTrackLength(): void {+ const parts = this.getParts();+ if (parts == null || this.interactions.size === 0) {+ return;+ }+ for (const interaction of this.interactions.values()) {+ const geometry = this.measure(parts);+ if (geometry.length === interaction.geometry.length) {+ continue;+ }+ interaction.geometry = geometry;+ const {coast} = interaction;+ if (coast != null) {+ const scale = coast.travel > 0 ? geometry.travel / coast.travel : 1;+ const {curve} = coast;+ coast.curve = {+ duration: curve.duration,+ at: t => curve.at(t) * scale,+ velocity: t => curve.velocity(t) * scale,+ };+ coast.travel = geometry.travel;+ coast.handles = this.playCoast(+ interaction,+ coast.curve,+ coast.touchRelease,+ coast.at,+ );+ this.endCoastWithThumb(interaction, coast);+ } else if (!interaction.released) {+ this.place(interaction);+ }+ }+ }++ /**+ * Plays the coast on the thumb and the fill parts, on one clock that+ * started at `at`. A re-mapped coast plays on from where its curve is.+ */+ private playCoast(+ interaction: Interaction,+ curve: MotionCurve,+ touchRelease: boolean,+ at: number,+ ): MotionHandle[] {+ const {axis, sign} = interaction.geometry;+ const handles: MotionHandle[] = [];+ for (const {element, at: position, slope} of this.partMaps(interaction)) {+ const partCurve: MotionCurve = {+ duration: curve.duration,+ at: t => sign * position(curve.at(t)),+ velocity: t => sign * slope * curve.velocity(t),+ };+ const animator = this.animatorFor(element);+ animator.set({[axis]: partCurve.at(0)});+ // A release's coast continues the throw: momentum, which keeps moving+ // under Reduce Motion. A tap's spring is a+ // transition.+ handles.push(+ touchRelease+ ? animator.decay({[axis]: partCurve}, {at, touchRelease})+ : animator.play({[axis]: partCurve}, {at}),+ );+ }+ return handles;+ }++ /**+ * The parts that move with the interaction's thumb. Each has its translate+ * as a function of the thumb's px along the travel (`p`), and that+ * function's slope. The formulas are the same as Slider's CSS.+ */+ private partMaps(interaction: Interaction): {+ element: HTMLElement;+ at: (p: number) => number;+ slope: number;+ }[] {+ const parts = this.getParts();+ if (parts == null) {+ return [];+ }+ const {geometry, index} = interaction;+ const {length, travel} = geometry;+ const inset = this.model.thumbSize / 2;+ const values = this.model.values();+ const {min, max, isRange} = this.model;+ const range = max - min;+ const pxPerValue = range > 0 ? travel / range : 0;+ const otherPx = ((values[index === 0 ? 1 : 0] ?? min) - min) * pxPerValue;+ const maps: {+ element: HTMLElement;+ at: (p: number) => number;+ slope: number;+ }[] = [];+ const add = (+ element: HTMLElement | null | undefined,+ at: (p: number) => number,+ slope: number,+ ) => {+ if (element != null) {+ maps.push({element, at, slope});+ }+ };+ add(parts.thumbs[index], p => p, 1);+ if (isRange) {+ if (index === 0) {+ add(parts.fillMover, p => inset + p, 1);+ add(parts.fill, p => otherPx - p - length, -1);+ } else {+ add(parts.fill, p => p - otherPx - length, 1);+ }+ } else {+ add(parts.fill, p => inset + p - length, 1);+ }+ return maps;+ }++ /**+ * Stops a coast where the browser draws the thumb in this frame. Returns+ * the value there for `finish` to end on, or null when the travel has no+ * length. The animator's own reading can run a frame ahead of or behind+ * what is drawn, and a finger stops what it sees.+ */+ private stopCoast(interaction: Interaction): number | null {+ const coast = interaction.coast;+ if (coast == null) {+ return null;+ }+ interaction.coast = null;+ this.getParts()?.control.ownerDocument.defaultView?.cancelAnimationFrame(+ coast.raf,+ );+ const {geometry, index} = interaction;+ const {min, max} = this.model;+ const thumb = this.getParts()?.thumbs[index];+ const drawn = thumb == null ? null : drawnTranslate(thumb, geometry.axis);+ const px = Math.abs(drawn ?? coast.handles[0]?.value(geometry.axis) ?? 0);+ for (const handle of coast.handles) {+ handle.stop();+ }+ const range = max - min;+ return range > 0 && geometry.travel > 0+ ? this.model.constrain(index, min + (px / geometry.travel) * range)+ : null;+ }++ /**+ * Ends an interaction from the handler that ends it: the lift, the cancel+ * or the coast's last frame. The owner renders the last value at once, and+ * the parts return to the stylesheet. `onChangeEnd` then reports what the+ * owner rendered, unless the browser took the touch before any drag+ * (`report` false).+ */+ private finish(+ interaction: Interaction,+ report: boolean,+ finalValue: number | null = null,+ ): void {+ if (this.interactions.get(interaction.owner) !== interaction) {+ return;+ }+ this.interactions.delete(interaction.owner);+ if (!interaction.released) {+ this.drop(interaction.index);+ }+ interaction.released = true;+ if (finalValue != null) {+ this.record(interaction, finalValue, {commits: true});+ }+ // The owner renders the final value from this handler even when a+ // frame's report already carried it: these handlers run outside React's+ // events. So that report's render can still be pending, and onChangeEnd+ // reads what the owner rendered.+ this.model.commit(interaction.index, finalValue);+ this.handBack();+ if (report) {+ this.model.reportEnd();+ }+ }++ // -- the thumb's lift --------------------------------------------------------++ private lift(index: number): void {+ const thumb = this.getParts()?.thumbs[index];+ if (thumb == null) {+ return;+ }+ const animator = this.animatorFor(thumb);+ // The lift is feedback with no fade of its own. Under Reduce Motion the+ // press shows in the pressed paint alone, and a change of state never+ // scales.+ if (animator.reducedMotion() !== 'off') {+ return;+ }+ animator.animate(+ {scale: UIKIT_SLIDER.liftScale},+ {spring: resolveMotion(this.getParts()?.control, SLIDER_LIFT_SPRING)},+ );+ }++ private drop(index: number): void {+ const thumb = this.getParts()?.thumbs[index];+ if (thumb == null) {+ return;+ }+ const animator = this.animators.get(thumb);+ if (animator == null || animator.get('scale') === 1) {+ return;+ }+ animator.animate(+ {scale: 1},+ {spring: resolveMotion(this.getParts()?.control, SLIDER_DROP_SPRING)},+ );+ }++ // -- helpers -----------------------------------------------------------------++ private measure(parts: SliderTouchParts): Geometry {+ const {control} = parts;+ const horizontal = this.model.isHorizontal;+ // The layout size (unrounded, untransformed): the size the CSS's+ // container units resolve against.+ const style = control.ownerDocument.defaultView?.getComputedStyle(control);+ const rect = control.getBoundingClientRect();+ const used = (horizontal ? style?.width : style?.height) ?? '';+ const length = used.endsWith('px')+ ? parseFloat(used)+ : horizontal+ ? rect.width+ : rect.height;+ return {+ length,+ travel: Math.max(0, length - this.model.thumbSize),+ axis: horizontal ? 'x' : 'y',+ sign: horizontal ? (isRtlElement(control) ? -1 : 1) : -1,+ rect,+ };+ }++ private endOf(value: number): 'min' | 'max' | null {+ if (value <= this.model.min) {+ return 'min';+ }+ if (value >= this.model.max) {+ return 'max';+ }+ return null;+ }++ private animatorFor(element: HTMLElement): Animator {+ let animator = this.animators.get(element);+ if (animator == null) {+ animator = createAnimator(element);+ this.animators.set(element, animator);+ }+ return animator;+ }++ private partsOf(interaction: Interaction): Set<HTMLElement> {+ const parts = this.getParts();+ const set = new Set<HTMLElement>();+ if (parts == null) {+ return set;+ }+ const thumb = parts.thumbs[interaction.index];+ for (const element of [thumb, parts.fillMover, parts.fill]) {+ if (element != null) {+ set.add(element);+ }+ }+ return set;+ }+}diff --git a/packages/core/src/Slider/useSliderTouch.test.tsx b/packages/core/src/Slider/useSliderTouch.test.tsxnew file mode 100644index 0000000000..cf1e42f474--- /dev/null+++ b/packages/core/src/Slider/useSliderTouch.test.tsx@@ -0,0 +1,920 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useSliderTouch.test.tsx+ * @input vitest, Testing Library, Slider under a stubbed coarse pointer,+ * stubbed geometry, timed touch events and fake timers+ * @output Holds Slider's touch presentation to UISlider's rules in jsdom:+ * targets, track taps, travel (LTR, RTL, vertical), coincident thumbs,+ * the coast, and a cancel's single `onChangeEnd`+ * @position Testing: the unit layer of useSliderTouch.ts. The browser layer+ * is __tests__/SliderTouch.interaction.browser.spec.ts.+ */++import {+ act,+ fireEvent,+ render,+ screen,+ type RenderResult,+} from '@testing-library/react';+import {useState, type ReactElement} from 'react';+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ onTestFinished,+ vi,+} from 'vitest';+import {Slider} from './Slider';+import {getGestureHost} from '../gestures/GestureHost';+import {PanGestureRecognizer} from '../gestures/PanGestureRecognizer';+import {projectDistance} from '../motion/projection';+import type * as HapticsModule from '../gestures/haptics';+import {slider as UIKIT_SLIDER} from '../motion/uikit/slider';++/** The control's stubbed layout: 300 px long at x = 0 (or y = 0). */+const LENGTH = 300;++// The end haptic is a spy: the browser's vibration is not observable here.+const haptics = vi.hoisted(() => ({playHaptic: vi.fn()}));+vi.mock('../gestures/haptics', async importOriginal => ({+ ...(await importOriginal<typeof HapticsModule>()),+ playHaptic: haptics.playHaptic,+}));++interface Contact {+ id: number;+ x: number;+ y: number;+}++function touch(+ type: 'touchstart' | 'touchmove' | 'touchend',+ target: Element,+ contact: Contact,+ time: number,+): void {+ const event = new Event(type, {+ bubbles: true,+ cancelable: true,+ composed: true,+ });+ const point = {+ identifier: contact.id,+ clientX: contact.x,+ clientY: contact.y,+ target,+ };+ Object.defineProperty(event, 'changedTouches', {value: [point]});+ Object.defineProperty(event, 'touches', {+ value: type === 'touchend' ? [] : [point],+ });+ Object.defineProperty(event, 'timeStamp', {value: time});+ act(() => {+ target.dispatchEvent(event);+ });+}++/** One pen event (pointer events only: a pen sends no touch events). */+function pen(+ type: 'pointerdown' | 'pointermove' | 'pointerup',+ target: Element,+ x: number,+ y: number,+ time: number,+): void {+ const event = new Event(type, {+ bubbles: true,+ cancelable: true,+ composed: true,+ });+ Object.defineProperties(event, {+ pointerId: {value: 7},+ pointerType: {value: 'pen'},+ isPrimary: {value: true},+ clientX: {value: x},+ clientY: {value: y},+ button: {value: type === 'pointermove' ? -1 : 0},+ buttons: {value: type === 'pointerup' ? 0 : 1},+ pressure: {value: type === 'pointerup' ? 0 : 0.5},+ width: {value: 1},+ height: {value: 1},+ timeStamp: {value: time},+ });+ act(() => {+ target.dispatchEvent(event);+ });+}++/**+ * Event timestamps keep increasing across tests: the document's gesture+ * host outlives each render, and its velocity filter reads the timestamps.+ */+let clock = 1000;+const nextStart = () => (clock += 10_000);++/** One finger from `from` by `dx`, `dy` in `steps` moves 16 ms apart. */+function dragThumb(+ hit: Element,+ from: {x: number; y: number},+ {dx = 0, dy = 0, steps = 10, start = nextStart(), lift = true} = {},+): number {+ touch('touchstart', hit, {id: 1, ...from}, start);+ let t = start;+ for (let i = 1; i <= steps; i++) {+ t += 16;+ touch(+ 'touchmove',+ hit,+ {id: 1, x: from.x + (dx * i) / steps, y: from.y + (dy * i) / steps},+ t,+ );+ }+ if (lift) {+ t += 4;+ touch('touchend', hit, {id: 1, x: from.x + dx, y: from.y + dy}, t);+ }+ return t;+}++/** A coarse (a finger) or a fine (a mouse) primary pointer. */+function stubMatchMedia(coarse: boolean) {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ matches: coarse && query.includes('pointer: coarse'),+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+}++/** Gives every slider control a 300 px layout box. */+function stubControlGeometry(vertical = false, length = LENGTH) {+ stubTouchAction();+ const rect = vertical+ ? {left: 0, top: 0, right: 24, bottom: length, width: 24, height: length}+ : {left: 0, top: 0, right: length, bottom: 24, width: length, height: 24};+ const original = HTMLElement.prototype.getBoundingClientRect;+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(+ function (this: HTMLElement) {+ if (this.classList.contains('astryx-slider-control')) {+ return {...rect, x: rect.left, y: rect.top, toJSON: () => rect};+ }+ return original.call(this);+ },+ );+}++function Controlled({+ initial,+ onChange,+ onChangeEnd,+ orientation,+ valueDisplay = 'none',+}: {+ initial: number | [number, number];+ onChange?: (value: number | [number, number]) => void;+ onChangeEnd?: (value: number | [number, number]) => void;+ orientation?: 'horizontal' | 'vertical';+ valueDisplay?: 'none' | 'tooltip' | 'text';+}) {+ const [value, setValue] = useState<number | [number, number]>(initial);+ const report = (next: number | [number, number]) => {+ onChange?.(next);+ setValue(next);+ };+ return Array.isArray(value) ? (+ <Slider+ label="Level"+ valueDisplay={valueDisplay}+ orientation={orientation}+ value={value}+ onChange={report}+ onChangeEnd={onChangeEnd}+ />+ ) : (+ <Slider+ label="Level"+ valueDisplay={valueDisplay}+ orientation={orientation}+ value={value}+ onChange={report}+ onChangeEnd={onChangeEnd}+ />+ );+}++/**+ * jsdom drops `touch-action` from styles, so report what the gesture host+ * sets on a thumb. A pan along the travel leaves the browser the cross axis.+ */+function stubTouchAction() {+ const original = window.getComputedStyle.bind(window);+ vi.spyOn(window, 'getComputedStyle').mockImplementation(+ (element: Element, pseudo?: string | null) => {+ const style = original(element, pseudo);+ if (+ element.classList.contains('astryx-slider-control') &&+ document.documentElement.getAttribute('dir') === 'rtl'+ ) {+ return new Proxy(style, {+ get(target, key): string | number | object | null | undefined {+ if (key === 'direction') {+ return 'rtl';+ }+ const value = Reflect.get(target, key) as+ string | number | object | null | undefined;+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ }+ if (element.getAttribute('role') !== 'slider') {+ return style;+ }+ const vertical = element.getAttribute('aria-orientation') === 'vertical';+ const touchAction = vertical ? 'pan-x pinch-zoom' : 'pan-y pinch-zoom';+ return new Proxy(style, {+ get(target, key): string | number | object | null | undefined {+ if (key === 'touchAction') {+ return touchAction;+ }+ if (key === 'getPropertyValue') {+ return (name: string) =>+ name === 'touch-action'+ ? touchAction+ : target.getPropertyValue(name);+ }+ const value = Reflect.get(target, key) as+ string | number | object | null | undefined;+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ },+ );+}++// A thumb takes a finger itself. Under a coarse primary pointer its+// `::before` is the touch target, drawn from the insets it carries.+const hitOf = (thumb: HTMLElement) => thumb;+const drawsTouchTarget = (thumb: HTMLElement) =>+ thumb.style.getPropertyValue('--_slider-hit-top') !== '';++beforeEach(() => {+ vi.useFakeTimers({+ toFake: [+ 'setTimeout',+ 'clearTimeout',+ 'requestAnimationFrame',+ 'cancelAnimationFrame',+ 'performance',+ ],+ });+ if (!Element.prototype.setPointerCapture) {+ Element.prototype.setPointerCapture = vi.fn();+ Element.prototype.releasePointerCapture = vi.fn();+ }+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ document.documentElement.removeAttribute('dir');+});++/**+ * Renders, then flushes the effects that attach the touch presentation to the+ * thumbs.+ */+async function renderTouch(ui: ReactElement): Promise<RenderResult> {+ const view = render(ui);+ await act(async () => {+ await Promise.resolve();+ });+ return view;+}++describe('Slider touch presentation (UISlider tracking)', () => {+ it('draws the thumbs’ touch targets only under a coarse primary pointer, with no element of their own', async () => {+ stubMatchMedia(false);+ const {unmount} = await renderTouch(<Controlled initial={50} />);+ const fine = screen.getByRole('slider');+ expect(drawsTouchTarget(fine)).toBe(false);+ const fineCount = fine.querySelectorAll('*').length;+ unmount();+ stubMatchMedia(true);+ await renderTouch(<Controlled initial={[20, 80]} />);+ for (const thumb of screen.getAllByRole('slider')) {+ expect(drawsTouchTarget(thumb)).toBe(true);+ expect(thumb.querySelectorAll('*').length).toBe(fineCount);+ }+ });++ it('gives every touch screen the same touch presentation, whatever its engine (one touch model)', async () => {+ stubMatchMedia(true);+ // No -webkit-touch-callout here, as on Android's Chromium: the touch+ // presentation keys on the coarse pointer alone.+ vi.stubGlobal('CSS', {supports: () => false});+ stubControlGeometry();+ const onChange = vi.fn();+ await renderTouch(<Controlled initial={50} onChange={onChange} />);+ expect(drawsTouchTarget(screen.getByRole('slider'))).toBe(true);+ const control = document.querySelector(+ '.astryx-slider-control',+ ) as HTMLElement;+ fireEvent.pointerDown(control, {+ pointerId: 1,+ pointerType: 'touch',+ clientX: 280,+ clientY: 12,+ });+ fireEvent.pointerUp(control, {pointerId: 1, pointerType: 'touch'});+ // The pointer handlers leave the finger to the touch presentation.+ expect(onChange).not.toHaveBeenCalled();+ });++ it('under a coarse primary pointer (a mouse on a touch device): ignores a finger on the track, while the mouse still moves the value there', async () => {+ stubMatchMedia(true);+ expect(matchMedia('(pointer: coarse)').matches).toBe(true);+ stubControlGeometry();+ const onChange = vi.fn();+ await renderTouch(<Controlled initial={50} onChange={onChange} />);+ const control = document.querySelector(+ '.astryx-slider-control',+ ) as HTMLElement;+ fireEvent.pointerDown(control, {+ pointerId: 1,+ pointerType: 'touch',+ clientX: 280,+ clientY: 12,+ });+ fireEvent.pointerUp(control, {pointerId: 1, pointerType: 'touch'});+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.pointerDown(control, {+ pointerId: 2,+ pointerType: 'mouse',+ clientX: 280,+ clientY: 12,+ button: 0,+ });+ fireEvent.pointerUp(control, {pointerId: 2, pointerType: 'mouse'});+ expect(onChange).toHaveBeenCalled();+ });++ it.each([+ {name: 'left to right', dir: 'ltr', dx: 70, expected: 50 + 20},+ {name: 'right to left', dir: 'rtl', dx: -70, expected: 50 + 20},+ ])(+ '$name: the value moves by the travel past the 10 px threshold over the track length',+ async ({dir, dx, expected}) => {+ stubMatchMedia(true);+ stubControlGeometry();+ document.documentElement.setAttribute('dir', dir);+ const onChange = vi.fn();+ await renderTouch(<Controlled initial={50} onChange={onChange} />);+ const thumb = screen.getByRole('slider');+ dragThumb(hitOf(thumb), {x: 150, y: 12}, {dx, lift: false});+ // (70 − 10) px of 300 px is 20 % of the range.+ expect(thumb).toHaveAttribute('aria-valuenow', String(expected));+ // The press itself and the first 10 px move nothing.+ expect(onChange.mock.calls[0]?.[0]).toBe(51);+ },+ );++ it('vertical: an upward drag raises the value', async () => {+ stubMatchMedia(true);+ stubControlGeometry(true);+ await renderTouch(<Controlled initial={50} orientation="vertical" />);+ const thumb = screen.getByRole('slider');+ const control = document.querySelector(+ '.astryx-slider-control',+ ) as HTMLElement;+ // The control's used height when the stylesheet gives one, else the+ // stubbed box.+ const height = getComputedStyle(control).height;+ const length = height.endsWith('px') ? parseFloat(height) : LENGTH;+ dragThumb(hitOf(thumb), {x: 12, y: 150}, {dy: -40, lift: false});+ expect(thumb).toHaveAttribute(+ 'aria-valuenow',+ String(50 + Math.round(((40 - 10) / length) * 100)),+ );+ });++ it('coincident range thumbs: the first movement picks the thumb that can follow it', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ await renderTouch(<Controlled initial={[40, 40]} />);+ const [low, high] = screen.getAllByRole('slider');+ // The thumb on top (the second) takes the finger. Dragging toward min+ // moves the first.+ dragThumb(hitOf(high), {x: 120, y: 12}, {dx: -40, lift: false});+ expect(low).toHaveAttribute('aria-valuenow', '30');+ expect(high).toHaveAttribute('aria-valuenow', '40');+ });++ it('vetoes an ancestor pan along the travel for a touch on a thumb, not one across it', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ const {container} = await renderTouch(<Controlled initial={50} />);+ const host = getGestureHost(document);+ // It would begin first (4 px against the thumb's 10 px) if not vetoed.+ const along = new PanGestureRecognizer({+ direction: 'horizontal',+ hysteresis: 4,+ });+ const across = new PanGestureRecognizer({direction: 'vertical'});+ const states: string[] = [];+ along.addListener(pan => states.push(`along:${pan.state}`));+ across.addListener(pan => states.push(`across:${pan.state}`));+ const detachAlong = host.attach(container, along);+ const thumb = screen.getByRole('slider');+ // A horizontal drag from the thumb: the slider's, never the pager's.+ dragThumb(hitOf(thumb), {x: 150, y: 12}, {dx: 60});+ expect(states.filter(state => state.startsWith('along'))).toEqual([]);+ expect(thumb).not.toHaveAttribute('aria-valuenow', '50');+ detachAlong();+ // A vertical drag from the thumb: the ancestor's vertical pan takes it.+ const detachAcross = host.attach(container, across);+ dragThumb(hitOf(thumb), {x: 150, y: 12}, {dy: 60});+ expect(states).toContain('across:began');+ detachAcross();+ });++ it('a tap on the thumb changes nothing and reports one onChangeEnd', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ const onChange = vi.fn();+ const onChangeEnd = vi.fn();+ await renderTouch(+ <Controlled initial={50} onChange={onChange} onChangeEnd={onChangeEnd} />,+ );+ const hit = hitOf(screen.getByRole('slider'));+ const start = nextStart();+ touch('touchstart', hit, {id: 1, x: 150, y: 12}, start);+ touch('touchend', hit, {id: 1, x: 150, y: 12}, start + 60);+ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(onChange).not.toHaveBeenCalled();+ expect(onChangeEnd).toHaveBeenCalledTimes(1);+ expect(onChangeEnd).toHaveBeenCalledWith(50);+ });++ it('fires onChangeEnd once, from the end of the touch, never again on a later render', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ const onChangeEnd = vi.fn();+ const {rerender} = await renderTouch(+ <Slider+ label="Level"+ valueDisplay="none"+ value={50}+ onChange={() => {}}+ onChangeEnd={onChangeEnd}+ />,+ );+ const hit = hitOf(screen.getByRole('slider'));+ const start = nextStart();+ touch('touchstart', hit, {id: 1, x: 150, y: 12}, start);+ touch('touchend', hit, {id: 1, x: 150, y: 12}, start + 60);+ expect(onChangeEnd).toHaveBeenCalledTimes(1);+ // A later render that changes Slider's own callbacks (single to range)+ // is not a second interaction.+ rerender(+ <Slider+ label="Level"+ valueDisplay="none"+ value={[20, 80]}+ onChange={() => {}}+ onChangeEnd={onChangeEnd}+ />,+ );+ expect(onChangeEnd).toHaveBeenCalledTimes(1);+ });++ it('sets the value from a tap on the track when the finger lifts, the thumb springing there (WCAG 2.5.7)', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ const onChange = vi.fn();+ const onChangeEnd = vi.fn();+ await renderTouch(+ <Controlled initial={50} onChange={onChange} onChangeEnd={onChangeEnd} />,+ );+ const control = document.querySelector(+ '.astryx-slider-control',+ ) as HTMLElement;+ const start = nextStart();+ touch('touchstart', control, {id: 1, x: 250, y: 12}, start);+ // Nothing moves while the finger is down: a tap sets the value on lift.+ expect(onChange).not.toHaveBeenCalled();+ touch('touchend', control, {id: 1, x: 250, y: 12}, start + 80);+ // Frame by frame, as a browser renders the owner between frames.+ for (let frame = 0; frame < 100; frame++) {+ await act(async () => {+ vi.advanceTimersByTime(16);+ });+ }+ // (250 - 10) / (300 - 20) of the range.+ expect(onChange).toHaveBeenLastCalledWith(86);+ expect(onChangeEnd).toHaveBeenCalledTimes(1);+ expect(onChangeEnd).toHaveBeenCalledWith(86);+ expect(screen.getByRole('slider')).toHaveAttribute('aria-valuenow', '86');+ });++ it('plays no end haptic for a tap on the track that sets an end: only a drag and its coast play it', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ haptics.playHaptic.mockClear();+ const onChangeEnd = vi.fn();+ await renderTouch(<Controlled initial={50} onChangeEnd={onChangeEnd} />);+ const control = document.querySelector(+ '.astryx-slider-control',+ ) as HTMLElement;+ const start = nextStart();+ // A tap at the track's far end sets the maximum, as UISlider never does+ // from a tap, so no haptic plays.+ touch('touchstart', control, {id: 1, x: 299, y: 12}, start);+ touch('touchend', control, {id: 1, x: 299, y: 12}, start + 80);+ for (let frame = 0; frame < 100; frame++) {+ await act(async () => {+ vi.advanceTimersByTime(16);+ });+ }+ expect(onChangeEnd).toHaveBeenLastCalledWith(100);+ expect(haptics.playHaptic).not.toHaveBeenCalled();+ // A drag from there into the minimum plays it once.+ dragThumb(+ hitOf(screen.getByRole('slider')),+ {x: 290, y: 12},+ {+ dx: -300,+ steps: 10,+ },+ );+ for (let frame = 0; frame < 100; frame++) {+ await act(async () => {+ vi.advanceTimersByTime(16);+ });+ }+ expect(onChangeEnd).toHaveBeenLastCalledWith(0);+ expect(haptics.playHaptic).toHaveBeenCalledTimes(1);+ });++ it('sets nothing from a touch on the track that moves away before lifting (a swipe)', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ const onChange = vi.fn();+ await renderTouch(<Controlled initial={50} onChange={onChange} />);+ const control = document.querySelector(+ '.astryx-slider-control',+ ) as HTMLElement;+ const start = nextStart();+ // Past the pan's 10 px threshold, the touch is no tap (in a browser the+ // page takes it to scroll).+ touch('touchstart', control, {id: 1, x: 250, y: 12}, start);+ touch('touchmove', control, {id: 1, x: 250, y: 26}, start + 40);+ touch('touchend', control, {id: 1, x: 250, y: 26}, start + 80);+ await act(async () => {+ vi.advanceTimersByTime(1500);+ });+ expect(onChange).not.toHaveBeenCalled();+ });++ it('takes a pen as it takes a finger: on a thumb the value follows its travel, and a tap on the track sets the value on its lift', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ const onChange = vi.fn();+ await renderTouch(<Controlled initial={50} onChange={onChange} />);+ // On the thumb the value follows the pen's travel past the threshold:+ // 50 + (60 - 10) / 300 × 100.+ const thumb = screen.getByRole('slider');+ const hit = hitOf(thumb);+ let t = nextStart();+ pen('pointerdown', hit, 150, 12, t);+ for (let i = 1; i <= 10; i++) {+ pen('pointermove', hit, 150 + 6 * i, 12, t + 16 * i);+ }+ expect(onChange).toHaveBeenLastCalledWith(67);+ // A pen rests before it lifts. So nothing coasts.+ pen('pointerup', hit, 210, 12, t + 400);+ for (let frame = 0; frame < 100; frame++) {+ await act(async () => {+ vi.advanceTimersByTime(16);+ });+ }+ // A pen's tap on the track sets the value on its lift, as a finger's+ // does. The value is (280 - 10) / (300 - 20) of the range.+ const control = document.querySelector(+ '.astryx-slider-control',+ ) as HTMLElement;+ t = nextStart();+ pen('pointerdown', control, 280, 12, t);+ pen('pointerup', control, 280, 12, t + 60);+ for (let frame = 0; frame < 100; frame++) {+ await act(async () => {+ vi.advanceTimersByTime(16);+ });+ }+ expect(onChange).toHaveBeenLastCalledWith(96);+ expect(thumb).toHaveAttribute('aria-valuenow', '96');+ });++ it('re-attaches the thumbs’ gestures when a valueDisplay change remounts them', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ const onChange = vi.fn();+ const view = await renderTouch(+ <Controlled initial={50} onChange={onChange} />,+ );+ // Wrapping each thumb in its value tooltip mounts new thumbs and new+ // touch targets.+ view.rerender(+ <Controlled initial={50} onChange={onChange} valueDisplay="tooltip" />,+ );+ await act(async () => {+ await Promise.resolve();+ });+ const thumb = screen.getByRole('slider');+ dragThumb(hitOf(thumb), {x: 150, y: 12}, {dx: 60, steps: 10, lift: false});+ expect(onChange).toHaveBeenLastCalledWith(67);+ });++ it('moves the thumb under the finger off the render path: it follows even when the owner renders nothing (spec:AST-094 FR9)', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ const onChange = vi.fn();+ // The owner keeps its value: no render follows any move.+ await renderTouch(+ <Slider+ label="Level"+ valueDisplay="none"+ value={50}+ onChange={onChange}+ />,+ );+ const thumb = screen.getByRole('slider');+ dragThumb(hitOf(thumb), {x: 150, y: 12}, {dx: 60, steps: 10, lift: false});+ expect(onChange).toHaveBeenLastCalledWith(67);+ expect(thumb).toHaveAttribute('aria-valuenow', '50');+ // Yet the thumb stands at 67's place along the 280 px travel, written+ // straight to its translate.+ expect(parseFloat(thumb.style.translate)).toBeCloseTo(0.67 * 280, 1);+ });++ it('moves no value on a collapsed track: a drag and its release on 0 px keep the value', async () => {+ stubMatchMedia(true);+ stubControlGeometry(false, 0);+ const onChange = vi.fn();+ await renderTouch(<Controlled initial={50} onChange={onChange} />);+ const thumb = screen.getByRole('slider');+ dragThumb(hitOf(thumb), {x: 0, y: 12}, {dx: 60, steps: 10});+ await act(async () => {+ vi.advanceTimersByTime(1000);+ });+ expect(onChange.mock.calls.filter(([value]) => value !== 50)).toEqual([]);+ expect(thumb).toHaveAttribute('aria-valuenow', '50');+ expect(thumb.style.translate).not.toContain('NaN');+ });++ it('follows the track through the page’s one shared ResizeObserver, not one per slider', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ let created = 0;+ class CountingObserver {+ constructor() {+ created += 1;+ }+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ vi.stubGlobal('ResizeObserver', CountingObserver);+ try {+ await renderTouch(+ <>+ <Slider label="One" valueDisplay="none" value={20} />+ <Slider label="Two" valueDisplay="none" value={80} />+ </>,+ );+ expect(screen.getAllByRole('slider')).toHaveLength(2);+ expect(created).toBe(1);+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it('ends a touch silently when the slider unmounts mid-drag', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});+ const onChange = vi.fn();+ const onChangeEnd = vi.fn();+ const view = await renderTouch(+ <Slider+ label="Level"+ valueDisplay="none"+ value={50}+ onChange={onChange}+ onChangeEnd={onChangeEnd}+ />,+ );+ dragThumb(+ hitOf(screen.getByRole('slider')),+ {x: 150, y: 12},+ {+ dx: 60,+ lift: false,+ },+ );+ expect(onChange).toHaveBeenCalled();+ onChange.mockClear();+ view.unmount();+ await act(async () => {+ await Promise.resolve();+ });+ expect(onChange).not.toHaveBeenCalled();+ expect(onChangeEnd).not.toHaveBeenCalled();+ expect(+ errors.mock.calls.filter(call => String(call[0]).includes('flushSync')),+ ).toEqual([]);+ errors.mockRestore();+ });++ it('cancels a drag when the slider is disabled mid-drag: onChangeEnd fires once, with the value the owner rendered', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});+ const onChange = vi.fn();+ const onChangeEnd = vi.fn();+ const slider = (isDisabled: boolean) => (+ <Slider+ label="Level"+ valueDisplay="none"+ value={50}+ isDisabled={isDisabled}+ onChange={onChange}+ onChangeEnd={onChangeEnd}+ />+ );+ const view = await renderTouch(slider(false));+ const thumb = screen.getByRole('slider');+ dragThumb(hitOf(thumb), {x: 150, y: 12}, {dx: 60, lift: false});+ expect(onChange).toHaveBeenCalled();+ onChange.mockClear();+ view.rerender(slider(true));+ await act(async () => {+ await Promise.resolve();+ });+ // The owner kept 50, so the cancelled drag ends there.+ expect(onChangeEnd).toHaveBeenCalledTimes(1);+ expect(onChangeEnd).toHaveBeenCalledWith(50);+ expect(onChange).not.toHaveBeenCalled();+ // The finger's lift finds nothing left to end.+ fireEvent.pointerUp(thumb, {pointerId: 1, pointerType: 'touch'});+ view.unmount();+ await act(async () => {+ await Promise.resolve();+ });+ expect(onChangeEnd).toHaveBeenCalledTimes(1);+ expect(+ errors.mock.calls.filter(call => String(call[0]).includes('flushSync')),+ ).toEqual([]);+ errors.mockRestore();+ });++ it('a slider unmounted mid-coast stops silently', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ const onChange = vi.fn();+ const onChangeEnd = vi.fn();+ const view = await renderTouch(+ <Controlled initial={20} onChange={onChange} onChangeEnd={onChangeEnd} />,+ );+ dragThumb(+ hitOf(screen.getByRole('slider')),+ {x: 60, y: 12},+ {+ dx: 80,+ steps: 5,+ },+ );+ // Two frames into the coast, before it reports (from its fourth frame).+ await act(async () => {+ vi.advanceTimersByTime(40);+ });+ expect(onChangeEnd).not.toHaveBeenCalled();+ onChange.mockClear();+ view.unmount();+ await act(async () => {+ vi.advanceTimersByTime(1000);+ });+ expect(onChange).not.toHaveBeenCalled();+ expect(onChangeEnd).not.toHaveBeenCalled();+ });++ it('a release coasts to 0.4 of the momentum projection, then onChangeEnd reports once', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ // jsdom has no Web Animations: a running stand-in. So the coast lasts+ // its curve (the animator settles it on its own clock).+ Object.defineProperty(HTMLElement.prototype, 'animate', {+ configurable: true,+ value: () =>+ ({+ finished: new Promise<never>(() => {}),+ cancel: () => {},+ startTime: null,+ }) as unknown as Animation,+ });+ onTestFinished(() => {+ delete (HTMLElement.prototype as {animate?: unknown}).animate;+ });+ const onChange = vi.fn();+ const onChangeEnd = vi.fn();+ await renderTouch(+ <Controlled initial={20} onChange={onChange} onChangeEnd={onChangeEnd} />,+ );+ const thumb = screen.getByRole('slider');+ // 10 moves of 6 px, 16 ms apart: 375 px/s at the lift.+ dragThumb(hitOf(thumb), {x: 60, y: 12}, {dx: 60, steps: 10});+ const liftValue = 20 + Math.round(((60 - 10) / LENGTH) * 100);+ const velocity = 6 / 0.016;+ const target = Math.round(+ liftValue ++ ((UIKIT_SLIDER.releaseProjectionShare *+ projectDistance(velocity, UIKIT_SLIDER.releaseProjectionRate)) /+ LENGTH) *+ 100,+ );+ expect(target).toBeGreaterThan(liftValue);+ expect(onChangeEnd).not.toHaveBeenCalled();+ for (let i = 0; i < 120; i++) {+ // Async. So the coast's completion (a promise) runs between frames.+ await act(async () => {+ vi.advanceTimersByTime(16);+ });+ }+ expect(thumb).toHaveAttribute('aria-valuenow', String(target));+ expect(onChange).toHaveBeenLastCalledWith(target);+ expect(onChangeEnd).toHaveBeenCalledTimes(1);+ expect(onChangeEnd).toHaveBeenCalledWith(target);+ // Handed back to the stylesheet: no inline translate is left.+ expect(thumb.style.translate).toBe('');+ });++ it('a pen lifted while it moves ends its drag at the release, with no coast (component:Slider FR7)', async () => {+ stubMatchMedia(true);+ stubControlGeometry();+ // A running stand-in, as for the finger's coast: a coast that started+ // would carry the value on.+ Object.defineProperty(HTMLElement.prototype, 'animate', {+ configurable: true,+ value: () =>+ ({+ finished: new Promise<never>(() => {}),+ cancel: () => {},+ startTime: null,+ }) as unknown as Animation,+ });+ onTestFinished(() => {+ delete (HTMLElement.prototype as {animate?: unknown}).animate;+ });+ const onChange = vi.fn();+ const onChangeEnd = vi.fn();+ await renderTouch(+ <Controlled initial={20} onChange={onChange} onChangeEnd={onChangeEnd} />,+ );+ const thumb = screen.getByRole('slider');+ const hit = hitOf(thumb);+ // Ten moves of 6 px, 16 ms apart, then the lift 16 ms later. That is+ // 375 px/s at the lift, which a finger's release would coast on.+ const t = nextStart();+ pen('pointerdown', hit, 60, 12, t);+ for (let i = 1; i <= 10; i++) {+ pen('pointermove', hit, 60 + 6 * i, 12, t + 16 * i);+ }+ const liftValue = 20 + Math.round(((60 - 10) / LENGTH) * 100);+ expect(onChange).toHaveBeenLastCalledWith(liftValue);+ pen('pointerup', hit, 120, 12, t + 16 * 11);+ expect(onChangeEnd).toHaveBeenCalledTimes(1);+ expect(onChangeEnd).toHaveBeenCalledWith(liftValue);+ for (let frame = 0; frame < 120; frame++) {+ await act(async () => {+ vi.advanceTimersByTime(16);+ });+ }+ expect(thumb).toHaveAttribute('aria-valuenow', String(liftValue));+ expect(onChange).toHaveBeenLastCalledWith(liftValue);+ expect(onChangeEnd).toHaveBeenCalledTimes(1);+ expect(thumb.style.translate).toBe('');+ });+});diff --git a/packages/core/src/Slider/useSliderTouch.ts b/packages/core/src/Slider/useSliderTouch.tsnew file mode 100644index 0000000000..f8d7f77c17--- /dev/null+++ b/packages/core/src/Slider/useSliderTouch.ts@@ -0,0 +1,78 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useSliderTouch.ts+ * @input Slider's value model and parts, and sliderTouchController.ts+ * @output Exports `useSliderTouch` (the React wiring) and the+ * `SliderTouchModel` and `SliderTouchParts` types+ * @position Internal to Slider. It is the touch layer's one import site, so+ * a desktop build can swap that module whole.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Slider/sliderTouchController.ts+ * - /packages/core/src/Slider/Slider.tsx (the model and the parts)+ * - /packages/core/src/Slider/useSliderTouch.test.tsx+ */++import {useEffect, useState} from 'react';+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';+import {+ SliderTouchController,+ type SliderTouchModel,+ type SliderTouchParts,+} from './sliderTouchController';++export type {SliderTouchModel, SliderTouchParts} from './sliderTouchController';++export interface UseSliderTouchOptions {+ /** The slider is enabled: its gestures attach for every pointer. */+ readonly isEnabled: boolean;+ readonly model: SliderTouchModel;+ readonly getParts: () => SliderTouchParts | null;+ /** Re-attaches when the thumbs or the orientation change. */+ readonly thumbCount: number;+ /**+ * Whether each thumb renders inside its value tooltip: changing it mounts+ * new thumbs. So the gestures re-attach.+ */+ readonly thumbsWrapped: boolean;+}++/**+ * Wires UISlider's tracking to a rendered Slider for every pointer, while it+ * is enabled. Slider's own pointer handlers then take only a mouse press on+ * the track.+ */+export function useSliderTouch({+ isEnabled,+ model,+ getParts,+ thumbCount,+ thumbsWrapped,+}: UseSliderTouchOptions): void {+ // The parts getter reads only refs. So the first one stays current.+ const [controller] = useState(+ () => new SliderTouchController(model, getParts),+ );+ // Hands the controller this render's model: the values and callbacks it+ // reads from gesture callbacks outside React's render.+ useIsomorphicLayoutEffect(() => {+ controller.setModel(model);+ });+ const {isHorizontal} = model;+ // Synchronizes the thumbs with the document's gesture host. Their+ // PressTrackers and pans attach while the slider is enabled. They detach,+ // ending any interaction silently, when it is disabled or the thumbs+ // change.+ useEffect(() => {+ if (!isEnabled) {+ return undefined;+ }+ return controller.attach();+ }, [controller, isEnabled, thumbCount, isHorizontal, thumbsWrapped]);+ // Releases the controller's animators and gesture host listeners on+ // unmount.+ useEffect(() => () => controller.dispose(), [controller]);+}diff --git a/packages/core/src/motion/uikit/index.ts b/packages/core/src/motion/uikit/index.tsindex a63ae7d6ea..f093e17f31 100644--- a/packages/core/src/motion/uikit/index.ts+++ b/packages/core/src/motion/uikit/index.ts@@ -4,7 +4,7 @@* @file index.ts* @input The domain files of the UIKit constants table* @output Re-exports `springs` and one constant per spring (`SHEET_PRESENT_SPRING`,- * …), `scroll`, `timing`, `navigation` and the+ * …), `scroll`, `timing`, `navigation`, the `slider` domain and the* gesture thresholds (one `UIKIT_*` group per recognizer, their union* `UIKIT_GESTURES`, and the haptic tables)* @position Entry of the UIKit constants table (motion/uikit). Internal to@@ -40,6 +40,7 @@ export {} from './gestures';export {navigation, registerNavigationTable} from './navigation';export {registerScrollTable, scroll} from './scroll';+export {slider} from './slider';export {ACTION_SHEET_DISMISS_SPRING,ACTION_SHEET_PRESENT_SPRING,diff --git a/packages/core/src/motion/uikit/slider.test.ts b/packages/core/src/motion/uikit/slider.test.tsnew file mode 100644index 0000000000..9e8e53af94--- /dev/null+++ b/packages/core/src/motion/uikit/slider.test.ts@@ -0,0 +1,172 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file slider.test.ts+ * @input vitest, the slider domain of the UIKit constants table, the spring+ * solver and the momentum projection, and samples of UIKit's own UISlider+ * @output Holds `slider` to UISlider's measured behavior on the iOS 26.2+ * simulator. It checks the value per `valueChanged` against the tracking+ * rule. It checks the lift and drop against the thumb's per-frame width,+ * and the coast against the per-frame value after a lift+ * @position Testing. Parity of the slider constants (law P4, unit layer).+ * The browser layer comes with Slider's touch presentation, which reads+ * this table.+ */++import {describe, expect, it} from 'vitest';+import {projectDistance} from '../projection';+import {solveSpring, toSpring} from '../spring';+import {UIKIT_GESTURES} from './gestures';+import {slider} from './slider';++/** The lab's slider: 300 pt long, value 0…1. */+const TRACK = 300;++/**+ * `valueChanged` during a 200 pt/s drag from 0.2, from the UIKit lab on the+ * iOS 26.2 simulator. Each sample is the finger's travel since touch-down+ * (pt) and the value UIKit reported for it. The pan began at 10.33 pt.+ */+const TRACKING = {+ startValue: 0.2,+ events: [+ [15.33, 0.21777777],+ [22.0, 0.24000001],+ [27.0, 0.25666666],+ [42.0, 0.30666667],+ [60.33, 0.36777779],+ [78.67, 0.42888889],+ [97.0, 0.49000001],+ [115.0, 0.55000001],+ ],+} as const;++/**+ * The thumb lens's width (pt) per frame from touch-down during an 800 ms+ * hold, and from the lift after it (UIKit lab, iOS 26.2 simulator).+ */+const LIFT = [+ [10.7, 37],+ [44.0, 47.1],+ [77.4, 54.93],+ [110.7, 58.6],+ [144.0, 59.39],+ [177.4, 58.84],+ [210.7, 58.02],+ [244.0, 57.43],+ [277.4, 57.27],+ [310.7, 57.35],+] as const;+const DROP = [+ [13.3, 57.35],+ [46.7, 54.62],+ [80.0, 50.8],+ [113.3, 46.87],+ [146.7, 43.39],+ [180.0, 40.62],+ [213.3, 38.6],+ [246.7, 37.27],+ [280.0, 36.5],+ [313.3, 36.13],+ [346.7, 36.04],+ [380.0, 36.12],+ [413.3, 36.27],+ [446.7, 36.46],+] as const;+const REST_WIDTH = 37;++/**+ * The value per frame after a lift at 126.9 pt/s (UIKit lab: grabbed 8 pt+ * off the thumb's center, dragged 60 pt). The coast+ * shows on screen 38 ms after the lift.+ */+const COAST = {+ velocity: 126.9,+ liftValue: 0.6667,+ startMs: 38,+ samples: [+ [47.4, 0.6705],+ [80.7, 0.682],+ [114.0, 0.6905],+ [147.4, 0.6964],+ [180.7, 0.7005],+ [214.0, 0.7033],+ [247.4, 0.7051],+ [280.7, 0.7064],+ [314.0, 0.7071],+ [347.4, 0.7077],+ [380.7, 0.708],+ [414.0, 0.7085],+ [480.7, 0.7085],+ ],+} as const;++function rms(errors: ReadonlyArray<number>): number {+ return Math.sqrt(+ errors.reduce((sum, error) => sum + error * error, 0) / errors.length,+ );+}++describe('slider under Reduce Motion', () => {+ it('keeps no motion of its own under Reduce Motion (design:reduced-motion DR4)', () => {+ expect(Object.keys(slider)).not.toContain('reducedMotion');+ });+});++describe('slider (UISlider) constants against UIKit', () => {+ it('the touch target is the thumb grown by its hit insets', () => {+ // 37 × 24 pt thumb, insets 5.5 pt left and right, 12 pt above and below.+ expect(37 + 2 * 5.5).toBe(slider.thumbHitTarget);+ expect(24 + 2 * 12).toBe(slider.thumbHitTarget);+ });++ it('the value is the start value plus the travel past the pan threshold over the track length', () => {+ const hysteresis = UIKIT_GESTURES.pan.hysteresis.value;+ for (const [travel, value] of TRACKING.events) {+ const model =+ TRACKING.startValue ++ ((travel - hysteresis) / TRACK) * slider.trackingGain;+ expect(model).toBeCloseTo(value, 4);+ }+ });++ it('the lift and the drop follow the thumb lens’s measured width', () => {+ const lifted = REST_WIDTH * slider.liftScale;+ expect(lifted).toBeCloseTo(57.35, 1);+ const lift = solveSpring(toSpring(slider.liftSpring), {+ from: REST_WIDTH,+ to: lifted,+ });+ const liftErrors = LIFT.map(([ms, width]) => lift.value(ms / 1000) - width);+ // The fit's rms over every frame is 0.31 pt. Over these samples, 0.41.+ expect(rms(liftErrors)).toBeLessThan(0.5);+ const drop = solveSpring(toSpring(slider.dropSpring), {+ from: lifted,+ to: REST_WIDTH,+ });+ const dropErrors = DROP.map(([ms, width]) => drop.value(ms / 1000) - width);+ // The best fit, 0.49 s, leaves 0.10 pt. The read 0.5 s, 0.20 pt.+ expect(rms(dropErrors)).toBeLessThan(0.25);+ });++ it('the release coasts on the release spring to 0.4 of the momentum projection', () => {+ const projected =+ slider.releaseProjectionShare *+ projectDistance(COAST.velocity, slider.releaseProjectionRate);+ // 12.64 pt predicted; UIKit travelled 12.56 pt.+ expect(projected).toBeCloseTo(12.64, 1);+ const target = COAST.liftValue + projected / TRACK;+ const coast = solveSpring(toSpring(slider.releaseSpring), {+ from: COAST.liftValue,+ to: target,+ velocity: COAST.velocity / TRACK,+ });+ const errors = COAST.samples.map(+ ([ms, value]) =>+ (coast.value(Math.max(0, ms - COAST.startMs) / 1000) - value) * TRACK,+ );+ // In pt of the track.+ expect(rms(errors)).toBeLessThan(0.15);+ expect(Math.max(...errors.map(Math.abs))).toBeLessThan(0.35);+ });+});diff --git a/packages/core/src/motion/uikit/slider.ts b/packages/core/src/motion/uikit/slider.tsnew file mode 100644index 0000000000..fd4e29717b--- /dev/null+++ b/packages/core/src/motion/uikit/slider.ts@@ -0,0 +1,105 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file slider.ts+ * @input Nothing: data only+ * @output Exports `slider`: UISlider's hit target, tracking rule, release+ * coast, lift, drop and end haptic, measured on the iOS 26.2 simulator+ * @position The slider domain of the UIKit constants table (motion/uikit).+ * Lengths are in pt (CSS px). Tests check each leaf's `@source`.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Slider/sliderTouchController.ts+ * - /packages/core/src/Slider/Slider.tsx+ * - /packages/core/src/motion/uikit/slider.test.ts+ */++import {SLIDER_RELEASE_SPRING} from './springs';++/**+ * UISlider's touch values: hit target, tracking, release coast, lift, drop+ * and the end-of-track haptic.+ */+export const slider = {+ /**+ * The thumb's touch target, a square in pt centered on the thumb. It is+ * the 37 × 24 pt thumb grown by its hit edge insets: 12 pt above and+ * below, 5.5 pt left and right. UIKit hit-tests inside the control's frame+ * first, so the lab's 40 pt frame clipped it to 48 × 40.+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro.+ * `_thumbHitEdgeInsets` reads {−12, −5.5, −12, −5.5}. Touch-downs on a+ * 4 pt grid take the thumb from −24 to +20 pt in x. A track tap away+ * from the thumb moves nothing. Oct 23 2026+ */+ thumbHitTarget: 48,+ /**+ * Value range per track length of finger travel. The value moves by+ * (max − min) × translation ÷ the track's full length. The translation+ * counts from the pan's threshold: the touch-down point plus 10 pt along+ * the track. 1 means one full range per track length.+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro. In+ * drags at 120 to 2000 pt/s, each event's value is v0 plus the+ * translation past 10 pt ÷ 300. Past the max end, the value leaves 1+ * only once the finger comes back past where it reached 1. Oct 23 2026+ */+ trackingGain: 1,+ /**+ * The coast after the lift. The thumb and the value spring from where the+ * finger left them to the projected target, with the release velocity.+ * Critically damped, it never overshoots a target ahead of it.+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro. The+ * `UIViewSpringAnimationBehavior` at the lift reads response 0.4 and+ * damping ratio 1. Four releases fit it per frame, at rms 0.11 pt or+ * less. Oct 23 2026+ */+ releaseSpring: SLIDER_RELEASE_SPRING,+ /**+ * The deceleration rate of the coast's momentum projection, per ms+ * (WWDC18's `project`). It is not UIScrollView's normal rate (0.998), so+ * pass it to the projection explicitly.+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro. The+ * release behavior's projection deceleration reads 0.996. Oct 23 2026+ */+ releaseProjectionRate: 0.996,+ /**+ * How much of the projection the coast travels. The target is the lift+ * value plus this share of the projected distance. A finger lifted outside+ * the control's tracking bounds coasts back to the lift value instead.+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro. The+ * release behavior's target smoothing reads 0.4. A 126.9 pt/s release+ * travels 12.56 pt, against 12.64 predicted. Oct 23 2026+ */+ releaseProjectionShare: 0.4,+ /**+ * The thumb's growth under a finger, uniform about its center (37 × 24 to+ * 57.35 × 37.2 pt).+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro. The lens+ * frame settled during an 800 ms hold. Oct 23 2026+ */+ liftScale: 1.55,+ /**+ * The lift: the thumb grows to `liftScale` when the finger lands.+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro. The lens+ * width per frame in an 800 ms hold fits one spring at rms 0.31 pt.+ * Oct 23 2026+ */+ liftSpring: {response: 0.215, dampingRatio: 0.6},+ /**+ * The drop: the thumb shrinks back to its rest size when the finger lifts,+ * while the coast runs.+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro. The+ * lens's spring at the lift of an 800 ms hold reads response 0.5 s and+ * damping ratio 0.7. The width per frame fits it at rms 0.10 pt.+ * Oct 23 2026+ */+ dropSpring: {response: 0.5, dampingRatio: 0.7},+ /**+ * The feedback each time the value reaches an end, once per entry. It+ * re-arms when the value leaves the end, in the drag and the coast. UIKit+ * plays "Micro Tap Medium", and the web stand-in is the closest kind.+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro. The+ * haptics log of drags into both ends shows the fluid slider generator's+ * "Micro Tap Medium" once per entry. Oct 23 2026+ */+ endHaptic: 'impactMedium',+} as const;diff --git a/packages/core/src/motion/uikit/springs.ts b/packages/core/src/motion/uikit/springs.tsindex 4cdcde8ecc..4181606555 100644--- a/packages/core/src/motion/uikit/springs.ts+++ b/packages/core/src/motion/uikit/springs.ts@@ -454,6 +454,33 @@ export const KEYBOARD_SPRING = {*/export const BANNER_SPRING = {mass: 3, stiffness: 1000, damping: 500} as const;+/**+ * UISlider's release: after a finger lifts, the thumb settles on this spring+ * toward 0.4 of the release's momentum projection. It is critically damped,+ * so it never overshoots a target ahead of it.+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro. The+ * `UIViewSpringAnimationBehavior` at the lift reads response 0.4 and+ * damping ratio 1. Four releases fit it per frame (the UIKit slider+ * table). Oct 23 2026+ */+export const SLIDER_RELEASE_SPRING = {response: 0.4, dampingRatio: 1} as const;++/**+ * UISlider's lift: a finger's touch-down scales the thumb up on this spring.+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro. The+ * thumb's scale per frame after touch-down (the UIKit slider table).+ * Oct 23 2026+ */+export const SLIDER_LIFT_SPRING = {response: 0.215, dampingRatio: 0.6} as const;++/**+ * UISlider's drop: the lift's end scales the thumb back down on this spring.+ * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro. The+ * thumb's scale per frame after the lift (the UIKit slider table).+ * Oct 23 2026+ */+export const SLIDER_DROP_SPRING = {response: 0.5, dampingRatio: 0.7} as const;+/*** Every spring above, by row name: the table the existing readers use. A* component imports only the rows it plays (`architecture:component-style-authoring`@@ -494,10 +521,15 @@ export const springs = {segmentedThumb: SEGMENTED_THUMB_SPRING,keyboard: KEYBOARD_SPRING,banner: BANNER_SPRING,+ sliderRelease: SLIDER_RELEASE_SPRING,+ sliderLift: SLIDER_LIFT_SPRING,+ sliderDrop: SLIDER_DROP_SPRING,} as const;/**- * The springs spec:AST-094 FR4 names: the only ones that are motion roles.+ * The only springs that are motion roles. The touch presentations' record+ * names some, and a component's own record names others, such as Slider's+ * three. The generated motion role table lists each with its record.* The registry takes these rows alone, so registering ships no other spring.*/const SPRING_ROLES = {@@ -516,10 +548,13 @@ const SPRING_ROLES = {contextMenuLift: CONTEXT_MENU_LIFT_SPRING,contextMenuDismiss: CONTEXT_MENU_DISMISS_SPRING,contextMenuMorph: CONTEXT_MENU_MORPH_SPRING,+ sliderRelease: SLIDER_RELEASE_SPRING,+ sliderLift: SLIDER_LIFT_SPRING,+ sliderDrop: SLIDER_DROP_SPRING,};/**- * Registers the springs spec:AST-094 FR4 names as internal motion roles+ * Registers the role springs (`SPRING_ROLES`) as internal motion roles* (motion/roles.ts), by their row names (`springs.settle`). Every other* spring, UIKit's menu spring under Reduce Motion and the keyboard's* included, is not a role. Nothing registers on import: the touch code thatdiff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjsindex 696e106705..b5dc21da1b 100644--- a/scripts/touch-support-bundle.test.mjs+++ b/scripts/touch-support-bundle.test.mjs@@ -118,7 +118,10 @@ function filesUnder(dir, pattern) {* gives a component its gesture adds that component's import, and each import* that reaches it, with a comment naming the gesture.*/-const GESTURE_USERS = new Set([]);+const GESTURE_USERS = new Set([+ // Slider's thumb.+ 'Slider',+]);/** Public imports that carry no gesture code, whatever the list above says. */const NEVER_GESTURE_USERS = ['Button', 'TextInput'];