All files / coral-component-shell/src/scripts ShellMenuBarItem.js

98.13% Statements 105/107
88.89% Branches 64/72
96.67% Functions 29/30
98.13% Lines 105/107

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                                                                      2x                                             2x                 2x     2x   2x 4x                     2x 2x   2x           92x   92x   92x 92x   92x                 92x                     2x     20x   20x   20x               12x   12x 12x   12x 2x 10x 10x                 2x               52x   52x   26x       26x   26x 24x     26x             1x                           38x 6x 2x     32x               92x   92x 92x 92x   92x 20x 20x   72x       72x     92x   92x 14x                               2x     6x                         4x     2x   2x                       6x         4x 4x   4x     4x 4x                                   14x                             54x     16x     16x 4x     12x   12x     12x   12x 8x     12x     12x                     2x     92x       92x                             164x         38x 18x 18x   20x 20x       38x 26x 26x   26x 20x   12x 2x                         42x     22x 22x 22x 22x   22x 20x 20x   2x 2x           668x      
/**
 * Copyright 2019 Adobe. All rights reserved.
 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy
 * of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
 * OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
 
import {BaseComponent} from '../../../coral-base-component';
import {commons, transform, validate} from '../../../coral-utils';
import '../../../coral-component-icon';
import '../../../coral-component-button';
import '../../../coral-component-anchorbutton';
import menuBarItem from '../templates/menuBarItem';
 
/**
 Enumeration for {@link ShellMenuBarItem} icon variants.
 
 @typedef {Object} ShellMenuBarItemIconVariantEnum
 
 @property {String} DEFAULT
 A default menubar item.
 @property {String} CIRCLE
 A round image as menubar item.
 */
const iconVariant = {
  DEFAULT: 'default',
  CIRCLE: 'circle'
};
 
/**
 Enumeration for valid aria-haspopup values.
 
 @typedef {Object} ShellMenuBarItemHasPopupRoleEnum
 @property {String} MENU
 ShellMenuBarItem opens a menu.
 @property {String} LISTBOX
 ShellMenuBarItem opens a list box.
 @property {String} TREE
 ShellMenuBarItem opens a tree.
 @property {String} GRID
 ShellMenuBarItem opens a grid.
 @property {String} DIALOG
 ShellMenuBarItem opens a dialog.
 @property {Null} DEFAULT
 Defaults to null.
 
 */
const hasPopupRole = {
  MENU: 'menu',
  LISTBOX: 'listbox',
  TREE: 'tree',
  GRID: 'grid',
  DIALOG: 'dialog',
  DEFAULT: null
};
 
// the Menubar Item's base classname
const CLASSNAME = '_coral-Shell-menubar-item';
 
// Builds a string containing all possible iconVariant classnames. This will be used to remove classnames when the variant
// changes
const ALL_ICON_VARIANT_CLASSES = [];
for (const variantValue in iconVariant) {
  ALL_ICON_VARIANT_CLASSES.push(`${CLASSNAME}--${iconVariant[variantValue]}`);
}
 
/**
 @class Coral.Shell.MenuBar.Item
 @classdesc A Shell MenuBar Item component
 @htmltag coral-shell-menubar-item
 @extends {HTMLElement}
 @extends {BaseComponent}
 */
class ShellMenuBarItem extends BaseComponent(HTMLElement) {
  /** @ignore */
  constructor() {
    super();
 
    // Templates
    this._elements = {};
    menuBarItem.call(this._elements);
 
    // Events
    this._delegateEvents({
      'click [handle="shellMenuButton"]': '_handleButtonClick',
 
      // it has to be global because the menus are not direct children
      'global:coral-overlay:close': '_handleOverlayEvent',
      'global:coral-overlay:beforeclose': '_handleOverlayBeforeEvent',
      'global:coral-overlay:open': '_handleOverlayEvent',
      'global:coral-overlay:beforeopen': '_handleOverlayBeforeEvent'
    });
  }
 
  /**
   Specifies the icon name used inside the menu item.
   See {@link Icon} for valid icon names.
 
   @type {String}
   @default ""
   @htmlattribute icon
   */
  get icon() {
    return this._elements.shellMenuButton.icon;
  }
 
  set icon(value) {
    this._elements.shellMenuButton.icon = value;
  }
 
