Skip to content

[slider] Fix interaction edge cases - #4937

Merged
atomiks merged 7 commits into
mui:masterfrom
atomiks:codex/slider-interaction-fixes
Jun 3, 2026
Merged

atomiks merged 7 commits into
mui:masterfrom
atomiks:codex/slider-interaction-fixes

Conversation

@atomiks

@atomiks atomiks commented May 28, 2026

Copy link
Copy Markdown
Contributor

Fixes several slider interaction edge cases around disabled thumbs, canceled changes, range clamping, and form/ARIA behavior.

Changes

  • Fixed range sliders so thumbs cannot cross a neighbor whose value is 0.
  • Ignored disabled thumbs during direct presses, track presses, and drag selection.
  • Prevented canceled slider changes from firing onValueCommitted.
  • Registered the range input for field/form focus on invalid submits.
  • Forwarded aria-valuetext and unhandled keydown events to the range input.
  • Updated slider docs examples and regression coverage.

@atomiks atomiks added component: slider Changes related to the slider component. type: bug It doesn't behave as expected. labels May 28, 2026
@pkg-pr-new

pkg-pr-new Bot commented May 28, 2026 •

Copy link
Copy Markdown
  • base-ui-tanstack-start

  • vite-css-base-ui-example

    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/react@4937
    
    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/utils@4937
    

commit: d309461

@code-infra-dashboard

code-infra-dashboard Bot commented May 28, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+135B(+0.03%) 🔺+55B(+0.04%)

Details of bundle changes

Performance

Total duration: 1,377.48 ms +20.38 ms(+1.5%) | Renders: 50 (+0) | Paint: 2,058.71 ms +15.70 ms(+0.8%)

Test Duration Renders
Scroll Area mount (300 instances) 119.22 ms 🔺+25.81 ms(+27.6%) 3 (+0)

11 tests within noise — details


Check out the code infra dashboard for more information about this PR.

@netlify

netlify Bot commented May 28, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Name Link
🔨 Latest commit d309461
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6a1fba72e7868e0008f4ea64
😎 Deploy Preview https://deploy-preview-4937--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@atomiks
atomiks marked this pull request as ready for review May 28, 2026 12:45

@flaviendelangle flaviendelangle left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR #4937 Review — [slider] Fix interaction edge cases

Four specialized agents reviewed the PR in parallel. The aggregated findings are below, deduplicated and ranked by severity. File paths are relative to packages/react/src/slider/.


Critical (must fix before merge)

1. pressedThumbIndexRef is mutated before setValue runs — canceled drags leak the swap into subsequent events
  control/SliderControl.tsx:228-232 and :354-358
The collision resolver in getFingerState writes pressedThumbIndexRef.current = collisionResult.thumbIndex before setValueFromPointer calls setValue. If the consumer cancels the change, the value/latestValuesRef snap back but the index ref stays pointing at the swapped thumb. The next move computes against pressedIndex (post‑swap) but currentValues (pre‑swap), so it operates on a thumb the user never visibly moved to — focus stays elsewhere. Snapshot the index ref before setValue and restore it when applied === false, or defer the write until setValue returns true.

2. isTargetDisabledThumb silently classifies as enabled when the input is missing
  control/SliderControl.tsx:171 and :266
thumbEl.querySelector('input[type="range"]')?.disabled === true returns false when the input element is absent — i.e. an unmounted/transient state is treated as a green light to interact. Same shape in the closest‑thumb loop (!input?.disabled). The fallback should be the safe direction (treat-as-disabled). Replace with if (!input) return true in isTargetDisabledThumb and the inverse in the neighbor loop.

3. SliderThumb.onPointerDown writes pressed‑thumb refs unconditionally
  thumb/SliderThumb.tsx:489-503 (write); control/SliderControl.tsx:482-491 (early‑return guards)
