All files / components/Form/Switcher Switcher.tsx

100% Statements 57/57
84.61% Branches 11/13
100% Functions 2/2
100% Lines 57/57

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 581x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 11x 15x 15x 15x 2x 2x 2x 2x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 4x 15x 15x 6x 15x 15x 15x 15x 15x 15x 15x 1x 1x  
import { useEffect, useState } from 'react';
 
import { c } from '../../../helpers';
import { type SwitcherProps } from './SwitcherProps';
 
import styles from './Switcher.module.css';
 
const Switcher = ({
  value,
  className,
  labelLeft,
  labelRight,
  title,
  disabled,
  onChange,
  IconOn,
  IconOff,
}: SwitcherProps): JSX.Element => {
  const [switchOn, setSwitchOn] = useState<boolean>(value ?? false);
 
  useEffect(() => {
    setSwitchOn(value ?? false);
  }, [value]);
 
  const handleToggle = (): void => {
    if (disabled) return;
    setSwitchOn(!switchOn);
    onChange?.(!switchOn);
  };
 
  return (
    <label
      title={title}
      className={c(
        styles.switcher,
        switchOn ? styles.on : styles.off,
        disabled ? styles.disabled : '',
        className
      )}
    >
      {labelLeft}
      <button onClick={handleToggle} className={c(styles.switcher_button)}>
        <span className={c(styles.switcher_button_dot)}>
          {switchOn && IconOn && (
            <IconOn className={c(styles.switcher_button_icon)} />
          )}
          {!switchOn && IconOff && (
            <IconOff className={c(styles.switcher_button_icon)} />
          )}
        </span>
      </button>
      {labelRight}
    </label>
  );
};
 
export default Switcher;