  /**
   Size of the icon. It accepts both lower and upper case sizes. See {@link ButtonIconSizeEnum}.
 
   @type {String}
   @default ButtonIconSizeEnum.SMALL
   @htmlattribute iconsize
   @htmlattributereflected
   */
  get iconSize() {
    return this._elements.shellMenuButton.iconSize;
  }E
 
  set iconSize(value) {
    this._elements.shellMenuButton.iconSize = value;
    // Required for styling
    this._reflectAttribute('iconsize', this.iconSize);
  }
 
  /**
   The menubar item's iconVariant. See {@link ShellMenuBarItemIconVariantEnum}.
 
   @type {String}
   @deEfault ShellMenuBarItemIconVariantEnum.DEFAULT
   @htmlattribute iconvariant
   */
  get iconVariant() {
    return this._iconVariant || iconVariant.DEFAULT;
  }E
 
  set iconVariant(value) {
    value = transform.string(value).toLowerCase();
    this._iconVariant = validate.enumeration(iconVariant)(value) && value || iconVariant.DEFAULT;
 
    // removes all the existing variants
    this.classList.remove(...ALL_ICON_VARIANT_CLASSES);
    // adds the new variant
    if (this.variant !== iconVariant.DEFAULT) {
      this.classList.add(`${CLASSNAME}--${this._iconVariant}`);
    }
  }
 
  /**
   The notification badge content.
 
   @type {String}
   @default ""
   @htmlattribute badge
   */
  get badge() {
    return this._elements.shellMenuButton.getAttribute('badge') || '';
  }
 
  set badge(value) {
    // Non-truthy values shouldn't show
    // null, empty string, 0, etc
    this._elements.shellMenuButton[!value || value === '0' ? 'removeAttribute' : 'setAttribute']('badge', value);
  }
 
  /**
   Whether the menu is open or not.
 
   @type {Boolean}
   @default false
   @htmlattribute open
   @htmlattributereflected
 
   @emits {coral-shell-menubar-item:open}
   @emits {coral-shell-menubar-item:close}
   */
  get open() {
    return this._open || false;
  }
 
  set open(value) {
    const menu = this._getMenu();
 
    // if we want to open the dialog we need to make sure there is a valid menu or hasPopup
    if (menu === null && this.hasPopup === hasPopupRole.DEFAULT) {
      return;
    }
 
    this._open = transform.booleanAttr(value);
    this._reflectAttribute('open', this._open);
 
    // if the menu is valid, toggle the menu and trigger the appropriate event
    if (menu !== null) {
      // Toggle the target menu
      if (menu.open !== this._open) {
        menu.open = this._open;
      }
 
      this.trigger(`coral-shell-menubar-item:${this._open ? 'open' : 'close'}`);
    }
 
    this._elements.shellMenuButton.setAttribute('aria-expanded', this._open);
  }
 
  /**
   The menubar item's label content zone.
 
   @type {ButtonLabel}
   @contentzone
   */
  get label() {
    return this._getContentZone(this._elements.shellMenuButtonLabel);
  }
 
  set label(value) {
    this._setContentZone('label', value, {
      handle: 'shellMenuButtonLabel',
      tagName: 'coral-button-label',
      insert: function (label) {
        this._elements.shellMenuButton.label = label;
      }
    });
  }
 
  /**
   The menu that this menu item should show. If a CSS selector is provided, the first matching element will be
   used.
 
   @type {?HTMLElement|String}
   @default null
   @htmlattribute menu
   */
  get menu() {
    return this._menu || null;
  }
 
  set menu(value) {
    let menu;
    if (value instanceof HTMLElement) {
      this._menu = value;
      menu = this._menu;
    } else {
      this._menu = String(value);
      menu = document.querySelector(this._menu);
    }
 
    // Link menu with item
    if (menu !== null) {
      this.id = this.id || commons.getUID();
      menu.setAttribute('target', `#${this.id}`);
      if (this.hasPopup === hasPopupRole.DEFAULT) {
        this.hasPopup = menu.getAttribute('role') || hasPopupRole.DIALOG;
      }
    } else if (this._menu && this.hasPopup !== hasPopupRole.DEFAULT) {
      this.hasPopup = hasPopupRole.DEFAULT;
    }
  }
 
  /**
   Whether the item opens a popup dialog or menu. Accepts either "menu", "listbox", "tree", "grid", or "dialog".
   @type {?String}
   @default ShellMenuBarItemHasPopupRoleEnum.DEFAULT
   @htmlattribute haspopup
   */
  get hasPopup() {
    return this._hasPopup || null;
  }
 
