All files / packages/sds-components/src/sds/menuManager menuManager.js

45.71% Statements 64/140
38.46% Branches 25/65
61.53% Functions 24/39
45.98% Lines 63/137

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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450                            3x 3x 3x 3x   3x           3x                                                             3x 3x               37x                     18x 18x 52x 12x                                                     30x               3x 3x 6x 6x     3x               3x                                                                                                                                                                         6x 6x 6x               19x   6x 1x 1x 5x   1x 1x 1x 2x 2x           4x                   6x                       28x     28x                         13x 3x   10x                 28x 28x 28x                                         3x 3x               26x       26x                                                                                                               3x 3x 3x                     3x 3x       28x 28x 28x 28x 26x                                         3x 3x 3x         1x 1x                 1x              
import { LightningElement, api } from 'lwc';
import 'sds/privateThemeProvider';
 
/**
 * TODO: Add menubar behavior
 * TODO: Add support for nested menu items behavior
 * TODO: Add support for left and right keys navigation when nested menus is built
 * TODO: Toggle orientation when menubar is built in
 * TODO: Add support for menuitemcheckbox and menuitemradio
 */
export default class MenuManager extends LightningElement {
  static shadowSupportMode = 'native';
 
  _valid = true;
  _groupsInSlot = false;
  _value = '';
  _rendered = false;
  _currentMenuItem = '';
 
  /**
   * The value of the menu.
   * @returns {string}
   */
  @api
  get value() {
    return this._value;
  }
 
  /**
   * Method to focus the Menu.
   */
  @api
  focus() {
    this.menu.focus();
  }
 
  get menu() {
    this._menuElement = this._menuElement || this.template.querySelector('[role="menu"]');
 
    return this._menuElement;
  }
 
  /**
   * Get all slotted children of the menu.
   * @returns {Array}
   */
  get slottedChildren() {
    const slot = this.template.querySelector('slot');
    return slot.assignedElements({ flatten: true });
  }
 
  /**
   * Get all valid slotted children of the menu. Checks for menu groups and returns the menu items.
   * @returns {Array}
   */
  get directChildren() {
    const groupedChildren = [];
    this.slottedChildren.forEach((item) => {
      if (item.children.length > 0) {
        groupedChildren.push(...item.children);
      }
    });
    return this._groupsInSlot
      ? groupedChildren.filter((item) => item.role !== 'presentation')
      : this.slottedChildren;
  }
 
  /**
   * Get all entries passed to menu and returns if they are valid menus.
   * @returns {Array}
   */
  get menuEntries() {
    return this.directChildren.filter((item) => item.id);
  }
 
  /**
   * Get all valid menu items passed to menu. This happens after component is upgraded when contracts are met.
   * @returns {Array}
   */
  get menuItems() {
    return this.directChildren.filter((item) => item.role === 'menuitem');
  }
 
  /**
   * Get the labels of an menu group.
   * @returns {Array}
   */
  get menuGroupLabels() {
    return this.allDirectChildren.filter((item) => item.role === 'presentation' && item.id);
  }
 
  /**
   * Get all valid slotted children of the menu. Includes all menu items including presentation nodes.
   * @returns {Array}
   */
  get allDirectChildren() {
    const groupedChildren = [];
    this.slottedChildren.forEach((item) => {
      if (item.children.length > 0) {
        groupedChildren.push(...item.children);
      }
    });
    return this._groupsInSlot ? groupedChildren : this.slottedChildren;
  }
 
  /**
   * Get the first item of the menu.
   * @returns {HTMLElement}
   */
  get firstMenuItem() {
    return this.menuEntries[0];
  }
 
  /**
   * Event handler for keydown events on the menu.
   * @param {KeyboardEvent} e
   *E/
  onMenuKeydown(e) {
    const inFocusMenuItem = this._currentMenuItem || this.firstMenuItem;
    let nextFocusMenuItem = null;
    let flag = false;
    if (!inFocusMenuItem) {
      return;
    }
    switch (e.key) {
      case 'ArrowUp':
        nextFocusMenuItem = this.findPrevMenuItem(inFocusMenuItem);
        flag = true;
        break;
      case 'ArrowDown':
        nextFocusMenuItem = this.findNextMenuItem(inFocusMenuItem);
        flag = true;
        break;
      case ' ':
      case 'Enter':
        this.onMenuItemClick(inFocusMenuItem);
        flag = true;
        break;
      case 'Tab':
        this.resetMenuSelection();
        break;
      default:
        break;
    }
    if (nextFocusMenuItem) {
      this.setFocusToMenuitem(nextFocusMenuItem);
    }
    if (flag) {
      e.stopPropagation();
      e.preventDefault();
    }
  }
 
  /**
   * Method to find the previous menu item in the menu.
   * @param {HTMLElement} currentMenuItem
   * @returns {HTMLElement}
   */
  findPrevMenuItem(currentMenuItem) {
    const allMenuItems = [...this.menuItems];
    const currentMenuItemIndex = allMenuItems.indexOf(currentMenuItem);
    let prevMenuItem = null;
 
    if (currentMenuItemIndex > 0) {
      prevMenuItem = allMenuItems[currentMenuItemIndex - 1];
    }
    if (currentMenuItemIndex === 0) {
      prevMenuItem = allMenuItems[allMenuItems.length - 1];
    }
    return prevMenuItem;
  }
 
