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

85.15% Statements 86/101
83.74% Branches 103/123
69.44% Functions 25/36
85.86% Lines 85/99

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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346                                                                                                      7x                                               114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x   114x         114x         114x 57x   3x   114x       114x   114x     57x 57x 57x               57x       57x 57x 57x           57x 281x 57x   285x     285x             3x     116x   50x                   1x   3x           57x     114x 57x 45x         57x 57x               57x 9x     48x 9x             57x   57x 57x   57x   57x   57x       57x 57x 57x 57x       114x 57x 57x     57x 57x 57x 57x         114x 57x 57x       114x 57x 57x       114x 57x 2x       114x   114x         114x 114x   114x 114x 114x 114x   114x                                       114x                     114x                                                                                       7x      
// @flow strict
import React, {
  useReducer,
  useEffect,
  useImperativeHandle,
  useRef,
  useMemo,
} from 'react';
import cx from 'classnames';
 
import { applyPassive } from '@material/dom/events';
import MDCTextFieldFoundation from '@material/textfield/foundation';
import MDCTextFieldHelperTextFoundation from '@material/textfield/helper-text/foundation';
 
import type { Node } from 'react';
 
import FloatingLabel from '../floating-label';
import LineRipple from '../line-ripple';
import NotchedOutline from '../notched-outline';
import TextFieldCharacterCounter from './CharacterCounter';
 
import { useRipple } from '../ripple';
import { mtClassNamesReducer } from '../reducers';
 
import type {
  HTMLTextFieldHelperTextElement,
  HTMLFloatinLabelElement,
  HTMLLineRippleElement,
  HTMLTextFieldIconElement,
  HTMLNotchedOutlineElement,
  HTMLTextFieldCharacterCounterElement,
  Style,
} from '../mt-types';
 
type Props = {
  label?: string,
  fullWidth?: boolean,
  multiline?: boolean,
  disabled?: boolean,
  outlined?: boolean,
  helperText?: Node,
  leadingIcon?: Node,
  trailingIcon?: Node,
  value?: string,
  defaultValue?: string,
  invalid?: boolean,
  withCharacterCounter?: boolean,
  className?: string,
  style?: Style,
};
 
const TextField = React.forwardRef<
  Props,
  ?HTMLInputElement | ?HTMLTextAreaElement,
