From 078374664ae2aae32253fa74e9460eeedca40386 Mon Sep 17 00:00:00 2001 From: Lee Chase Date: Fri, 18 Aug 2023 17:44:12 +0100 Subject: [PATCH] fix: slider to range step values --- .../react/src/components/Slider/Slider.tsx | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/react/src/components/Slider/Slider.tsx b/packages/react/src/components/Slider/Slider.tsx index 3b07778da43b..66440f73d9c3 100644 --- a/packages/react/src/components/Slider/Slider.tsx +++ b/packages/react/src/components/Slider/Slider.tsx @@ -455,6 +455,23 @@ export default class Slider extends PureComponent { return Math.max(min, Math.min(val, max)); } + /** + * Takes a value and ensures it fits to the steps of the range + * @param value + * @returns value of the nearest step + */ + nearestStepValue(value) { + const tempInput = document.createElement('input'); + + tempInput.type = 'range'; + tempInput.min = `${this.props.min}`; + tempInput.max = `${this.props.max}`; + tempInput.step = `${this.props.step}`; + tempInput.value = `${value}`; + + return parseFloat(tempInput.value); + } + /** * Sets up "drag" event handlers and calls `this.onDrag` in case dragging * started on somewhere other than the thumb without a corresponding "move" @@ -534,7 +551,7 @@ export default class Slider extends PureComponent { } const { value, left } = this.calcValue({ clientX }); - this.setState({ value, left, isValid: true }); + this.setState({ value: this.nearestStepValue(value), left, isValid: true }); }; /** @@ -588,7 +605,7 @@ export default class Slider extends PureComponent { : this.state.value) + delta, }); - this.setState({ value, left, isValid: true }); + this.setState({ value: this.nearestStepValue(value), left, isValid: true }); }; /**