All files / src/components/ui/form SliderField.tsx

0% Statements 0/18
0% Branches 0/20
0% Functions 0/3
0% Lines 0/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 85 86 87 88 89 90 91 92 93 94 95                                                                                                                                                                                             
import React, { FC } from "react";
import styled from "styled-components";
import { Slider } from "./Slider";
import { Label } from "./Label";
import { StyledInput } from "./style";
import { NumberInput } from "./NumberInput";
 
export interface SliderFieldProps {
  name: string;
  label?: string;
  value?: number;
  placeholder?: number;
  min: number;
  max: number;
  step?: number;
  onChange?: (value?: number) => void;
}
 
const Wrapper = styled.div`
  width: 100%;
`;
 
const SliderWrapper = styled.div`
  width: 100%;
 
  @container (max-width: 150px) {
    display: none;
  }
`;
 
const InnerWrapper = styled.div`
  display: flex;
  container-type: inline-size;
 
  ${StyledInput} {
    width: 70px;
    margin-right: 10px;
    flex-shrink: 0;
  }
`;
 
const clamp = (value: number, min: number, max: number) =>
  Math.min(max, Math.max(min, value));
 
export const SliderField: FC<SliderFieldProps> = ({
  name,
  label,
  value,
  min,
  max,
  step,
  placeholder,
  onChange,
}) => {
  const sliderValue =
    value !== undefined
      ? clamp(value || 0, min, max)
      : clamp(placeholder || 0, min, max);
  const inputValue =
    value !== undefined ? String(clamp(value || 0, min, max)) : "";
  return (
    <Wrapper>
      {label && <Label htmlFor={name}>{label}</Label>}
      <InnerWrapper>
        <NumberInput
          id={name}
          type="number"
          name={name}
          value={inputValue}
          placeholder={placeholder !== undefined ? String(placeholder) : ""}
          min={min}
          max={max}
          step={step}
          onChange={(e) => {
            const newValue =
              e.currentTarget.value.length > 0
                ? clamp(parseFloat(e.currentTarget.value), min, max)
                : undefined;
            onChange?.(newValue);
          }}
        />
        <SliderWrapper>
          <Slider
            value={sliderValue}
            min={min}
            max={max}
            step={step}
            onChange={onChange}
          />
        </SliderWrapper>
      </InnerWrapper>
    </Wrapper>
  );
};