>(
  (
    {
      style,
      className,
      label,
      fullWidth = false,
      multiline = false,
      outlined = false,
      disabled = false,
      withCharacterCounter = false,
      invalid = false,
      trailingIcon,
      leadingIcon,
      helperText,
      value,
      defaultValue,
      ...rest
    }: Props,
    ref,
  ) => {
    const rootRef = useRef<?HTMLLabelElement>();
    const foundationRef = useRef<?MDCTextFieldFoundation>();
    const inputRef = useRef<?HTMLInputElement | ?HTMLTextAreaElement>();
    const labelRef = useRef<?HTMLFloatinLabelElement>();
    const lineRippleRef = useRef<?HTMLLineRippleElement>();
    const notchedOutlineRef = useRef<?HTMLNotchedOutlineElement>();
    const helperInlineRef = useRef<?HTMLDivElement>();
    const helperTextRef = useRef<?HTMLTextFieldHelperTextElement>();
    const leadingIconRef = useRef<?HTMLTextFieldIconElement>();
    const trailingIconRef = useRef<?HTMLTextFieldIconElement>();
    const characterCounterRef = useRef<?HTMLTextFieldCharacterCounterElement>();
 
    const [mtClassName, mtClassNameDispatch] = useReducer(
      mtClassNamesReducer,
      new Set<string>(),
    );
 
    const { rippleClassName, rippleStyle } = useRipple({
      activator: inputRef,
      disabled: outlined || multiline || disabled || fullWidth,
    });
 
    useEffect(() => {
      const foundation = new MDCTextFieldFoundation({
        addClass: mClassName =>
          mtClassNameDispatch({ type: 'add', className: mClassName }),
        removeClass: mClassName =>
          mtClassNameDispatch({ type: 'remove', className: mClassName }),
        hasClass: mClassName =>
          rootRef.current && rootRef.current.classList.contains(mClassName),
        registerTextFieldInteractionHandler: (evtType, handler) =>
          rootRef.current && rootRef.current.addEventListener(evtType, handler),
        deregisterTextFieldInteractionHandler: (evtType, handler) =>
          rootRef.current &&
          rootRef.current.removeEventListener(evtType, handler),
        registerValidationAttributeChangeHandler: handler => {
          const input = inputRef.current;
          Eif (input) {
            const getAttributesList = (
              mutationsList: MutationRecord[],
            ): Array<?string> => {
              return mutationsList
                .map(mutation => mutation.attributeName)
                .filter(attributeName => attributeName);
            };
 
            const observer = new MutationObserver(mutationsList =>
              handler(getAttributesList(mutationsList)),
            );
 
            const config = { attributes: true };
            observer.observe(input, config);
            return observer;
          }
 
          return undefined;
        },
        deregisterValidationAttributeChangeHandler: observer =>
          observer.disconnect(),
        getNativeInput: () => inputRef.current,
        isFocused: () => document.activeElement === inputRef.current,
        registerInputInteractionHandler: (evtType, handler) =>
          inputRef.current &&
          inputRef.current.addEventListener(evtType, handler, applyPassive()),
        deregisterInputInteractionHandler: (evtType, handler) =>
          inputRef.current &&
          inputRef.current.removeEventListener(
            evtType,
            handler,
            applyPassive(),
          ),
        floatLabel: shouldFloat =>
          labelRef.current && labelRef.current.foundation.float(shouldFloat),
        getLabelWidth: () =>
          labelRef.current ? labelRef.current.foundation.getWidth() : 0,
        hasLabel: () => Boolean(labelRef.current),
        shakeLabel: shouldShake =>
          labelRef.current && labelRef.current.foundation.shake(shouldShake),
        activateLineRipple: () =>
          lineRippleRef.current && lineRippleRef.current.foundation.activate(),
        deactivateLineRipple: () =>
          lineRippleRef.current &&
          lineRippleRef.current.foundation.deactivate(),
        setLineRippleTransformOrigin: normalizedX =>
          lineRippleRef.current &&
          lineRippleRef.current.foundation.setRippleCenter(normalizedX),
        closeOutline: () =>
          notchedOutlineRef.current &&
          notchedOutlineRef.current.foundation.closeNotch(),
        hasOutline: () => Boolean(notchedOutlineRef.current), // Note. better use outlined prop?
        notchOutline: labelWidth =>
          notchedOutlineRef.current &&
          notchedOutlineRef.current.foundation.notch(labelWidth),
      });
 
      foundationRef.current = foundation;
    }, []);
 
    useEffect(() => {
      if (helperText != null && helperInlineRef.current) {
        helperTextRef.current = (helperInlineRef.current.querySelector(
          MDCTextFieldHelperTextFoundation.strings.ROOT_SELECTOR,
        ): any); // flowlint-line unclear-type:off
      }
 
      Eif (rootRef.current) {
        Iif (leadingIcon != null && trailingIcon != null) {
          const iconElements = rootRef.current.querySelectorAll(
            MDCTextFieldFoundation.strings.ICON_SELECTOR,
          );
 
          // flowlint unclear-type:off
          leadingIconRef.current = (iconElements[0]: any);
          trailingIconRef.current = (iconElements[0]: any);
        } else if (leadingIcon != null) {
          leadingIconRef.current = (rootRef.current.querySelector(
            MDCTextFieldFoundation.strings.ICON_SELECTOR,
          ): any);
        } else if (trailingIcon != null) {
          trailingIconRef.current = (rootRef.current.querySelector(
            MDCTextFieldFoundation.strings.ICON_SELECTOR,
          ): any);
          // flowlint unclear-type:error
        }
      }
 
      const foundation = foundationRef.current;
 
      Eif (foundation) {
        foundation.helperText_ =
          helperTextRef.current && helperTextRef.current.foundation;
        foundation.leadingIcon_ =
          leadingIconRef.current && leadingIconRef.current.foundation;
        foundation.trailingIcon_ =
          trailingIconRef.current && trailingIconRef.current.foundation;
        foundation.characterCounter_ =
          characterCounterRef.current && characterCounterRef.current.foundation;
      }
 
      return () => {
        helperTextRef.current = null;
        leadingIconRef.current = null;
        trailingIconRef.current = null;
      };
    }, [helperText, leadingIcon, trailingIcon]);
 
    useEffect(() => {
      Eif (foundationRef.current) {
        foundationRef.current.init();
      }
 
      return () => {
        Eif (foundationRef.current) {
          foundationRef.current.destroy();
          foundationRef.current = null;
        }
      };
    }, []);
 
    useEffect(() => {
      Eif (foundationRef.current) {
        foundationRef.current.setDisabled(disabled);
      }
    }, [disabled]);
 
    useEffect(() => {
      Eif (foundationRef.current) {
        foundationRef.current.setValid(!invalid);
      }
    }, [invalid]);
 
    useEffect(() => {
      if (foundationRef.current && (value != null || defaultValue != null)) {
        foundationRef.current.setValue(value != null ? value : defaultValue);
      }
    }, [defaultValue, value]);
 
    useImperativeHandle(ref, () => inputRef.current, []);
 
    const memoizedStyle = useMemo(() => ({ ...style, ...rippleStyle }), [
      rippleStyle,
      style,
    ]);
 
    const Input = multiline ? 'textarea' : 'input';
    const withLabel = label != null;
    const withFilledLabel =
      label != null && !outlined && !multiline && !fullWidth;
    const withLineRipple = !multiline && !outlined;
    const withNotchedOutline = outlined || multiline;
    const withRipple = !(outlined || multiline || fullWidth);
 
    const rootProps = {
      style: memoizedStyle,
      ref: rootRef,
      className: cx(
        'mdc-text-field',
        {
          'mdc-text-field--disabled': disabled,
          'mdc-text-field--fullwidth': fullWidth,
          'mdc-text-field--textarea': multiline,
          'mdc-text-field--no-label': !withLabel,
          'mdc-text-field--outlined': outlined,
          'mdc-text-field--with-leading-icon': leadingIcon !== undefined,
          'mdc-text-field--with-trailing-icon': trailingIcon !== undefined,
        },
        ...Array.from(mtClassName),
        ...Array.from(withRipple ? rippleClassName : []),
        className,
      ),
    };
 
    const inputProps = {
      ...rest,
      disabled,
      value,
      defaultValue,
      placeholder: fullWidth && !multiline && !outlined ? label : null,
      'aria-label': fullWidth && !multiline && !outlined ? label : null,
      className: 'mdc-text-field__input',
      ref: inputRef,
    };
 
    return (
      <>
        <label // eslint-disable-line jsx-a11y/label-has-for,jsx-a11y/label-has-associated-control
          {...rootProps}
        >
          {leadingIcon}
          {withCharacterCounter && multiline && (
            <TextFieldCharacterCounter ref={characterCounterRef} />
          )}
          <Input {...inputProps} />
          {withFilledLabel && (
            <FloatingLabel
              label={label}
              ref={labelRef}
              preFilled={value != null || defaultValue != null}
            />
          )}
          {trailingIcon}
          {withLineRipple && <LineRipple ref={lineRippleRef} />}
          {withNotchedOutline && (
            <NotchedOutline ref={notchedOutlineRef}>
              {withLabel && (
                <FloatingLabel
                  label={label}
                  ref={labelRef}
                  preFilled={value != null || defaultValue != null}
                />
              )}
            </NotchedOutline>
          )}
        </label>
        {(helperText !== undefined || withCharacterCounter) && (
          <div ref={helperInlineRef} className="mdc-text-field-helper-line">
            {helperText}
            {withCharacterCounter && !multiline && (
              <TextFieldCharacterCounter ref={characterCounterRef} />
            )}
          </div>
        )}
      </>
    );
  },
);
 
TextField.displayName = 'TextField';
 
export default TextField;