Skip to content

Commit 6cfc67e

Browse files
committed
fix(utils): updated nearest to support a custom range for sliders
1 parent c4ee05b commit 6cfc67e

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

packages/form/src/slider/utils.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ export const getDragValue = ({
152152
const range = max - min;
153153
const steps = getSteps(min, max, step);
154154
const value = percentageDragged * range + min;
155-
const rounded = nearest(value, minValue, maxValue, steps);
155+
const rounded = nearest(value, minValue, maxValue, steps, range);
156156

157157
if (!vertical && isRtl) {
158158
return steps - rounded;

packages/utils/src/__tests__/nearest.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,18 @@ describe("nearest", () => {
2020
expect(nearest(0.28, 0, 1, 4)).toBe(0.25);
2121
expect(nearest(0.33, 0, 1, 4)).toBe(0.25);
2222
});
23+
24+
it("should allow for a custom range to be used with range sliders", () => {
25+
// to explain this a bit better, need to make sure that the slider thumbs
26+
// are always in order of `min -> max` so the min and max values change
27+
// depending on which thumb is being dragged:
28+
// - thumb1 -> min === min, max === thumb2Value
29+
// - thumb2 -> min === thumb1Value, max === max
30+
31+
expect(nearest(44.3, 40, 100, 100, 100)).toBe(44);
32+
expect(nearest(50, 20, 50, 50, 50)).toBe(50);
33+
expect(nearest(22.3, 20, 50, 50, 50)).toBe(22);
34+
expect(nearest(12.3, 20, 50, 50, 50)).toBe(20);
35+
expect(nearest(0, 30, 50, 100, 100)).toBe(30);
36+
});
2337
});

packages/utils/src/nearest.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,17 @@
66
* @param min The min value allowed
77
* @param max The max value allowed
88
* @param steps The number of steps in the min/max range
9+
* @param range The range allowed for the value that defaults to `max - min`
910
* @return the value rounded to the nearest step in the min/max range
1011
* @since 2.5.0 - Added the `range` param
1112
*/
1213
export function nearest(
1314
value: number,
1415
min: number,
1516
max: number,
16-
steps: number
17+
steps: number,
18+
range = max - min
1719
): number {
18-
const range = max - min;
1920
const rounded = Math.round(((value - min) * steps) / range) / steps;
2021
const zeroToOne = Math.min(Math.max(rounded, 0), 1);
2122

0 commit comments

Comments
 (0)