  /**
   * Method to find the next menu item in the menu.
   * @param {HTMLElement} currentMenuItem
   * @returns {HTMLElement}
   */
  findNextMenuItem(currentMenuItem) {
    const allMenuItems = [...this.menuItems];
    const currentMenuItemIndex = allMenuItems.indexOf(currentMenuItem);
    let nextMenuItem = null;
 
    if (currentMenuItemIndex > -1 && currentMenuItemIndex < allMenuItems.length - 1) {
      nextMenuItem = allMenuItems[currentMenuItemIndex + 1];
    }
    if (currentMenuItemIndex === allMenuItems.length - 1) {
      nextMenuItem = allMenuItems[0];
    }
    return nextMenuItem;
  }
 
  /**
   * Method to check for contracts of menu.
   * @returns {boolean}
   */
  handleValidContracts() {
    // Need to run first so we can check if the parent element is valid and has children
    this.handleValidParentWithChildren();
    const slottedElement = this.directChildren;
    this.handleValidChildrenWithParent(slottedElement);
  }
 
  /**
   * Method to check if menu contains parent elements with children, handles single and multiple parents (menu groups).
   * @returns {boolean}
   */
  handleValidParentWithChildren() {
    const groups = this.slottedChildren.filter((item) => this.checkValidParent(item));
    // Deal with single parent, such as a div, ul, or ol
    if (groups.length === 1) {
      this._groupsInSlot = true;
      groups[0].setAttribute('role', 'presentation');
    } else if (groups.length > 1) {
      // Deal with multiple parents, which are menu groups, they required a label
      this._groupsInSlot = true;
      if (this.menuGroupLabels.length === groups.length) {
        [...groups].forEach((item, key) => {
          item.setAttribute('role', 'group');
          item.setAttribute('aria-labelledby', this.menuGroupLabels[key].id);
        });
      } else {
        console.error(
          'We have determined you have menu groups, but not all of them have labels. Please add an element with role="presentation" and a unique id to each group.',
        );
      }
    } else {
      return;
    }
  }
 
  /**
   * Method to check if menu contains valid children.
   * @param {HTMLElement} parentElement
   * @returns {boolean}
   */
  handleValidChildrenWithParent(parentElement) {
    if (EparentElement.length !== this.menuEntries.length) {
      this._valid = false;
      console.error(
        'Contracts for Menu Manager have not been met, please ensure each menu item has an "id" attribute, with a unique value.',
      );
    }
  }
 
  /**
   * Method to check if the menu item is valid and contains no interactive elements.
   * @param {HTMLElement} item
   * @returns {boolean}
   */
  handleValidMenuItem(item) {
    Iif (item.role !== 'menuitem') {
      return;
    }
    if (item.children.length > 0) {
      const interactiveElements = this.findInteractiveChildren(item);
      if (interactiveElements.length > 0) {
        console.error('Menu items cannot be interactive elements, please use a <span> or <div> instead.');
      }
    }
  }
 
  /**
   *I Method to find interactive elements within the menu items.
   * @param {HTMLElement} root
   * @returns {Array}
   *I/
  findInteractiveChildren = (root) => {
    const elements = [];
    function traverse(node) {
      if (node.nodeType === Node.ELEMENT_NODE) {
        if (
          node instanceof HTMLAnchorElement ||
          node instanceof HTMLButtonElement ||
          node instanceof HTMLInputElement
        ) {
          elements.push(node);
        }
        for (let i = 0; i < node.childNodes.length; i++) {
          traverse(node.childNodes[i]);
        }
      }
    }
    traverse(root);
    return elements;
  };
 
  /**
   * Method to check if the parent element is valid, only allows div, ul, and ol.
   * @param {HTMLElement} parentElement
   * @returns {boolean}
   */
  checkValidParent(parentElement) {
    if (
      parentElement instanceof HTMLUListElement ||
      parentElement instanceof HTMLDivElement ||
      parentElement instanceof HTMLOListElement
    ) {
      return true;
    } else {
      return false;
    I}
  }
 
