Repository navigation
[slider] Fix interaction edge cases - #4937
Conversation
commit: |
Bundle size
PerformanceTotal duration: 1,377.48 ms +20.38 ms(+1.5%) | Renders: 50 (+0) | Paint: 2,058.71 ms +15.70 ms(+0.8%)
11 tests within noise — details Check out the code infra dashboard for more information about this PR. |
✅ Deploy Preview for base-ui ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
flaviendelangle
left a comment
There was a problem hiding this comment.
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
onKeyDownis forwarded to the wrapper<div>, not therole="slider"input (thumb/SliderThumb.tsx:114, 463-507). Arrow keys hit the input'sstopPropagation()forCOMPOSITE_KEYSand never reach the user handler;event.currentTargetis the div, not the slider input. Either merge into the input viamergeProps, 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). Nativedisabledshould prevent focus, but the proactive blur inSliderRoot.tsx:271-279has 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).
currentInteractionValueRefwill hold the intermediate20, so commit fires with0but the user moved. Lock in the intended semantics. handleInputChangecallssetTouched(true)even on cancel (root/SliderRoot.tsx:248-261). Touched without commit is asymmetric — intentional or not, worth a one‑line comment.onValueCommittedJSDoc (root/SliderRoot.tsx:575-578) is accurate but no longer anchors when commit fires (lost thepointerupreference). Add a one‑liner like "Fired after each discrete interaction completes."- Narrating test comments at
root/SliderRoot.test.tsx:337,:426-430,:877andutils/getSliderValue.test.ts:12,14restate code — remove per the project's "default to no comments" rule. The// Requires layout: …comments at:400, :802are good examples to keep. - Track‑press disabled skip at
control/SliderControl.tsx:256— pre‑existing// pressed on controlcomment now under‑documents the loop. Add a brief WHY for the disabled‑input check inside.
Strengths
- The
|| -Infinity→?? -Infinityfix inutils/getSliderValue.ts:21is symmetric, correct, and exhaustively unit‑tested for both range directions. setValue's newbooleanreturn 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
lastChangedValueRefwith the control‑localcurrentInteractionValueRefscopes 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 perAGENTS.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
- Fix the three critical items first — they corrupt state in ways that survive across user gestures.
- Address items 4–8 before merge; item 4 (multi‑thumb form focus) is a user‑visible regression on range sliders.
- Folder up items in Suggestions (onKeyDown semantics decision, untested cases, JSDoc tweaks, comment cleanup) — most can land in this PR cheaply.
- Re‑run targeted reviews after fixes:
code-revieweron the changed control/root files andpr-test-analyzeronce the new tests are added.
flaviendelangle
left a comment
There was a problem hiding this comment.
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
-
resolveThumbCollision.tsignores disabled state (packages/react/src/slider/utils/resolveThumbCollision.ts).
The PR claims "disabled thumbs are skipped during press/drag", but the collision resolver has zerodisabledawareness. With defaultthumbCollisionBehavior="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 settingthumbCollisionBehavior="none"— so the gap is invisible to CI. Either filter disabled neighbours inresolveThumbCollision, or add a failing test documenting current behavior and declare scope. -
aria-valuetextis an undocumented public prop onSlider.Thumb(packages/react/src/slider/thumb/SliderThumb.tsx:103,312).
The PR destructuresaria-valuetextfrom props and routes it to the inner<input>, but the prop is not declared onSliderThumbPropsand not listed indocs/.../slider/types.md. It type-checks today only becauseBaseUIComponentProps<'div', …>permits any ARIA attribute of adiv. Add an explicit'aria-valuetext'?: stringtoSliderThumbPropswith JSDoc, then runpnpm docs:api. -
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 insetValueFromPointer(SliderControl.tsx:315) is not pinned by a test. A regression that forgets theif (applied)guard for the array case would slip through. Mirror the test usingTestRangeSlider.
Suggestions — 5
-
Range-slider keyboard "no-commit on unchanged value" is not tested (only single-thumb is). Mirror
SliderRoot.test.tsx:880-906to a range slider thumb pressing against a neighbour. -
currentInteractionValueRefuses mutablenumber[](SliderControl.tsx), while every other slider value-ref usesreadonly number[]. Root cause isFingerState.valueandResolveThumbCollisionResult.valuetyped asnumber | number[]. Tightening those tonumber | readonly number[]would let this ref follow suit. -
SliderThumb.tsx:490-491disabled-thumb comment overstates the risk. The control'sisTargetDisabledThumb/resetPressedThumb(SliderControl.tsx:490-493) is the real first defense; the thumb-level guard is hygiene that avoids transientpressedThumbCenterOffsetRef/pressedInputRefwrites. Reword to reflect this. -
SliderRootContext.ts:81-83setValueJSDoc 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. -
Cancel-callback side effects are undocumented.
onValueChangesubscribers callingdetails.cancel()still triggerfocusThumbon track-press,setDragging(true)on drag, andsetTouched(true)on keyboard. None silently corrupt state, but the cancellation contract in the updatedonValueCommittedJSDoc 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
lastChangedValueRefis a clean encapsulation win — the new localcurrentInteractionValueReflives where the pointer lifecycle is owned. setValuereturningbooleanis the pragmatic right choice; all four call sites correctly gate side-effects on it.- The literal-union
reason: typeof REASONS.trackPress | typeof REASONS.dragonsetValueFromPointeris idiomatic for this codebase. - Inline
skipIf(isJSDOM)justifications ("Requires layout: …") atSliderRoot.test.tsx:491,798are exemplary. getSliderValue.test.tsis a model pure-unit test — four focused cases for the??-vs-||regression.- Removing the explicit
onKeyDownplumbing inSliderThumbquietly fixes a swallowed-handler bug (the old code destructuredonKeyDownPropand never used it). The newforwards key eventstest pins it.
Recommended action
- Decide scope on finding #1 (collision-vs-disabled): either fix
resolveThumbCollisionor add a test documenting current behavior + a note in the PR description. - Add
aria-valuetexttoSliderThumbPropswith JSDoc and regeneratetypes.md. - Add the range-slider variant of the "last applied value before cancel" test.
- Optional: address the suggestion-tier comment/JSDoc tightenings before merge.
- 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.
ad44839 to
179a2c8
Compare
Fixes several slider interaction edge cases around disabled thumbs, canceled changes, range clamping, and form/ARIA behavior.
Changes
0.onValueCommitted.aria-valuetextand unhandled keydown events to the range input.