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

81.65% Statements 89/109
63.33% Branches 38/60
51.43% Functions 18/35
81.65% Lines 89/109

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 347 348 349                                                                          6x   6x   6x   6x                             62x 31x 31x     62x 62x 62x 62x 62x   62x 62x 62x         62x 31x             62x               62x   31x   31x 31x       62x   31x   31x 9x         31x 4x         31x 31x 31x       62x   31x 31x 31x 31x   31x   6x                                                             5x         31x   31x     31x     31x     31x 31x 31x 31x   31x     31x 3x       3x           31x   31x 31x 3x       3x           31x 31x 31x 31x   31x     31x 31x       62x   31x 31x   31x 31x                                 62x   31x 31x   31x 31x                                 62x   31x 31x 31x 31x 5x                       5x         62x 31x 1x           62x 31x 1x       62x 31x       62x                                                                      
// @flow strict
import React, { useEffect, useRef, useMemo, useState, useReducer } from 'react';
import cx from 'classnames';
 
import MDCChipFoundation from '@material/chips/chip/foundation';
 
import type { Node } from 'react';
 
import { createEvent } from '../utils';
import { useRipple } from '../ripple';
import {
  mtClassNamesReducer,
  mtAttrsReducer,
  mtStylesReducer,
} from '../reducers';
 
import type { Style, HTMLChipElement, HTMLChipIconElement } from '../mt-types';
 
type Props = {
  className?: string,
  style?: Style,
  label: string,
  defaultSelected?: boolean,
  filter?: boolean,
  leadingIcon?: Node,
  trailingIcon?: Node,
  shouldRemoveOnTrailingIconClick?: boolean,
  beginExit?: boolean,
  onSelected?: ({
    chipId: string,
    selected: boolean,
    element: HTMLChipElement,
  }) => void,
  onRemoval?: ({ chipId: string, element: HTMLChipElement }) => void,
  onInteraction?: ({ chipId: string, element: HTMLChipElement }) => void,
};
 
let chipIdCounter = 0;
 
const noOp = () => {};
 
const { strings } = MDCChipFoundation;
 
