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

0% Statements 0/16
0% Branches 0/20
0% Functions 0/3
0% Lines 0/15

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                                                                                                                                                   
import React, { FC } from "react";
import styled from "styled-components";
import { Slider } from "./Slider";
import { Label } from "./Label";
import { StyledInput } from "./style";
 
export interface SliderFieldProps {
  name: string;
  label?: string;
  value?: number;
  placeholder?: number;
  min: number;
  max: number;
  onChange?: (value?: number) => void;
}
 
const Wrapper = styled.div`
  width: 100%;
`;
 
const InnerWrapper = styled.div`
  display: flex;
 
  ${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,
  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>
        <StyledInput
          id={name}
          type="number"
          name={name}
          value={inputValue}
          placeholder={placeholder !== undefined ? String(placeholder) : ""}
          min={min}
          max={max}
          onChange={(e) => {
            const newValue =
              e.currentTarget.value.length > 0
                ? clamp(parseInt(e.currentTarget.value), min, max)
                : undefined;
            onChange?.(newValue);
          }}
        />
        <Slider value={sliderValue} min={min} max={max} onChange={onChange} />
      </InnerWrapper>
    </Wrapper>
  );
};