All files / lib/Menu index.js

80% Statements 68/85
67.74% Branches 42/62
76.47% Functions 13/17
80% Lines 68/85
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                                  19x             12x 12x   12x           6x 6x   6x   6x           6x         19x 19x 19x   19x       19x     19x 19x   19x           2x 2x       2x           4x 4x 4x   4x 4x 4x   4x 2x 2x               4x           4x                                                     4x     4x 4x   4x   1x             1x 1x     1x             1x 1x     1x         1x     1x 1x     1x       1x 1x                   4x 4x 4x                   22x 22x   22x 30x 48x         1x         47x 47x   47x 47x     47x                     22x                                 89x                 89x           89x       89x         89x  
import React from 'react';
import PropTypes from 'prop-types';
import { isEqual } from 'lodash';
 
/**
 * Menu is container component which contains MenuItems
 * @component Menu
 * @variations collab-ui-react
 */
 
export default class Menu extends React.Component {
 
  state = {
    menuIndex: []
  };
 
  getChildContext = () => {
    return {
      handleClick: this.handleClick,
      handleKeyDown: this.handleKeyDown,
    };
  };
 
  componentWillMount() {
    const { children } = this.props;
    const initialIndex = this.getNewIndex(-1, 1, React.Children.toArray(children));
 
    this.setState({
      menuIndex: [initialIndex]
    });
  }
 
  handleClick = (e, menuItemIndex, menuItem) => {
    const { onSelect } = this.context;
    const { children } = menuItem.props;
    const selectedChildIndex =
      children && this.getNewIndex(-1, 1, React.Children.toArray(children));
 
    this.setState(
      {
        menuIndex: children
          ? menuItemIndex.concat(selectedChildIndex)
          : [menuItemIndex[0]]
      },
      () => onSelect && onSelect(e, menuItemIndex, menuItem)
    );
  };
 
  getNewIndex = (currentIndex, change, siblings) => {
    const getPossibleIndex = () => {
      const length = siblings.length - 1;
      Iif (currentIndex + change < 0) {
        return length;
      } else Iif (currentIndex + change > length) {
        return 0;
      }
 
      return currentIndex + change;
    };
 
    const possibleIndex = getPossibleIndex();
    const potentialTarget = React.Children.toArray(siblings)[possibleIndex];
 
    return potentialTarget.props.disabled || potentialTarget.props.isHeader
      ? this.getNewIndex(possibleIndex, change, siblings)
      : possibleIndex;
  };
 
  setFocusInCurrentMenu = newIndex => {
    const { menuIndex } = this.state;
    const clonedIndex = !menuIndex.length
      ? [...newIndex]
      : [...menuIndex.slice(0, menuIndex.length - 1), newIndex];
 
    this.setState({
      menuIndex: clonedIndex
    });
  };
 
