From 681592e689dd736b70f9cccb5e368349686560bc Mon Sep 17 00:00:00 2001 From: Jeremy Thomas Date: Mon, 24 Jun 2024 03:48:38 +0100 Subject: [PATCH] Improve Slider --- .../src/components/Slider.jsx | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/docs/_react/bulma-customizer/src/components/Slider.jsx b/docs/_react/bulma-customizer/src/components/Slider.jsx index 00432c48..f0ba3bad 100644 --- a/docs/_react/bulma-customizer/src/components/Slider.jsx +++ b/docs/_react/bulma-customizer/src/components/Slider.jsx @@ -12,15 +12,27 @@ const RANGES = { any: [0, 100, 1], }; +const xToValue = (x, width, min, max) => { + const decimal = x / width; + const newValue = decimal * (max - min); + return Math.round(newValue); +}; + +const valueToX = (value, width, min, max) => { + const decimal = value / (max - min); + const newValue = decimal * width; + return Math.round(newValue); +}; + function Slider({ id, kind, start, unit }) { + const [min, max] = RANGES[kind]; + const [value, setValue] = useState(start); const [isMoving, setMoving] = useState(false); - const [x, setX] = useState(0); + const [x, setX] = useState(valueToX(start, 240, min, max)); const sliderRef = useRef(null); const handleRef = useRef(null); - const [min, max, step] = RANGES[kind]; - const handleMouseDown = (event) => { setMoving(true); const slider = sliderRef.current; @@ -50,6 +62,13 @@ function Slider({ id, kind, start, unit }) { } }, [id, start, unit, value]); + useEffect(() => { + const slider = sliderRef.current; + const sliderRect = slider.getBoundingClientRect(); + const final = xToValue(x, sliderRect.width, min, max); + setValue(final); + }, [min, max, unit, x]); + useEffect(() => { const docMouseMove = (event) => { if (!isMoving || !sliderRef.current || !handleRef.current) {