]> git.ipfire.org Git - thirdparty/bulma.git/commitdiff
Improve Slider
authorJeremy Thomas <bbxdesign@gmail.com>
Mon, 24 Jun 2024 02:48:38 +0000 (03:48 +0100)
committerJeremy Thomas <bbxdesign@gmail.com>
Mon, 24 Jun 2024 02:48:38 +0000 (03:48 +0100)
docs/_react/bulma-customizer/src/components/Slider.jsx

index 00432c48865dc18a8789da1c2067aadbdc88e39e..f0ba3bad0333db29f8f6489b76ede51b6c48eb20 100644 (file)
@@ -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) {