The thumb writes pressedThumbIndexRef.current = index first, then SliderControl.onPointerDown may bail on disabled || event.defaultPrevented || event.button !== 0 before isTargetDisabledThumb and resetPressedThumb run. A right‑click or preventDefault'd event on a disabled thumb leaves the ref pointing at it; the next legitimate left‑click on the track reuses that index and writes to the disabled thumb's value. Either reorder the guards so the reset runs first, or skip the writes from SliderThumb when the thumb is disabled.


Important (should fix)

4. validation.inputRef ends up on the last‑mounted thumb of a range slider
  root/SliderRoot.tsx:173, thumb/SliderThumb.tsx:458
Each thumb's input is merged into validation.inputRef, so invalid submits focus the last‑mounted input. For a range whose last thumb is disabled, focus lands on a disabled input. The new test covers single‑thumb only. Have SliderRoot maintain a firstEnabledThumbInputRef and register that instead. Add a multi‑thumb invalid‑submit regression test.

5. Disabled neighbors are still pushed/swapped via collision behavior
  utils/resolveThumbCollision.ts
The PR blocks direct interactions with disabled thumbs but resolveThumbCollision is unaware of disabled. Dragging an enabled thumb into a disabled neighbor under push/swap still mutates the disabled value — the very behavior the PR is trying to prevent. Pass disabled indexes to the resolver and treat them as a hard barrier.

6. handleTouchEnd keeps a stale finger != null gate that can swallow a real commit
  control/SliderControl.tsx:369-378
The commit value is now currentInteractionValueRef.current, not finger.value — but the early‑return still requires finger to be non‑null. If getFingerCoords/getFingerState returns null at pointerup (e.g. thumb unmounted mid‑drag), an interaction that did apply silently drops its commit. Drop the finger != null requirement; commit purely on currentInteractionValueRef.current != null.

7. Multi‑move cancel: onValueCommitted fires with the prior applied value
  control/SliderControl.tsx:308-326, 372-378; tested at root/SliderRoot.test.tsx:991-1044
The cancel test only fires a single canceled pointerMove. If the user moves 0→20→cancel(50), currentInteractionValueRef still holds 20 at touchend, so commit fires with 20 even though the last move was canceled. The doc says "Does not fire if the value … was canceled," which makes this ambiguous. Decide the intended semantics and add a mixed applied/canceled regression test.

8. setValue JSDoc on the context is now wrong in two ways
  root/SliderRootContext.ts:82-84
Current text: Callback fired when dragging and invokes onValueChange. The function is also used by keyboard/input/track press, and it now returns boolean (true = applied). Callers rely on that return; the comment doesn't mention it.


Suggestions

  • onKeyDown is forwarded to the wrapper <div>, not the role="slider" input (thumb/SliderThumb.tsx:114, 463-507). Arrow keys hit the input's stopPropagation() for COMPOSITE_KEYS and never reach the user handler; event.currentTarget is the div, not the slider input. Either merge into the input via mergeProps, or document the "div + only unhandled keys" contract and add a test asserting arrow keys do not reach the user handler.
  • Disabled‑thumb keyboard interactions untested (root/SliderRoot.test.tsx:308-433). Native disabled should prevent focus, but the proactive blur in SliderRoot.tsx:271-279 has no behavioral test.
  • 0‑neighbor range fix has only a unit test (utils/getSliderValue.test.ts). Add a keyboard/pointer integration test against a [-10, 0] range.
  • "Move and return" drag case untested — drag 0→20→0 (back to origin). currentInteractionValueRef will hold the intermediate 20, so commit fires with 0 but the user moved. Lock in the intended semantics.
  • handleInputChange calls setTouched(true) even on cancel (root/SliderRoot.tsx:248-261). Touched without commit is asymmetric — intentional or not, worth a one‑line comment.
  • onValueCommitted JSDoc (root/SliderRoot.tsx:575-578) is accurate but no longer anchors when commit fires (lost the pointerup reference). Add a one‑liner like "Fired after each discrete interaction completes."
  • Narrating test comments at root/SliderRoot.test.tsx:337, :426-430, :877 and utils/getSliderValue.test.ts:12,14 restate code — remove per the project's "default to no comments" rule. The // Requires layout: … comments at :400, :802 are good examples to keep.
  • Track‑press disabled skip at control/SliderControl.tsx:256 — pre‑existing // pressed on control comment now under‑documents the loop. Add a brief WHY for the disabled‑input check inside.

