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

68.5% Statements 87/127
61.29% Branches 38/62
52.78% Functions 19/36
68.25% Lines 86/126

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                      43x                                   43x   43x                                       77x 77x 77x 77x   77x 70x   70x 70x       70x   22x   70x         29x     70x   70x 70x 70x             77x 70x   5x 5x 5x                     5x       75x   58x 58x     56x 56x                                             5x 5x 5x                                                           70x                                   70x   70x                         70x                         70x         70x         70x 70x 70x 70x 70x     70x       70x   70x 70x 70x 70x 70x 70x     70x   70x       77x 70x 70x 70x       77x 70x 70x 70x       77x 70x 70x 70x 27x   70x       77x 70x   70x 70x       77x 70x   70x 70x       77x 70x 70x 5x       77x   77x   77x 34x       77x                                     43x      
// @flow strict
import React, { useEffect, useRef, useImperativeHandle } from 'react';
import cx from 'classnames';
 
import MDCListFoundation from '@material/list/foundation';
import { closest, matches } from '@material/dom/ponyfill';
 
import type { Node, ElementType } from 'react';
 
import type { HTMLListItemElement, HTMLListElement } from '../mt-types';
 
const noOp = () => {};
 
type Props = {
  as?: ElementType,
  asActived?: true,
  avatarList?: boolean,
  children?: Node,
  className?: string,
  dense?: boolean,
  nonInterative?: boolean,
  onSelected?: (selected: number[] | number) => void,
  role?: 'list' | 'listbox' | 'radiogroup' | 'group' | 'menu',
  selected?: number | number[],
  twoLines?: boolean,
  vertical?: boolean,
  wrapFocus?: boolean,
};
 
const { cssClasses, strings } = MDCListFoundation;
 