  /**
   * Set the initial state of the menu items.
   * @param {HTMLElement} item
   */
  handleAriaRoles(menuItem) {
    menuItem.setAttribute('role', 'menuitem');
    menuItem.setAttribute('tabindex', '-1');
    menuItem.title = menuItem.textContent;
  }
 
  /**
   * Method to handle disabled menu items. Adds aria-disabled attribute and tabindex=-1 to disabled menu items.
   * @param {*} item
   */
  handleDisabledMenuItem(item) {
    if (item.hasAttribute('disabled')) {
      item.setAttribute('aria-disabled', 'true');
    } else {
      item.setAttribute('aria-disabled', 'false');
    }
  }
 
  /**
   * Method to handle focus of menu. Sets focus on the first menu item when navigating with keyboard.
   * If single select, will focus and select the active descendant.
   */
  handleFocus() {
    const firstItem = this.firstMenuItem;
    this.setAriaActiveDescendant(firstItem.id);
    firstItem.setAttribute('focus', '');
  }
 
  /**
   * Method to add all associated event listeners to the menu item.
   * @param {HTMLElement} menuItem
   */
  bindEventListenersToMenuItem(menuItem) {
    menuItem.addEventListener('click', (e) => {
      let clickedMenuItem = e.currentTarget;
      this.onMenuItemClick(clickedMenuItem);
    });
    menuItem.addEventListener('mouseover', (e) => {
      this.onMenuitemMouseover(e);
    });
  }
 
  /**
   * Method to handle the click event on a menu item.
   * @param {HTMLElement} currentMenuItem
   */
  onMenuItemClick(currentMenuItem) {
    if (!currentMenuItem.hasAttribute('aria-disabled')) {
      this._value = currentMenuItem.textContent;
      currentMenuItem.removeAttribute('focus');
      this.setAriaActiveDescendant();
      this.dispatchEvent(new CustomEvent('selectionchange', { detail: 'sds-menu-manager' }));
    }
  }
 
  /*I*
   * Method to handle the mouseover event on a menu item.
   * @param {MouseEvent} event
   */
  onMenuitemMouseover(event) {
    var tgt = event.currentTarget;
    this.setFocusToMenuitem(tgt);
  }
 
  /**
   * Method to set focus on the menu item when they are
   * traversed through keyboard navigation.
   * @param {HTMLElement} newMenuItem
   */
  setFocusToMenuitem(newMenuItem) {
    [...this.directChildren].forEach((menuItem) => {
      if (menuItem === newMenuItem) {
        menuItem.setAttribute('focus', '');
        this._currentMenuItem = menuItem;
        if (menuItem.hasAttribute('aria-disabled')) {
          this.setAriaActiveDescendant();
        } else {
          this.setAriaActiveDescendant(menuItem.id);
        E}
      } else {
        menuItem.removeAttribute('focus');
      }
    });
  }
 
  /**
   * Method to set aria-activedescendant attribute when navigating over the menu items.
   * It's vaue is set to empty when a menu item is selected.
   * * @param {String} menuItem id
   *I/
  setAriaActiveDescendant(id) {
    const menu = this.menu;
 
    if (id) {
      menu.setAttribute('aria-activedescendant', id);
    } else {
      menu.setAttribute('aria-activedescendant', '');
    }
  }
 
  /**
   * Event handler for slot change. Upgrades the menu when contracts are met and binds event listeners to the menu items.
   * @param {Event} e
   */
  handleSlotChange(e) {
    this.handleValidContracts();
    if (!this._valid) {
      return;
    }
 
    [...this.directChildren].forEach((item) => {
      const isDisabled = item.hasAttribute('disabled');
      this.handleAriaRoles(item);
      this.handleValidMenuItem(item);
      if (!isDisabled) {
        this.bindEventListenersToMenuItem(item);
      } else {
        item.setAttribute('aria-disabled', 'true');
      }
    });
  }
 
  /**
   * Method to reset the Menu.
   * Removes focus on any menu item and clears the aria-activedescendant attribute.
   */
  resetMenuSelection() {
    this._currentMenuItem && this._currentMenuItem.removeAttribute('focus');
    this.setAriaActiveDescendant();
  }
 
  /**
   * When the component renders, we validate the contracts and upgrade the menu.
   */
  renderedCallback() {
    if (!this._rendered) {
      this._rendered = true;
      this.handleValidContracts();
      this.addEventListener('mouseleave', this.resetMenuSelection.bind(this));
    }
  }
}