  handleKeyDown = (e, selectedIndex, menuItem) => {
    const { menuIndex } = this.state;
    const { children } = this.props;
    const { onSelect } = this.context;
 
    const subMenu = menuItem.props.children;
    const subMenuIndex = subMenu && this.getNewIndex(-1, 1, React.Children.toArray(subMenu));
    const originIndex = selectedIndex[selectedIndex.length - 1];
 
    const getSiblings = (idx, menuItems = children) => {
      Eif (idx.length === 1) {
        return menuItems;
      }
      return getSiblings(
        idx.slice(1),
        React.Children.toArray(menuItems[idx[0]].props.children)
      );
    };
 
    const getIncludesFirstCharacter = (str, char) =>
      str
        .charAt(0)
        .toLowerCase()
        .includes(char);
 
    const setFocusByFirstCharacter = (char, currentIdx) => {
      const siblings = getSiblings(currentIdx);
      const length = siblings.length - 1;
      const indexInSubmenu = currentIdx[currentIdx.length - 1];
 
      const newIndex = React.Children.toArray(siblings).reduce(
        (agg, child, idx, arr) => {
          const index =
            indexInSubmenu + idx + 1 > length
              ? Math.abs(indexInSubmenu + idx - length)
              : indexInSubmenu + idx + 1;
 
          const label = arr[index].props.label;
 
          return !agg.length
            && !arr[index].props.disabled
            && !arr[index].props.isReadOnly
            && getIncludesFirstCharacter(label, char)
              ? agg.concat(index)
              : agg;
        },
        []
      );
 
      !isNaN(newIndex[0]) && this.setFocusInCurrentMenu(newIndex[0]);
    };
 
    const isPrintableCharacter = str => {
      return str.length === 1 && str.match(/\S/);
    };
    let flag = false;
    const char = e.key;
 
    switch (e.which) {
      case 38:
        this.setFocusInCurrentMenu(
          this.getNewIndex(
            originIndex,
            -1,
            getSiblings(selectedIndex)
          )
        );
        flag = true;
        break;
 
      case 40:
        this.setFocusInCurrentMenu(
          this.getNewIndex(
            originIndex,
            1,
            getSiblings(selectedIndex)
          )
        );
        flag = true;
        break;
 
      case 39: //right
        subMenu &&
          this.setState(
            {
              menuIndex: menuIndex.concat(subMenuIndex)
            },
            () => onSelect && onSelect(e, menuIndex, menuItem)
          );
 
        flag = true;
        break;
 
      case 37: //left
        menuIndex.length - 1 &&
          this.setState({
            menuIndex: menuIndex.slice(0, menuIndex.length - 1)
          });
        flag = true;
        break;
 
      default:
        if (isPrintableCharacter(char)) {
          setFocusByFirstCharacter(char, selectedIndex);
          flag = true;
        }
        break;
    }
 
    Eif (flag) {
      e.stopPropagation();
      e.preventDefault();
    }
  };
 
  render() {
    const {
      ariaLabel,
      children,
      className,
      ...props
    } = this.props;
    const { menuIndex } = this.state;
 
    const setMenuItems = (menuList, currentItemIndex = []) => {
      return React.Children.toArray(menuList).map((child, idx) => {
        if (
          !child.type
            ||
          !['MenuItem', 'SubMenu'].includes(child.type.displayName)
        ) {
          throw new Error(
            '[@collab-ui/react] Menu: children of Menu should be of type MenuItem or SubMenu'
          );
        }
 
        const menuItemIndex = currentItemIndex.concat(idx);
        const menuItems = child.props.children;
 
        const focus = isEqual(menuIndex, menuItemIndex);
        const isOpen = isEqual(menuIndex.slice(0, menuItemIndex.length), menuItemIndex)
          && menuIndex.length !== menuItemIndex.length;
 
        return React.cloneElement(child, {
          index: menuItemIndex,
          focus,
          isOpen,
          ...child.type.displayName === 'SubMenu' && {
            children: menuItems && setMenuItems(React.Children.toArray(menuItems), menuItemIndex),
          },
        });
      });
    };
 
    return (
      <div
        className={
          'cui-menu' +
          ' cui-menu-item-container' +
          `${(className && ` ${className}`) || ''}`
        }
        aria-label={ariaLabel}
        role="menubar"
        {...props}
      >
        {setMenuItems(children)}
      </div>
    );
  }
}
 
Menu.propTypes = {
  /** @prop Text to display for accessibility features | ''  */
  ariaLabel: PropTypes.string,
  /** @prop Children nodes to render inside Menu | null */
  children: PropTypes.node,
  /** @prop Optional css class name | '' */
  className: PropTypes.string,
};
 
Menu.defaultProps = {
  ariaLabel: '',
  children: null,
  className: '',
};
 
Menu.contextTypes = {
  onSelect: PropTypes.func,
};
 
Menu.childContextTypes = {
  handleClick: PropTypes.func,
  handleKeyDown: PropTypes.func
};
 
Menu.displayName = 'Menu';