Skip to content

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

TypeScript

fix(Slider): two coincident range thumbs can be dragged apart (#8151)

Christopher Chedeau6a79bfb74848
diff --git a/.changeset/slider-coincident-range-thumbs.md b/.changeset/slider-coincident-range-thumbs.md
new file mode 100644
index 0000000000..09177f2242
--- /dev/null
+++ b/.changeset/slider-coincident-range-thumbs.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Slider: a range slider whose two thumbs sit on the same value can be dragged apart again. Only one of the two thumbs can travel toward where the pointer goes: a press on the track beside them picks the thumb on its side, and a press on the thumbs themselves waits for the pointer to move, so the direction of that first movement picks the thumb, which takes the drag's focus, pressed paint and value tooltip. Such a drag always follows the pointer: once the pointer passes the other thumb, the dragged thumb stops against it and the other one takes the drag, so a first step that drifts the wrong way never sticks it. Before, two thumbs at the maximum could not be dragged down, and a press on the track above two coincident thumbs moved neither.
+
+@vjeux
diff --git a/packages/core/src/Slider/Slider.spec.md b/packages/core/src/Slider/Slider.spec.md
index 17552e5d07..1011212372 100644
--- a/packages/core/src/Slider/Slider.spec.md
+++ b/packages/core/src/Slider/Slider.spec.md
@@ -78,13 +78,14 @@ 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, 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 |
+| 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, 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 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. 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 |
### Observed current target asymmetry
@@ -225,15 +226,16 @@ separately listed value tooltip retains Tooltip's target.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
-| FR1 | `Slider.test.tsx` structure, range, and marks suites | Single, range, horizontal, vertical, marks | Removing or misaligning stable parts breaks existing role, position, or mark assertions. | `audit:Slider/anatomy` |
-| AR1 | Slider accessibility contract (`internal/a11y-spec`, pending) bound to Slider; disabled-thumb Tab stop pending conformance; in jsdom and Chromium; `Slider.test.tsx` keyboard suites, including "follows the mirrored track under RTL: ArrowLeft increases, ArrowRight decreases, Up/Down unchanged" and "keeps ArrowLeft decreasing on a vertical track under RTL"; the Page, Home/End and Up/Down cases under the contract | Single and range; horizontal LTR and RTL; vertical; disabled; formatted value | A thumb loses its role, name or value properties; an arrow, Page, Home or End key stops stepping or steps against the mirrored track; a range thumb crosses the other | `audit:Slider/accessibility` |
-| FR2 | `Slider.test.tsx`, `themingTargets.test.ts`, generated probe theme, and Chromium | Root, horizontal/vertical control, disabled control, track, and thumb | A target class/state is missing, undocumented, or placed outside its owning anatomy. | `audit:Slider/theming` |
-| FR3 | Source and consumer-doc review | Filled range, marks, labels, adjacent text value | A missing target is inaccurately documented as present or intentionally permanent. | `audit:Slider/theming` |
-| 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` |
-| 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` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- |
+| FR1 | `Slider.test.tsx` structure, range, and marks suites | Single, range, horizontal, vertical, marks | Removing or misaligning stable parts breaks existing role, position, or mark assertions. | `audit:Slider/anatomy` |
+| AR1 | Slider accessibility contract (`internal/a11y-spec`, pending) bound to Slider; disabled-thumb Tab stop pending conformance; in jsdom and Chromium; `Slider.test.tsx` keyboard suites, including "follows the mirrored track under RTL: ArrowLeft increases, ArrowRight decreases, Up/Down unchanged" and "keeps ArrowLeft decreasing on a vertical track under RTL"; the Page, Home/End and Up/Down cases under the contract | Single and range; horizontal LTR and RTL; vertical; disabled; formatted value | A thumb loses its role, name or value properties; an arrow, Page, Home or End key stops stepping or steps against the mirrored track; a range thumb crosses the other | `audit:Slider/accessibility` |
+| FR2 | `Slider.test.tsx`, `themingTargets.test.ts`, generated probe theme, and Chromium | Root, horizontal/vertical control, disabled control, track, and thumb | A target class/state is missing, undocumented, or placed outside its owning anatomy. | `audit:Slider/theming` |
+| FR3 | Source and consumer-doc review | Filled range, marks, labels, adjacent text value | A missing target is inaccurately documented as present or intentionally permanent. | `audit:Slider/theming` |
+| 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 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, or keeps its focus, pressed state or tooltip on a thumb the drag has left | `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 and
disabled state. Source/metadata guards cover all four target declarations. The
diff --git a/packages/core/src/Slider/Slider.test.tsx b/packages/core/src/Slider/Slider.test.tsx
index 26798f89a4..1bd65bcac6 100644
--- a/packages/core/src/Slider/Slider.test.tsx
+++ b/packages/core/src/Slider/Slider.test.tsx
@@ -1659,3 +1659,288 @@ describe('pressed state', () => {
expect(declaresPressedOverlay(thumb)).toBe(false);
});
});
+
+describe('coincident range thumbs', () => {
+ // A 200 px control: the thumbs travel from 10 px (value 0) to 190 px
+ // (value 100), so value = (x - 10) / 1.8.
+ function mockGroupRect() {
+ screen.getByRole('group').getBoundingClientRect = () => ({
+ left: 0,
+ top: 0,
+ right: 200,
+ bottom: 20,
+ width: 200,
+ height: 20,
+ x: 0,
+ y: 0,
+ toJSON: () => {},
+ });
+ }
+
+ function ControlledRange({
+ initial,
+ onChange,
+ }: {
+ initial: [number, number];
+ onChange: (value: [number, number]) => void;
+ }) {
+ const [value, setValue] = useState<[number, number]>(initial);
+ return (
+ <Slider
+ label="Price"
+ value={value}
+ min={0}
+ max={100}
+ onChange={(next: [number, number]) => {
+ onChange(next);
+ setValue(next);
+ }}
+ />
+ );
+ }
+
+ it('drags the lower thumb when a drag from two thumbs at the maximum goes toward the minimum', () => {
+ const onChange = vi.fn();
+ render(<ControlledRange initial={[100, 100]} onChange={onChange} />);
+ 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});
+
+ expect(onChange).toHaveBeenLastCalledWith([50, 100]);
+ expect(start).toHaveAttribute('aria-valuenow', '50');
+ expect(end).toHaveAttribute('aria-valuenow', '100');
+ });
+
+ it('hands the drag, its focus and its pressed paint to the thumb the first movement picks', () => {
+ const onChange = vi.fn();
+ render(<ControlledRange initial={[50, 50]} onChange={onChange} />);
+ 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.
+ expect(declaresPressedOverlay(end)).toBe(true);
+ expect(onChange).toHaveBeenLastCalledWith([50, 50]);
+
+ fireEvent.pointerMove(end, {clientX: 64, clientY: 10, pointerId: 1});
+ 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});
+ 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});
+ expect(declaresPressedOverlay(end)).toBe(false);
+ });
+
+ it('commits a press beside the shared value to no thumb until the pointer moves', () => {
+ const onChange = vi.fn();
+ const {unmount} = render(
+ <ControlledRange initial={[80, 80]} onChange={onChange} />,
+ );
+ 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});
+ expect(onChange).toHaveBeenLastCalledWith([80, 90]);
+ fireEvent.pointerUp(end, {clientX: 172, clientY: 10, pointerId: 1});
+ 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});
+ expect(onChange).toHaveBeenLastCalledWith([30, 80]);
+ expect(start).toHaveAttribute('aria-valuenow', '30');
+ });
+
+ it('picks the thumb by the mirrored direction under RTL', () => {
+ const onChange = vi.fn();
+ const realGetComputedStyle = window.getComputedStyle;
+ // Under RTL the inline start is the right edge: value = (190 - x) / 1.8.
+ const asRtl = () => {
+ const group = screen.getByRole('group');
+ return vi
+ .spyOn(window, 'getComputedStyle')
+ .mockImplementation((el: Element, pseudo?: string | null) =>
+ el === group
+ ? ({direction: 'rtl'} as CSSStyleDeclaration)
+ : realGetComputedStyle(el, pseudo ?? undefined),
+ );
+ };
+ const {unmount} = render(
+ <ControlledRange initial={[50, 50]} onChange={onChange} />,
+ );
+ mockGroupRect();
+ 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});
+ expect(onChange).toHaveBeenLastCalledWith([50, 80]);
+ fireEvent.pointerUp(end, {clientX: 46, clientY: 10, pointerId: 1});
+ spy.mockRestore();
+ unmount();
+
+ // Rightward is toward the minimum: the lower thumb follows.
+ render(<ControlledRange initial={[50, 50]} onChange={onChange} />);
+ mockGroupRect();
+ 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});
+ expect(onChange).toHaveBeenLastCalledWith([20, 50]);
+ expect(document.activeElement).toBe(start);
+ spy.mockRestore();
+ });
+
+ it('hands a drag from coincident thumbs to the other thumb once the pointer passes their value the other way', () => {
+ const onChange = vi.fn();
+ 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});
+ expect(onChange).toHaveBeenLastCalledWith([80, 99]);
+ fireEvent.pointerUp(end, {clientX: 188.2, clientY: 10, pointerId: 1});
+ });
+
+ it('measures the first movement from a press on a mark label against the press, not the mark', () => {
+ const onChange = vi.fn();
+ function MarkedRange() {
+ const [value, setValue] = useState<[number, number]>([50, 50]);
+ return (
+ <Slider
+ label="Price"
+ value={value}
+ min={0}
+ max={100}
+ marks={[{value: 50, label: '50%'}]}
+ onChange={(next: [number, number]) => {
+ onChange(next);
+ setValue(next);
+ }}
+ />
+ );
+ }
+ render(<MarkedRange />);
+ mockGroupRect();
+ const label = screen
+ .getByText('50%')
+ .closest<HTMLElement>('[data-mark-value]')!;
+ // A press on the label right of its mark (52), dragged toward the
+ // minimum: the lower thumb follows, as it does on main.
+ fireEvent.pointerDown(label, {clientX: 104, clientY: 10, pointerId: 1});
+ fireEvent.pointerMove(label, {clientX: 103, clientY: 10, pointerId: 1});
+ fireEvent.pointerMove(label, {clientX: 46, clientY: 10, pointerId: 1});
+ expect(onChange).toHaveBeenLastCalledWith([20, 50]);
+ fireEvent.pointerUp(label, {clientX: 46, clientY: 10, pointerId: 1});
+ });
+
+ it('keeps a drag that began with a track press beside coincident thumbs on the thumb it moved', () => {
+ const onChange = vi.fn();
+ render(<ControlledRange initial={[50, 50]} onChange={onChange} />);
+ mockGroupRect();
+ const track = screen.getByRole('group');
+ // A track press below the shared value takes the lower thumb there; the
+ // drag on to the maximum stops it against the upper thumb, as the same
+ // drag from separate thumbs does. Only a drag that began on the shared
+ // thumbs hands itself over.
+ fireEvent.pointerDown(track, {clientX: 46, clientY: 10, pointerId: 1});
+ expect(onChange).toHaveBeenLastCalledWith([20, 50]);
+ fireEvent.pointerMove(track, {clientX: 154, clientY: 10, pointerId: 1});
+ expect(onChange).toHaveBeenLastCalledWith([50, 50]);
+ fireEvent.pointerUp(track, {clientX: 154, clientY: 10, pointerId: 1});
+ });
+
+ it('closes the value tooltip of the thumb a drag was handed away from', () => {
+ render(<ControlledRange initial={[50, 50]} onChange={vi.fn()} />);
+ mockGroupRect();
+ const [start, end] = screen.getAllByRole('slider');
+ const tipOf = (thumb: HTMLElement) =>
+ document.getElementById(
+ (thumb.getAttribute('aria-describedby') ?? '')
+ .split(' ')
+ .find(
+ id =>
+ 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});
+ expect(document.activeElement).toBe(start);
+ expect(tipOf(end)).not.toHaveAttribute('popover-open');
+ });
+
+ it('moves the upper thumb for a track press above the shared value', () => {
+ const onChange = vi.fn();
+ render(<ControlledRange initial={[50, 50]} onChange={onChange} />);
+ mockGroupRect();
+ const [, end] = screen.getAllByRole('slider');
+
+ fireEvent.pointerDown(screen.getByRole('group'), {
+ clientX: 154,
+ clientY: 10,
+ pointerId: 1,
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith([50, 80]);
+ expect(declaresPressedOverlay(end)).toBe(true);
+ expect(document.activeElement).toBe(end);
+ });
+
+ it('moves the lower thumb for a track press below the shared value', () => {
+ const onChange = vi.fn();
+ render(<ControlledRange initial={[50, 50]} onChange={onChange} />);
+ mockGroupRect();
+ const [start] = screen.getAllByRole('slider');
+
+ fireEvent.pointerDown(screen.getByRole('group'), {
+ clientX: 46,
+ clientY: 10,
+ pointerId: 1,
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith([20, 50]);
+ expect(document.activeElement).toBe(start);
+ });
+
+ it('still drags the upper thumb from two thumbs at the minimum toward the maximum', () => {
+ const onChange = vi.fn();
+ render(<ControlledRange initial={[0, 0]} onChange={onChange} />);
+ mockGroupRect();
+ const [, end] = screen.getAllByRole('slider');
+
+ fireEvent.pointerDown(end, {clientX: 10, clientY: 10, pointerId: 1});
+ fireEvent.pointerMove(end, {clientX: 100, clientY: 10, pointerId: 1});
+
+ expect(onChange).toHaveBeenLastCalledWith([0, 50]);
+ });
+});
diff --git a/packages/core/src/Slider/Slider.tsx b/packages/core/src/Slider/Slider.tsx
index 4aec05427a..cc87803e62 100644
--- a/packages/core/src/Slider/Slider.tsx
+++ b/packages/core/src/Slider/Slider.tsx
@@ -5,7 +5,7 @@
/**
* @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
+ * @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
* @position Core implementation; consumed by index.ts, tested by Slider.test.tsx
*
* SYNC: When modified, update these files to stay in sync:
@@ -672,8 +672,24 @@ export function Slider({ref, ...props}: SliderProps) {
[isRange, values],
);
+ // The pointer's value at a press on two coincident thumbs, while no
+ // movement has said which way the drag goes; the first value off it picks
+ // the thumb that can travel that way (see handlePointerMove).
+ const coincidentDragRef = useRef<number | null>(null);
+ // Whether the drag in progress began on two coincident thumbs: such a drag
+ // can always follow the pointer, so when the dragged thumb is held against
+ // the other one and the pointer passes it, the other thumb takes the drag.
+ const coincidentOriginRef = useRef(false);
+
const updateValue = useCallback(
- (thumbIndex: number, newVal: number, snap = true) => {
+ (
+ thumbIndex: number,
+ newVal: number,
+ snap = true,
+ // The other thumb's values to start from, when one event moves both
+ // (a drag handed from one coincident thumb to the other).
+ from: ReadonlyArray<number> = values,
+ ) => {
if (isDisabled) {
return;
}
@@ -687,7 +703,7 @@ export function Slider({ref, ...props}: SliderProps) {
);
if (isRange) {
- const currentValues = [...values] as [number, number];
+ const currentValues = [...from] as [number, number];
currentValues[thumbIndex] = clamped;
// Enforce minStepsBetweenThumbs
@@ -765,6 +781,8 @@ export function Slider({ref, ...props}: SliderProps) {
detachLostCaptureRef.current = null;
draggingThumbRef.current = null;
dragPointerRef.current = null;
+ coincidentDragRef.current = null;
+ coincidentOriginRef.current = false;
setDraggingThumb(null);
fireChangeEnd();
}
@@ -804,13 +822,33 @@ export function Slider({ref, ...props}: SliderProps) {
pressedThumb == null || thumbs == null
? -1
: Array.from(thumbs).indexOf(pressedThumb);
- // A direct thumb press owns that thumb even when range values coincide.
- // Track and mark presses still choose the nearest value.
- const thumbIndex =
+ // A direct thumb press owns that thumb; track and mark presses choose
+ // the nearest value. Two thumbs on one value are the exception: only
+ // one of them can travel toward where the pointer goes. A track press
+ // beside them picks the thumb on its side. A press on the thumbs
+ // themselves (or on their shared value) moves nothing: the pressed
+ // thumb holds the press until the pointer moves, and the direction of
+ // that first movement from the press picks the thumb.
+ const isCoincident = isRange && values[0] === values[1];
+ let thumbIndex =
pressedThumbIndex >= 0 ? pressedThumbIndex : getClosestThumb(newVal);
+ const parks =
+ isCoincident && (pressedThumbIndex >= 0 || newVal === values[0]);
+ // The first movement is measured from the pointer itself, not from a
+ // mark it pressed (a wide label sits away from its mark's value).
+ coincidentDragRef.current = parks
+ ? getValueFromPosition(e.clientX, e.clientY)
+ : null;
+ // Only a drag that began on the shared thumbs, the press that waited for
+ // the first movement, hands itself to the other thumb (FR6); a track
+ // press beside them already picked its thumb.
+ coincidentOriginRef.current = parks;
+ if (isCoincident && !parks) {
+ thumbIndex = newVal > values[0] ? 1 : 0;
+ }
draggingThumbRef.current = thumbIndex;
setDraggingThumb(thumbIndex);
- updateValue(thumbIndex, newVal);
+ updateValue(thumbIndex, parks ? values[thumbIndex] : newVal);
// Focus the thumb that owns this drag.
thumbs?.[thumbIndex]?.focus();
@@ -839,7 +877,15 @@ export function Slider({ref, ...props}: SliderProps) {
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
}
},
- [isDisabled, getValueFromPosition, getClosestThumb, updateValue, endDrag],
+ [
+ isDisabled,
+ isRange,
+ values,
+ getValueFromPosition,
+ getClosestThumb,
+ updateValue,
+ endDrag,
+ ],
);
const handlePointerMove = useCallback(
@@ -852,6 +898,48 @@ export function Slider({ref, ...props}: SliderProps) {
return;
}
const newVal = getValueFromPosition(e.clientX, e.clientY);
+ // Hands the drag to a thumb, with its focus and pressed paint.
+ const handTo = (thumbIndex: number) => {
+ if (thumbIndex === draggingThumbRef.current) {
+ return;
+ }
+ draggingThumbRef.current = thumbIndex;
+ setDraggingThumb(thumbIndex);
+ const thumbs =
+ trackRef.current?.querySelectorAll<HTMLElement>('[role="slider"]');
+ thumbs?.[thumbIndex]?.focus();
+ setKeyboardFocusThumb(null);
+ };
+ const pressValue = coincidentDragRef.current;
+ if (pressValue !== null) {
+ if (newVal === pressValue) {
+ return;
+ }
+ // The first movement from a press on coincident thumbs hands the
+ // drag to the thumb that can travel that way.
+ coincidentDragRef.current = null;
+ handTo(newVal > pressValue ? 1 : 0);
+ } else if (coincidentOriginRef.current) {
+ // A drag that began on coincident thumbs follows the pointer either
+ // way: once the pointer passes the other thumb, the dragged one stops
+ // against it and the other takes the drag (a first step that drifted
+ // the wrong way never sticks the drag).
+ const current = valuesRef.current;
+ const dragging = draggingThumbRef.current;
+ const other = dragging === 0 ? 1 : 0;
+ if (
+ (dragging === 0 && newVal > current[1]) ||
+ (dragging === 1 && newVal < current[0])
+ ) {
+ // The dragged thumb ends against the other one, as if it had
+ // followed the pointer there, and the other follows the pointer on.
+ const from = [...current];
+ from[dragging] = current[other];
+ handTo(other);
+ updateValue(other, newVal, true, from);
+ return;
+ }
+ }
updateValue(draggingThumbRef.current, newVal);
},
[isDisabled, getValueFromPosition, updateValue],
@@ -1070,7 +1158,11 @@ export function Slider({ref, ...props}: SliderProps) {
placement={tooltipPlacement}
delay={0}
focusTrigger="always"
- isOpen={draggingThumb === thumbIndex ? true : undefined}>
+ // 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
+ }>
{thumbElement}
</Tooltip>
);