const List = React.forwardRef<Props, ?HTMLListElement>(
  (
    {
      as: Component = 'ul',
      asActived = false,
      avatarList = false,
      children,
      className,
      dense = false,
      nonInterative = false,
      onSelected = noOp,
      role = 'list',
      selected,
      twoLines = false,
      vertical = true,
      wrapFocus = false,
      ...rest
    }: Props,
    ref,
  ) => {
    const foundationRef = useRef<?MDCListFoundation>();
    const rootRef = useRef();
    const listElementsRef = useRef<HTMLListItemElement[]>([]);
    const childrenCount = React.Children.count(children);
 
    useEffect(() => {
      const root = rootRef.current;
 
      Eif (root) {
        listElementsRef.current = [].slice.call(
          root.querySelectorAll(`.${cssClasses.LIST_ITEM_CLASS}`),
        );
 
        [].slice
          .call(root.querySelectorAll(strings.FOCUSABLE_CHILD_ELEMENTS))
          .forEach((el: HTMLElement) => el.setAttribute('tabindex', '-1'));
 
        if (
          (selected == null || selected.length === 0) &&
          listElementsRef.current.length > 0 &&
          listElementsRef.current[0].setMtAttribute
        ) {
          listElementsRef.current[0].setMtAttribute('tabindex', 0);
        }
 
        root.listElements = listElementsRef.current || [];
 
        return () => {
          listElementsRef.current = [];
          delete root.listElements;
        };
      }
 
      return () => {};
    }, [childrenCount, selected]);
 
    useEffect(() => {
      const foundation = new MDCListFoundation({
        addClassForElementIndex: (index, mClassName) => {
          const element = listElementsRef.current[index];
          Eif (element) {
            element.addMtClassName(mClassName);
          }
        },
        focusItemAtIndex: index => {
          // flowlint-next-line unclear-type:off
          const element = ((listElementsRef.current[index]: any): HTMLElement);
          if (element) {
            element.focus();
          }
        },
        getAttributeForElementIndex: (index, attr) =>
          listElementsRef.current[index].getAttribute(attr),
        getFocusedElementIndex: () =>
          listElementsRef.current.indexOf(document.activeElement),
        getListItemCount: () =>
          listElementsRef.current && listElementsRef.current.length,
        hasCheckboxAtIndex: index => {
          const listItem = listElementsRef.current[index];
          return !!listItem.querySelector(strings.CHECKBOX_SELECTOR);
        },
        hasRadioAtIndex: index => {
          const listItem = listElementsRef.current[index];
          return !!listItem.querySelector(strings.RADIO_SELECTOR);
        },
        isCheckboxCheckedAtIndex: index => {
          const listItem = listElementsRef.current[index];
          const toggleEl = listItem.querySelector<HTMLInputElement>(
            strings.CHECKBOX_SELECTOR,
          );
          return toggleEl.checked;
        },
        isFocusInsideList: () => {
          return (
            rootRef.current != null &&
            rootRef.current.contains(document.activeElement)
          );
        },
        isRootFocused: () => document.activeElement === rootRef.current,
        removeClassForElementIndex: (index, mClassName) => {
          const element = listElementsRef.current[index];
          if (element) {
            element.removeMtClassName(mClassName);
          }
        },
        setAttributeForElementIndex: (index, attr, value) => {
          const element = listElementsRef.current[index];
          Eif (element) {
            element.setMtAttribute(attr, value);
          }
        },
        setCheckedCheckboxOrRadioAtIndex: (index, isChecked) => {
          const listItem = listElementsRef.current[index];
          const toggleEl = listItem.querySelector<HTMLInputElement>(
            MDCListFoundation.strings.CHECKBOX_RADIO_SELECTOR,
          );
 
          if (toggleEl) {
            toggleEl.checked = isChecked;
 
            const event = document.createEvent('Event');
            event.initEvent('change', true, true);
            toggleEl.dispatchEvent(event);
          }
        },
        setTabIndexForListItemChildren: (listItemIndex, tabIndexValue) => {
          const element = listElementsRef.current[listItemIndex];
          const listItemChildren: HTMLElement[] = element.querySelectorAll(
            strings.CHILD_ELEMENTS_TO_TOGGLE_TABINDEX,
          );
          listItemChildren.forEach(el =>
            el.setAttribute('tabindex', tabIndexValue),
          );
        },
        // Note. do nothing as ListItem should handle this
        setEnabled: () => {},
      });
 
      const getListItemIndex = (evt: SyntheticEvent<HTMLElement>) => {
        const eventTarget = evt.target; // as Element;
        const nearestParent = closest(
          eventTarget,
          `.${cssClasses.LIST_ITEM_CLASS}, .${cssClasses.ROOT}`,
        );
 
        // Get the index of the element if it is a list item.
        if (
          nearestParent &&
          matches(nearestParent, `.${cssClasses.LIST_ITEM_CLASS}`)
        ) {
          return listElementsRef.current.indexOf(nearestParent);
        }
 
        return -1;
      };
 
      const root = rootRef.current;
 
      const handleKeydownEvent = (evt: SyntheticKeyboardEvent<HTMLElement>) => {
        const index = getListItemIndex(evt);
        const { target } = evt;
        foundation.handleKeydown(
          evt,
          // flowlint-next-line unclear-type:off
          ((target: any): HTMLElement).classList.contains(
            cssClasses.LIST_ITEM_CLASS,
          ),
          index,
        );
      };
 
      const handleClick = (evt: SyntheticMouseEvent<HTMLElement>) => {
        const index = getListItemIndex(evt);
        const { target } = evt;
 
        // Toggle the checkbox only if it's not the target of the event,
        // or the checkbox will have 2 change events.
        const toggleCheckbox = !matches(
          target,
          strings.CHECKBOX_RADIO_SELECTOR,
        );
        foundation.handleClick(index, toggleCheckbox);
      };
 
      const handleFocusInEvent = (evt: SyntheticFocusEvent<HTMLElement>) => {
        const index = getListItemIndex(evt);
        foundation.handleFocusIn(evt, index);
      };
 
      const handleFocusOutEvent = (evt: SyntheticFocusEvent<HTMLElement>) => {
        const index = getListItemIndex(evt);
        foundation.handleFocusOut(evt, index);
      };
 
      Eif (root) {
        root.addEventListener('keydown', handleKeydownEvent);
        root.addEventListener('click', handleClick);
        root.addEventListener('focusin', handleFocusInEvent);
        root.addEventListener('focusout', handleFocusOutEvent);
      }
 
      foundation.init();
 
      // this.initializeListType();
 
      foundationRef.current = foundation;
 
      return () => {
        Eif (root) {
          root.removeEventListener('keydown', handleKeydownEvent);
          root.removeEventListener('click', handleClick);
          root.removeEventListener('focusin', handleFocusInEvent);
          root.removeEventListener('focusout', handleFocusOutEvent);
        }
 
        foundationRef.current = null;
 
        foundation.destroy();
      };
    }, [className]);
 
    useEffect(() => {
      const foundation = foundationRef.current;
      Eif (foundation) {
        foundation.setWrapFocus(wrapFocus);
      }
    }, [wrapFocus]);
 
    useEffect(() => {
      const foundation = foundationRef.current;
      Eif (foundation) {
        foundation.setSingleSelection(role === 'listbox');
      }
    }, [role]);
 
    useEffect(() => {
      const foundation = foundationRef.current;
      Eif (foundation) {
        if (role !== 'list') {
          foundation.setVerticalOrientation(vertical);
        }
        foundation.layout();
      }
    }, [role, vertical]);
 
    useEffect(() => {
      const foundation = foundationRef.current;
 
      Eif (foundation) {
        foundation.setUseActivatedClass(asActived);
      }
    }, [asActived]);
 
    useEffect(() => {
      const foundation = foundationRef.current;
 
      Eif (foundation) {
        foundation.adapter_.notifyAction = onSelected;
      }
    }, [onSelected]);
 
    useEffect(() => {
      const foundation = foundationRef.current;
      if (foundation && selected != null) {
        foundation.setSelectedIndex(selected);
      }
    }, [selected]);
 
    useImperativeHandle(ref, () => rootRef.current, []);
 
    const extraProps = {};
 
    if (role !== 'list') {
      extraProps['aria-orientation'] =
        vertical === true ? 'vertical' : 'horizontal';
    }
 
    return (
      <Component
        {...(rest: mixed)}
        {...extraProps}
        role={role}
        ref={rootRef}
        className={cx('mdc-list', className, {
          'mdc-list--two-line': twoLines,
          'mdc-list--avatar-list': avatarList,
          'mdc-list--dense': dense,
          'mdc-list--non-interactive': nonInterative,
        })}
      >
        {children}
      </Component>
    );
  },
);
 
List.displayName = 'List';
 
export default List;