Strengths

  • The || -Infinity → ?? -Infinity fix in utils/getSliderValue.ts:21 is symmetric, correct, and exhaustively unit‑tested for both range directions.
  • setValue's new boolean return threads cancellation consistently through every commit path; matched by tests for canceled keyboard, no‑op keyboard, no‑op press, canceled track press, and canceled drag.
  • Reordering lastChangeReasonRef.current = … to after the cancel check correctly aligns the ref with committed changes only.
  • Replacing the global lastChangedValueRef with the control‑local currentInteractionValueRef scopes the bookkeeping to where it's used.
  • All direct disabled‑thumb entry points are consistently guarded (track‑press closest loop, pointer down, touch start, single‑thumb fallback in getFingerState).
  • Shadow‑DOM‑safe utilities (contains, getTarget, ownerDocument, ownerWindow) used per AGENTS.md.
  • The field‑control registration swap (non‑focusable wrapper → input) is the correct direction; the regression test covers the single‑thumb case.
  • New tests are behavioral (aria-valuenow, toHaveFocus, callback args) and follow project conventions (Vitest only, it.skipIf(isJSDOM) where layout matters).

Recommended action

  1. Fix the three critical items first — they corrupt state in ways that survive across user gestures.
  2. Address items 4–8 before merge; item 4 (multi‑thumb form focus) is a user‑visible regression on range sliders.
  3. Folder up items in Suggestions (onKeyDown semantics decision, untested cases, JSDoc tweaks, comment cleanup) — most can land in this PR cheaply.
  4. Re‑run targeted reviews after fixes: code-reviewer on the changed control/root files and pr-test-analyzer once the new tests are added.

@flaviendelangle flaviendelangle left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR #4937 Review Summary — [slider] Fix interaction edge cases

Reviewed 5 dimensions in parallel: code quality, test coverage, silent failures, comments, type design. Overall the PR is well-scoped and tightly tested; all 7 stated fixes have at least one regression test that fails on master. Findings below.

Critical issues — 0

Nothing must-fix-before-merge surfaced. The cancel/apply paths, setValue boolean contract, currentInteractionValueRef lifecycle, useRegisterFieldControl(validation.inputRef, …) change, and ??-fix in getSliderValue.ts were all substantiated as correct.

Important issues — 3

  1. resolveThumbCollision.ts ignores disabled state (packages/react/src/slider/utils/resolveThumbCollision.ts).
    The PR claims "disabled thumbs are skipped during press/drag", but the collision resolver has zero disabled awareness. With default thumbCollisionBehavior="push" (or "swap"), dragging an enabled thumb across a disabled neighbour will still push/swap the disabled thumb's value. The only multi-thumb disabled test (SliderRoot.test.tsx:401) sidesteps this by setting thumbCollisionBehavior="none" — so the gap is invisible to CI. Either filter disabled neighbours in resolveThumbCollision, or add a failing test documenting current behavior and declare scope.

  2. aria-valuetext is an undocumented public prop on Slider.Thumb (packages/react/src/slider/thumb/SliderThumb.tsx:103,312).
    The PR destructures aria-valuetext from props and routes it to the inner <input>, but the prop is not declared on SliderThumbProps and not listed in docs/.../slider/types.md. It type-checks today only because BaseUIComponentProps<'div', …> permits any ARIA attribute of a div. Add an explicit 'aria-valuetext'?: string to SliderThumbProps with JSDoc, then run pnpm docs:api.

  3. Missing range-slider test for "commit reflects last applied value before cancel" (packages/react/src/slider/root/SliderRoot.test.tsx:1044).
    The "commits the last applied value when a later move is canceled" test only covers single-thumb. The array branch in setValueFromPointer (SliderControl.tsx:315) is not pinned by a test. A regression that forgets the if (applied) guard for the array case would slip through. Mirror the test using TestRangeSlider.

