All files / src/material-toolbox/checkbox index.js

83.56% Statements 61/73
66.67% Branches 24/36
70.83% Functions 17/24
84.51% Lines 60/71

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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230                                                              10x         54x 54x 54x 54x   54x         54x         54x           54x 27x 27x 3x       54x 27x   27x   27x   35x             27x 4x 40x 85x   5x   26x       27x   27x   27x     27x 27x           27x 27x 27x 18x 18x   27x 6x 6x       27x   27x 27x 27x           27x 27x     27x 27x       54x 27x   27x 3x       54x 27x   27x         54x   54x 54x   54x 54x       54x                                                   54x         54x                                                                     10x      
// @flow strict
import React, {
  useRef,
  useMemo,
  useEffect,
  useLayoutEffect,
  useReducer,
  useState,
  useImperativeHandle,
} from 'react';
 
import cx from 'classnames';
import MDCCheckboxFoundation from '@material/checkbox/foundation';
import { getCorrectEventName } from '@material/animation/util';
 
import { mtClassNamesReducer, mtAttrsReducer } from '../reducers';
import { useRipple } from '../ripple';
 
import type {
  Style,
  HTMLMTCheckboxElement,
  HTMLCheckboxElement,
} from '../mt-types';
 
type Props = {
  indeterminate?: boolean,
  disabled?: boolean,
  className?: string,
  style?: Style,
};
 
const Checkbox = React.forwardRef<Props, HTMLCheckboxElement>(
  (
    { indeterminate, disabled: propDisabled, className, style, ...rest }: Props,
    ref,
  ) => {
    const rootRef = useRef<?HTMLDivElement>();
    const foundationRef = useRef<?MDCCheckboxFoundation>();
    const checkboxRef = useRef<?HTMLInputElement>();
    const [disabled, setDisabled] = useState<?boolean>(propDisabled);
 
    const [checkboxAttrs, checkboxAttrsDispatch] = useReducer(
      mtAttrsReducer,
      {},
    );
 
    const [mtCheckboxClassName, mtCheckboxClassNameDispatch] = useReducer(
      mtClassNamesReducer,
      new Set<string>(),
    );
 
    const { rippleStyle, rippleClassName, ripple } = useRipple({
      surface: rootRef,
      activator: checkboxRef,
      unbounded: true,
    });
 
    useLayoutEffect(() => {
      const checkbox = checkboxRef.current;
      if (checkbox && indeterminate != null) {
        checkbox.indeterminate = indeterminate;
      }
    }, [indeterminate]);
 
    useEffect(() => {
      const root = rootRef.current;
      // flowlint-next-line unclear-type:off
      const checkbox: HTMLMTCheckboxElement = (checkboxRef.current: any);
 
      const foundation = new MDCCheckboxFoundation({
        addClass: mClassName =>
          mtCheckboxClassNameDispatch({ type: 'add', className: mClassName }),
        removeClass: mClassName =>
          mtCheckboxClassNameDispatch({
            type: 'remove',
            className: mClassName,
          }),
        forceLayout: () => root && root.offsetWidth,
        hasNativeControl: () => !!checkbox,
        isAttachedToDOM: () => root && root.parentNode,
        isChecked: () => checkbox && checkbox.checked,
        isIndeterminate: () => checkbox && checkbox.indeterminate,
        setNativeControlAttr: (attr, value) =>
          checkboxAttrsDispatch({ type: 'set', name: attr, value }),
        removeNativeControlAttr: attr =>
          checkboxAttrsDispatch({ type: 'unset', name: attr }),
        setNativeControlDisabled: setDisabled,
      });
 
      foundationRef.current = foundation;
 
      const handleChange = (...args) => foundation.handleChange(...args);
 
      const handleAnimationEnd = (...args) =>
        foundation.handleAnimationEnd(...args);
 
      Eif (root) {
        root.addEventListener(
          getCorrectEventName(window, 'animationend'),
          handleAnimationEnd,
        );
      }
 
      Eif (checkbox) {
        checkbox.addEventListener('change', handleChange);
        checkbox.mtSetChecked = isChecked => {
          checkbox.checked = isChecked;
          foundation.handleChange();
        };
        checkbox.mtSetIndterminate = mtIndterminate => {
          checkbox.indeterminate = mtIndterminate;
          foundation.handleChange();
        };
      }
 
      foundation.init();
 
      return () => {
        Eif (root) {
          root.removeEventListener(
            getCorrectEventName(window, 'animationend'),
            handleAnimationEnd,
          );
        }
 
        Eif (checkbox) {
          checkbox.removeEventListener('change', handleChange);
        }
 
        foundation.destroy();
        foundationRef.current = null;
      };
    }, []);
 
    useEffect(() => {
      const foundation = foundationRef.current;
 
      if (foundation && indeterminate != null) {
        foundation.handleChange();
      }
    }, [indeterminate]);
 
    useEffect(() => {
      const foundation = foundationRef.current;
 
      Iif (foundation && propDisabled != null) {
        foundation.setDisabled(propDisabled);
      }
    }, [propDisabled]);
 
    useEffect(() => {
      // flowlint-next-line unclear-type:off
      const checkbox: HTMLMTCheckboxElement = (checkboxRef.current: any);
      const foundation = foundationRef.current;
 
      Eif (foundation && checkbox) {
        checkbox.ripple = ripple;
      }
    }, [ripple]);
 
    useImperativeHandle(
      ref,
      () => ({
        root: rootRef.current,
        input: checkboxRef.current,
        // flowlint-next-line unsafe-getters-setters:off
        set checked(isChecked) {
          // flowlint-next-line unclear-type:off
          const checkbox: HTMLMTCheckboxElement = (checkboxRef.current: any);
          if (checkbox) {
            checkbox.mtSetChecked(isChecked);
          }
        },
        // flowlint-next-line unsafe-getters-setters:off
        set indeterminate(isIndeterminate) {
          // flowlint-next-line unclear-type:off
          const checkbox: HTMLMTCheckboxElement = (checkboxRef.current: any);
 
          if (checkbox) {
            checkbox.mtSetIndterminate(isIndeterminate);
          }
        },
      }),
      [],
    );
 
    const memoizedStyle = useMemo(() => ({ ...style, ...rippleStyle }), [
      style,
      rippleStyle,
    ]);
 
    return (
      <div
        style={memoizedStyle}
        ref={rootRef}
        className={cx(
          'mdc-checkbox',
          className,
          ...Array.from(rippleClassName),
          ...Array.from(mtCheckboxClassName),
        )}
      >
        <input
          {...rest}
          {...checkboxAttrs}
          disabled={disabled}
          type="checkbox"
          className="mdc-checkbox__native-control"
          ref={checkboxRef}
        />
        <div className="mdc-checkbox__background">
          <svg className="mdc-checkbox__checkmark" viewBox="0 0 24 24">
            <path
              className="mdc-checkbox__checkmark-path"
              fill="none"
              stroke="white"
              d="M1.73,12.91 8.1,19.28 22.79,4.59"
            />
          </svg>
          <div className="mdc-checkbox__mixedmark" />
        </div>
      </div>
    );
  },
);
 
Checkbox.displayName = 'Checkbox';
 
export default Checkbox;