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

70.42% Statements 50/71
50% Branches 29/58
52% Functions 13/25
71.01% Lines 49/69

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                                              5x                         5x                             13x 13x 13x   13x 9x   9x   1x   1x 1x                     1x   1x 1x                         9x           1x                                   1x         1x       1x     1x                 9x   9x   9x   9x   9x 9x 9x     9x 9x   9x 9x   9x     9x 9x       13x 9x 9x 9x           13x 9x 1x       13x 9x 1x       13x   13x             13x                   13x                                           5x            
// @flow strict
import React, {
  useEffect,
  useRef,
  useCallback,
  useImperativeHandle,
} from 'react';
import cx from 'classnames';
 
import MDCMenuFoundation from '@material/menu/foundation';
import { closest } from '@material/dom/ponyfill';
 
import type { Node } from 'react';
 
import MenuSurface from '../menu-surface';
import List from '../list';
 
import type {
  HTMLMenuSurfaceElement,
  HTMLListElement,
  HTMLListItemElement,
} from '../mt-types';
 
const noOp = () => {};
 
type Props = {
  className?: string,
  children?: Node,
  onOpened?: () => void,
  onSelected?: ({ index: number, item: HTMLListItemElement }) => void,
  selectedIndex?: number,
  defaultFocusState?: number,
  role?: 'listbox' | 'menu',
  wrapFocus?: boolean,
};
 
const Menu = React.forwardRef<Props, ?HTMLMenuSurfaceElement>(
  (
    {
      className,
      children,
      onOpened = noOp,
      onSelected = noOp,
      selectedIndex,
      defaultFocusState,
      role = 'menu',
      wrapFocus = true,
      ...rest
    }: Props,
    ref,
  ) => {
    const rootRef = useRef<?HTMLMenuSurfaceElement>();
    const listRef = useRef<?HTMLListElement>();
    const foundationRef = useRef<?MDCMenuFoundation>();
 
    useEffect(() => {
      let isMenuActive = true;
 
      const foundation = new MDCMenuFoundation({
        addClassToElementAtIndex: (index, mClassName) => {
          const list = listRef.current;
 
          Eif (list) {
            list.listElements[index].addMtClassName(mClassName);
          }
        },
        removeClassFromElementAtIndex: (index, mClassName) => {
          const list = listRef.current;
 
          if (list) {
            list.listElements[index].removeMtClassName(mClassName);
          }
        },
        addAttributeToElementAtIndex: (index, attr, value) => {
          const list = listRef.current;
 
          Eif (list) {
            list.listElements[index].setMtAttribute(attr, value);
          }
        },
        removeAttributeFromElementAtIndex: (index, attr) => {
          const list = listRef.current;
 
          if (list) {
            list.listElements[index].removeMtAttribute(attr);
          }
        },
        elementContainsClass: (element, mClassName) =>
          element.classList.contains(mClassName),
        closeSurface: (skipRestoreFocus: boolean) =>
          isMenuActive &&
          (rootRef.current &&
            rootRef.current.foundation.close(skipRestoreFocus)),
        getElementIndex: element =>
          listRef.current ? listRef.current.listElements.indexOf(element) : 0,
        getMenuItemCount: () =>
          listRef.current && listRef.current.listElements.length,
        focusItemAtIndex: index => {
          if (listRef.current) {
            listRef.current.listElements[index].focus();
          }
        },
        focusListRoot: () => {
          const element =
            rootRef.current &&
            rootRef.current.querySelector(
              MDCMenuFoundation.strings.LIST_SELECTOR,
            );
 
          if (element) {
            element.focus();
          }
        },
        isSelectableItemAtIndex: index =>
          !!closest(
            listRef.current && listRef.current.listElements[index],
            `.${MDCMenuFoundation.cssClasses.MENU_SELECTION_GROUP}`,
          ),
        getSelectedSiblingOfItemAtIndex: index => {
          const selectionGroupEl = closest(
            listRef.current && listRef.current.listElements[index],
            `.${MDCMenuFoundation.cssClasses.MENU_SELECTION_GROUP}`,
          );
          const selectedItemEl = selectionGroupEl.querySelector(
            `.${MDCMenuFoundation.cssClasses.MENU_SELECTED_LIST_ITEM}`,
          );
          return selectedItemEl && listRef.current
            ? // flowlint-next-line unclear-type:off
              (listRef.current: any).listElements.indexOf(selectedItemEl)
            : -1;
        },
        // Note. do nothing as MenuItem should handle this
        setEnabled: () => {},
      });
 
      foundation.init();
 
      foundationRef.current = foundation;
 
      const root = rootRef.current;
 
      const handleKeydown = (...args) => foundation.handleKeydown(...args);
 
      Eif (root) {
        root.items = listRef.current ? listRef.current.listElements : [];
        root.addEventListener('keydown', handleKeydown);
      }
 
      return () => {
        isMenuActive = false;
 
        Eif (root) {
          root.removeEventListener('keydown', handleKeydown);
          // $FlowFixMe
          delete root.items;
        }
 
        foundation.destroy();
        foundationRef.current = null;
      };
    }, [className]);
 
    useEffect(() => {
      Eif (foundationRef.current && listRef.current) {
        const { listElements } = listRef.current;
        foundationRef.current.adapter_.notifySelected = ({ index }) => {
          onSelected({ index, item: listElements[index] });
        };
      }
    }, [onSelected]);
 
    useEffect(() => {
      if (foundationRef.current && defaultFocusState != null) {
        foundationRef.current.setDefaultFocusState(defaultFocusState);
      }
    }, [defaultFocusState]);
 
    useEffect(() => {
      if (foundationRef.current && selectedIndex != null) {
        foundationRef.current.setSelectedIndex(selectedIndex);
      }
    }, [selectedIndex]);
 
    useImperativeHandle(ref, () => rootRef.current, []);
 
    const handleItemAction = useCallback(index => {
      if (foundationRef.current && listRef.current && !Array.isArray(index)) {
        const item = listRef.current.listElements[index];
        foundationRef.current.handleItemAction(item);
      }
    }, []);
 
    const handleMenuSurfaceOpened = useCallback(
      (...args) => {
        if (foundationRef.current) {
          foundationRef.current.handleMenuSurfaceOpened(...args);
          onOpened(...args);
        }
      },
      [onOpened],
    );
 
    return (
      <MenuSurface
        {...rest}
        ref={rootRef}
        onOpened={handleMenuSurfaceOpened}
        className={cx('mdc-menu', className)}
      >
        <List
          ref={listRef}
          role={role}
          aria-hidden="true"
          tabIndex="-1"
          wrapFocus={wrapFocus}
          onSelected={handleItemAction}
        >
          {children}
        </List>
      </MenuSurface>
    );
  },
);
 
Menu.displayName = 'Menu';
 
export { DefaultFocusState } from '@material/menu/constants';
export { Corner } from '@material/menu-surface/constants';
 
export default Menu;