const Chip = ({
  className,
  style,
  label,
  defaultSelected,
  filter = false,
  leadingIcon,
  trailingIcon,
  shouldRemoveOnTrailingIconClick,
  beginExit,
  onInteraction = noOp,
  onRemoval = noOp,
  onSelected = noOp,
  ...rest
}: Props) => {
  const [chipId] = useState(() => {
    chipIdCounter += 1;
    return `mdc-chip-${chipIdCounter}`;
  });
 
  const rootRef = useRef<?HTMLButtonElement>();
  const checkmarkRef = useRef<?HTMLSpanElement>();
  const foundationRef = useRef<?MDCChipFoundation>();
  const leadingIconRef = useRef<?HTMLChipIconElement>();
  const trailingIconRef = useRef<?HTMLChipIconElement>();
 
  const [mtAttrs, mtAttrsDispatch] = useReducer(mtAttrsReducer, {});
  const [mtStyle, mtStyleDispatch] = useReducer(mtStylesReducer, {});
  const [mtClassName, mtClassNameDispatch] = useReducer(
    mtClassNamesReducer,
    new Set<string>(),
  );
 
  const partialAdapter = useMemo(
    () => ({
      computeBoundingRect: () =>
        foundationRef.current && foundationRef.current.getDimensions(),
    }),
    [],
  );
 
  const { rippleStyle, rippleClassName } = useRipple(
    {
      activator: rootRef,
      unbounded: true,
    },
    partialAdapter,
  );
 
  useEffect(() => {
    // flowlint-next-line unclear-type:off
    const root: HTMLChipElement = (rootRef.current: any);
 
    Eif (root) {
      root.defaultSelected = defaultSelected;
    }
  }, [defaultSelected]);
 
  useEffect(() => {
    // flowlint-next-line unclear-type:off
    const root: HTMLChipElement = (rootRef.current: any);
 
    if (leadingIcon != null && root) {
      leadingIconRef.current = (root.querySelector(
        strings.LEADING_ICON_SELECTOR,
      ): any); // flowlint-line unclear-type:off
    }
 
    if (trailingIcon != null && root) {
      trailingIconRef.current = (root.querySelector(
        strings.TRAILING_ICON_SELECTOR,
      ): any); // flowlint-line unclear-type:off
    }
 
    return () => {
      trailingIconRef.current = null;
      leadingIconRef.current = null;
    };
  }, [leadingIcon, trailingIcon]);
 
  useEffect(() => {
    // flowlint-next-line unclear-type:off
    const root: HTMLChipElement = (rootRef.current: any);
    const checkmark = checkmarkRef.current;
    const leadingIconElement = leadingIconRef.current;
    const trailingIconElement = trailingIconRef.current;
 
    const foundation = new MDCChipFoundation({
      addClass: mClassName =>
        mtClassNameDispatch({ type: 'add', className: mClassName }),
      addClassToLeadingIcon: mClassName =>
        leadingIconElement && leadingIconElement.mtAddClassName(mClassName),
      eventTargetHasClass: (target, mClassName) =>
        target ? target.classList.contains(mClassName) : false,
      getCheckmarkBoundingClientRect: () =>
        checkmark && checkmark.getBoundingClientRect(),
      getComputedStyleValue: propertyName =>
        window.getComputedStyle(root).getPropertyValue(propertyName),
      getRootBoundingClientRect: () => root && root.getBoundingClientRect(),
      hasClass: mClassName => root && root.classList.contains(mClassName),
      hasLeadingIcon: () => !!leadingIconElement,
      notifyTrailingIconInteraction: () => {
        if (rootRef.current) {
          rootRef.current.dispatchEvent(
            createEvent(
              strings.TRAILING_ICON_INTERACTION_EVENT,
              {
                chipId,
                element: root,
              },
              true /* bubble */,
            ),
          );
        }
      },
      removeClass: mClassName =>
        mtClassNameDispatch({ type: 'remove', className: mClassName }),
      removeClassFromLeadingIcon: mClassName =>
        leadingIconElement && leadingIconElement.mtRemoveClassName(mClassName),
      setAttr: (attr, value) =>
        mtAttrsDispatch({ type: 'set', name: attr, value }),
      setStyleProperty: (propertyName, value) =>
        mtStyleDispatch({ type: 'set', name: propertyName, value }),
    });
 
    foundation.init();
 
    const handleInteraction = (...args) =>
      foundation.handleInteraction(...args);
 
    const handleTransitioinEnd = (...args) =>
      foundation.handleTransitionEnd(...args);
 
    const handleTrailingIconInteraction = (...args) =>
      foundation.handleTrailingIconInteraction(...args);
 
    Eif (root) {
      root.addEventListener('click', handleInteraction);
      root.addEventListener('keydown', handleInteraction);
      root.addEventListener('transitionend', handleTransitioinEnd);
 
      root.foundation = foundation;
    }
 
    if (trailingIconElement) {
      trailingIconElement.addEventListener(
        'keydown',
        handleTrailingIconInteraction,
      );
      trailingIconElement.addEventListener(
        'click',
        handleTrailingIconInteraction,
      );
    }
 
    foundationRef.current = foundation;
 
    return () => {
      if (trailingIconElement) {
        trailingIconElement.removeEventListener(
          'keydown',
          handleTrailingIconInteraction,
        );
        trailingIconElement.removeEventListener(
          'click',
          handleTrailingIconInteraction,
        );
      }
 
      Eif (root) {
        root.removeEventListener('click', handleInteraction);
        root.removeEventListener('keydown', handleInteraction);
        root.removeEventListener('transitionend', handleTransitioinEnd);
 
        delete root.foundation;
      }
 
      foundation.destroy();
      foundationRef.current = null;
    };
  }, [chipId]);
 
  useEffect(() => {
    // flowlint-next-line unclear-type:off
    const root: HTMLChipElement = (rootRef.current: any);
    const foundation = foundationRef.current;
 
    Eif (foundation && root) {
      foundation.adapter_.notifyInteraction = () => {
        root.dispatchEvent(
          createEvent(
            strings.INTERACTION_EVENT,
            {
              chipId,
              element: rootRef.current,
            },
            true /* bubble */,
          ),
        );
 
        onInteraction({ chipId, element: root });
      };
    }
  }, [chipId, onInteraction]);
 
  useEffect(() => {
    // flowlint-next-line unclear-type:off
    const root: HTMLChipElement = (rootRef.current: any);
    const foundation = foundationRef.current;
 
    Eif (foundation && root) {
      foundation.adapter_.notifyRemoval = () => {
        root.dispatchEvent(
          createEvent(
            strings.REMOVAL_EVENT,
            {
              chipId,
              element: root,
            },
            true /* bubble */,
          ),
        );
 
        onRemoval({ chipId, element: root });
      };
    }
  }, [chipId, onRemoval]);
 
  useEffect(() => {
    // flowlint-next-line unclear-type:off
    const root: HTMLChipElement = (rootRef.current: any);
    const foundation = foundationRef.current;
    Eif (foundation && root) {
      foundation.adapter_.notifySelection = mSelected => {
        root.dispatchEvent(
          createEvent(
            strings.SELECTION_EVENT,
            {
              chipId,
              selected: mSelected,
              element: root,
            },
            true /* bubble */,
          ),
        );
 
        onSelected({ chipId, selected: mSelected, element: root });
      };
    }
  }, [chipId, onSelected]);
 
  useEffect(() => {
    if (foundationRef.current && shouldRemoveOnTrailingIconClick != null) {
      foundationRef.current.setShouldRemoveOnTrailingIconClick(
        shouldRemoveOnTrailingIconClick,
      );
    }
  }, [shouldRemoveOnTrailingIconClick]);
 
  useEffect(() => {
    if (foundationRef.current && beginExit === true) {
      foundationRef.current.beginExit();
    }
  }, [beginExit]);
 
  const memoizedStyle = useMemo(
    () => ({ ...style, ...rippleStyle, ...mtStyle }),
    [style, rippleStyle, mtStyle],
  );
 
  return (
    <button
      {...rest}
      {...mtAttrs}
      id={chipId}
      ref={rootRef}
      style={memoizedStyle}
      type="button"
      className={cx(
        'mdc-chip',
        className,
        ...Array.from(rippleClassName),
        ...Array.from(mtClassName),
      )}
    >
      {leadingIcon}
      {filter && (
        <span ref={checkmarkRef} className="mdc-chip__checkmark">
          <svg className="mdc-chip__checkmark-svg" viewBox="-2 -3 30 30">
            <path
              className="mdc-chip__checkmark-path"
              fill="none"
              stroke="black"
              d="M1.73,12.91 8.1,19.28 22.79,4.59"
            />
          </svg>
        </span>
      )}
      <span className="mdc-chip__text">{label}</span>
      {trailingIcon}
    </button>
  );
};
 
export default Chip;