summaryrefslogtreecommitdiffhomepage
path: root/frontend/src/components/inputs/Slider.tsx
blob: e8a8c3c3541c2d72f10bf0edc01fa06512cc5eac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import RcSlider from "rc-slider";
import "rc-slider/assets/index.css";
import React, { FunctionComponent, useMemo, useState } from "react";
import "./slider.scss";

type TooltipsOptions = boolean | "Always";

export interface SliderProps {
  tooltips?: TooltipsOptions;
  min?: number;
  max?: number;
  step?: number;
  start?: number;
  defaultValue?: number;
  onAfterChange?: (value: number) => void;
  onChange?: (value: number) => void;
}

export const Slider: FunctionComponent<SliderProps> = ({
  min,
  max,
  step,
  tooltips,
  defaultValue,
  onChange,
  onAfterChange,
}) => {
  max = max ?? 100;
  min = min ?? 0;
  step = step ?? 1;

  const [curr, setValue] = useState(defaultValue);

  return (
    <div className="d-flex flex-row align-items-center py-2">
      <span className="text-muted text-nowrap pr-3">{`${min} / ${curr}`}</span>
      <RcSlider
        min={min}
        max={max}
        className="custom-rc-slider"
        step={step}
        defaultValue={defaultValue}
        onChange={(v) => {
          setValue(v);
          onChange && onChange(v);
        }}
        onAfterChange={onAfterChange}
        handle={(props) => (
          <div
            className="rc-slider-handle"
            style={{
              left: `${props.offset}%`,
            }}
          >
            <SliderTooltips
              tooltips={tooltips}
              value={props.value}
            ></SliderTooltips>
          </div>
        )}
      ></RcSlider>
      <span className="text-muted pl-3">{max}</span>
    </div>
  );
};

const SliderTooltips: FunctionComponent<{
  tooltips?: TooltipsOptions;
  value: number;
}> = ({ tooltips, value }) => {
  const cls = useMemo(() => {
    const tipsCls = ["rc-slider-handle-tips"];
    if (tooltips !== undefined) {
      if (typeof tooltips === "string") {
        tipsCls.push("rc-slider-handle-tips-always");
      } else if (tooltips === false) {
        tipsCls.push("rc-slider-handle-tips-hidden");
      }
    }
    return tipsCls.join(" ");
  }, [tooltips]);

  return <span className={cls}>{value}</span>;
};