Suggestions — 5

  1. Range-slider keyboard "no-commit on unchanged value" is not tested (only single-thumb is). Mirror SliderRoot.test.tsx:880-906 to a range slider thumb pressing against a neighbour.

  2. currentInteractionValueRef uses mutable number[] (SliderControl.tsx), while every other slider value-ref uses readonly number[]. Root cause is FingerState.value and ResolveThumbCollisionResult.value typed as number | number[]. Tightening those to number | readonly number[] would let this ref follow suit.

  3. SliderThumb.tsx:490-491 disabled-thumb comment overstates the risk. The control's isTargetDisabledThumb/resetPressedThumb (SliderControl.tsx:490-493) is the real first defense; the thumb-level guard is hygiene that avoids transient pressedThumbCenterOffsetRef/pressedInputRef writes. Reword to reflect this.

  4. SliderRootContext.ts:81-83 setValue JSDoc says false is returned "when it was unchanged or canceled" but the implementation has three branches: NaN, equal-value, canceled. Add "or invalid (NaN)" for completeness.

  5. Cancel-callback side effects are undocumented. onValueChange subscribers calling details.cancel() still trigger focusThumb on track-press, setDragging(true) on drag, and setTouched(true) on keyboard. None silently corrupt state, but the cancellation contract in the updated onValueCommitted JSDoc only describes value/commit behavior. Consider noting that focus/touched/dragging side effects of the pressed interaction still apply.

Strengths

  • Removal of the cross-component lastChangedValueRef is a clean encapsulation win — the new local currentInteractionValueRef lives where the pointer lifecycle is owned.
  • setValue returning boolean is the pragmatic right choice; all four call sites correctly gate side-effects on it.
  • The literal-union reason: typeof REASONS.trackPress | typeof REASONS.drag on setValueFromPointer is idiomatic for this codebase.
  • Inline skipIf(isJSDOM) justifications ("Requires layout: …") at SliderRoot.test.tsx:491,798 are exemplary.
  • getSliderValue.test.ts is a model pure-unit test — four focused cases for the ??-vs-|| regression.
  • Removing the explicit onKeyDown plumbing in SliderThumb quietly fixes a swallowed-handler bug (the old code destructured onKeyDownProp and never used it). The new forwards key events test pins it.

Recommended action

  1. Decide scope on finding #1 (collision-vs-disabled): either fix resolveThumbCollision or add a test documenting current behavior + a note in the PR description.
  2. Add aria-valuetext to SliderThumbProps with JSDoc and regenerate types.md.
  3. Add the range-slider variant of the "last applied value before cancel" test.
  4. Optional: address the suggestion-tier comment/JSDoc tightenings before merge.

atomiks added 5 commits June 3, 2026 14:46
- Track a swapped thumb only after the change is applied so a canceled swap
  no longer leaks the new index into later moves.
- Skip pressed-thumb ref writes for a disabled thumb so a stale index can't be
  reused by a later track press.
- Commit on pointerup based on the last applied value instead of re-deriving a
  finger state that could drop a legitimate commit.
- Fix the `setValue` context JSDoc and trim narrating test comments.
@atomiks
atomiks force-pushed the codex/slider-interaction-fixes branch from ad44839 to 179a2c8 Compare June 3, 2026 04:49
@atomiks
atomiks merged commit ec358d2 into mui:master Jun 3, 2026
6 checks passed
@atomiks
atomiks deleted the codex/slider-interaction-fixes branch June 3, 2026 07:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: slider Changes related to the slider component. type: bug It doesn't behave as expected.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants