@@ -37,23 +37,23 @@ function areValuesEqual(
37
37
return false ;
38
38
}
39
39
40
- function findClosest ( values : readonly number [ ] , currentValue : number ) {
41
- const { index : closestIndex } =
42
- values . reduce < { distance : number ; index : number } | null > (
43
- ( acc , value : number , index : number ) => {
44
- const distance = Math . abs ( currentValue - value ) ;
45
-
46
- if ( acc === null || distance < acc . distance || distance === acc . distance ) {
47
- return {
48
- distance,
49
- index,
50
- } ;
51
- }
40
+ function getClosestThumbIndex ( values : readonly number [ ] , currentValue : number , max : number ) {
41
+ let closestIndex ;
42
+ let minDistance ;
43
+ for ( let i = 0 ; i < values . length ; i += 1 ) {
44
+ const distance = Math . abs ( currentValue - values [ i ] ) ;
45
+ if (
46
+ minDistance === undefined ||
47
+ // when the value is at max, the lowest index thumb has to be dragged
48
+ // first or it will block higher index thumbs from moving
49
+ // otherwise consider higher index thumbs to be closest when their values are identical
50
+ ( values [ i ] === max ? distance < minDistance : distance <= minDistance )
51
+ ) {
52
+ closestIndex = i ;
53
+ minDistance = distance ;
54
+ }
55
+ }
52
56
53
- return acc ;
54
- } ,
55
- null ,
56
- ) ?? { } ;
57
57
return closestIndex ;
58
58
}
59
59
@@ -74,12 +74,14 @@ export function focusThumb(
74
74
return ;
75
75
}
76
76
77
- const doc = ownerDocument ( sliderRef . current ) ;
77
+ const activeEl = activeElement ( ownerDocument ( sliderRef . current ) ) ;
78
78
79
79
if (
80
- ! sliderRef . current . contains ( doc . activeElement ) ||
81
- Number ( doc ?. activeElement ?. getAttribute ( SliderThumbDataAttributes . index ) ) !== thumbIndex
80
+ activeEl == null ||
81
+ ! sliderRef . current . contains ( activeEl ) ||
82
+ Number ( activeEl . getAttribute ( SliderThumbDataAttributes . index ) ) !== thumbIndex
82
83
) {
84
+ // TODO: possibly simplify with thumbRefs as it already exists
83
85
(
84
86
sliderRef . current . querySelector (
85
87
`[type="range"][${ SliderThumbDataAttributes . index } ="${ thumbIndex } "]` ,
@@ -371,7 +373,7 @@ export function useSliderRoot(parameters: useSliderRoot.Parameters): useSliderRo
371
373
}
372
374
373
375
if ( shouldCaptureThumbIndex ) {
374
- closestThumbIndexRef . current = findClosest ( values , newValue ) ?? 0 ;
376
+ closestThumbIndexRef . current = getClosestThumbIndex ( values , newValue , max ) ?? 0 ;
375
377
}
376
378
377
379
const closestThumbIndex = closestThumbIndexRef . current ?? 0 ;
0 commit comments