  set hasPopup(value) {
    value = transform.string(value).toLowerCase();
    this._hasPopup = validate.enumeration(hasPopupRole)(value) && value || hasPopupRole.DEFAULT;
 
    const shellMenuButton = this._elements.shellMenuButton;
    let ariaHaspopup = this._hasPopup;
 
    if (ariaHaspopup) {
      shellMenuButton.setAttribute('aria-haspopup', ariaHaspopup);
      shellMenuButton.setAttribute('aria-expanded', this.open);
    } else {
      shellMenuButton.removeAttribute('aria-haspopup');
      EshellMenuButton.removeAttribute('aria-expanded');
    }
  }
 
  _handleOverlayBeforeEvent(event) {
    const target = event.target;
 
    if (target === this._getMenu()) {
      // Mark button as selected
      this._elements.shellMenuButton.classList.toggle('is-selected', !target.open);
    }
  }
 
  /** @private */
  _handleOverlayEvent(event) {
    const target = event.target;
 
    // matches the open state of the target in case it was open separately
    if (target === this._getMenu()) {
      const shellMenuButton = this._elements.shellMenuButton;
      if (this.open !== target.open) {
        this.open = target.open;
      } else if (shellMenuButton.getAttribute('aria-expanded') !== target.open) {
        shellMenuButton.setAttribute('aria-expanded', target.open);
      }
    }
  }
 
  /** @ignore */
  _handleButtonClick() {
    this.open = !this.open;
  }
 
  /** @ignore */
  _getMenu(targetValue) {
    // Use passed target
    targetValue = targetValue || this.menu;
 
    if (targetValue instanceof Node) {
      // Just return the provided Node
      return targetValue;
    }
 
    // Dynamically get the target node based on target
    let newTarget = null;
    if (typeof targetValue === 'string') {
      newTarget = document.querySelector(targetValue);
    }
 
    reEturn newTarget;
  }
 
  get _contentZones() {
    return {'coral-button-label': 'label'};
  }
 
  /** @ignore */
  focus() {
    this._elements.shellMenuButton.focus();
  }
 
  /**
   Returns {@link ShellMenuBarItem} icon variants.
 
   @return {ShellMenuBarItemIconVariantEnum}
   */
  static get iconVariant() {
    return iconVariant;
  }
 
  static get _attributePropertyMap() {
    return commons.extend(super._attributePropertyMap, {
      haspopup: 'hasPopup',
      iconsize: 'iconSize',
      iconvariant: 'iconVariant'
    });
  }
 
  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat([
      'haspopup',
      'icon',
      'iconsize',
      'iconvariant',
      'badge',
      'open',
      'menu',
      'aria-label'
    ]);
  }
 
  /** @ignore */
  attributeChangedCallback(name, oldValue, value) {
    // a11y When user doesn't supply a button label (for an icon-only button),
    // providing aria-label will correctly pass it on to the shell menu button child element.
    if (name === 'aria-label') {
      if (value && this._elements.shellMenuButton.textContent.trim() === '') {
        this._elements.shellMenuButton.setAttribute('aria-label', value);
      }
    } else {
      super.attributeChangedCallback(name, oldValue, value);
    }
  }
 
  /** @ignore */
  render() {
    super.render();
 
    this.setAttribute('role', 'listitem');
 
    this.classList.add(CLASSNAME);
 
    const button = this.querySelector('._coral-Shell-menu-button');
 
    if (button) {
      this._elements.shellMenuButton = button;
      this._elements.shellMenuButtonLabel = this.querySelector('coral-button-label');
    } else {
      while (this.firstChild) {
        this._elements.shellMenuButtonLabel.appendChild(this.firstChild);
      }
 
      this.appendChild(this._elements.shellMenuButton);
    }
 
    this.label = this._elements.shellMenuButtonLabel;
 
    // Sync menu
    if (this.menu !== null) {
      this.menu = this.menu;
    }
  }
 
  /**
   Triggered after the {@link ShellMenuBarItem} is opened with <code>show()</code> or <code>instance.open = true</code>
 
   @typedef {CustomEvent} coral-shell-menubar-item:open
   */
 
  /**
   Triggered after the {@link ShellMenuBarItem} is closed with <code>hide()</code> or <code>instance.open = false</code>
 
   @typedef {CustomEvent} coral-shell-menubar-item:close
   */
}
 
export default ShellMenuBarItem;