All files / coral-component-sidenav/src/scripts SideNav.js

93.08% Statements 121/130
92.39% Branches 85/92
87.5% Functions 21/24
93.08% Lines 121/130

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                                              2x   2x 1714x     2x 1370x     2x 734x                           2x                         2x 2x   2x           68x   68x   68x                     68x   68x   68x   68x     68x   68x         68x                 2x                                                   26x   26x         176x   176x     176x   176x 6x 12x   6x 6x       6x       176x     176x         176x   176x 52x   52x 24x 24x   24x 24x     24x       52x   52x                 176x 176x   176x 34x       34x           1014x 310x 2x 2x 308x 4x 4x   4x   704x 46x   46x 44x 44x   44x 28x 28x     658x 54x   54x 6x 6x   6x 2x 2x               16x 16x         72x   72x   974x 664x   664x     664x 4x     664x 6x         974x 310x   310x   310x 2x                             68x   68x   68x 46x       68x 36x       68x 12x       68x   68x   68x 68x                             798x 68x                 798x                       454x                
/**
 * 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 {SelectableCollection} from '../../../coral-collection';
import {transform, validate, commons} from '../../../coral-utils';
import {Decorator} from '../../../coral-decorator';
 
const CLASSNAME = '_coral-SideNav';
 
const isLevel = node => node.nodeName === 'CORAL-SIDENAV-LEVEL';
const isHeading = node => node.nodeName === 'CORAL-SIDENAV-HEADING';
const isItem = node => node.nodeName === 'A' && node.getAttribute('is') === 'coral-sidenav-item';
 
/**
 Enumeration for {@link SideNav} variants.
 
 @typedef {Object} SideNavVariantEnum
 
 @property {String} DEFAULT
 A default sidenav.
 @property {String} MULTI_LEVEL
 A sidenav with multiple levels of indentation.
 */
const variant = {
  DEFAULT: 'default',
  MULTI_LEVEL: 'multilevel',
};
 
/**
 @class Coral.SideNav
 @classdesc A Side Navigation component to navigate the entire content of a product or a section.
 These can be used for a single level or a multi-level navigation.
 @htmltag coral-sidenav
 @extends {HTMLElement}
 @extends {BaseComponent}
 */
const SideNav = Decorator(class extends BaseComponent(HTMLElement) {
  /** @ignore */
  constructor() {
    super();
 
    // Attach events
    this._delegateEvents({
      // Interaction
      'click a[is="coral-sidenav-item"]': '_onItemClick',
 
      // Accessibility
      'capture:focus a[is="coral-sidenav-item"].focus-ring': '_onItemFocusIn',
      'capture:blur a[is="coral-sidenav-item"]': '_onItemFocusOut',
 
      // Private
      'coral-sidenav-item:_selectedchanged': '_onItemSelectedChanged'
    });
 
    // Used for eventing
    this._oldSelection = null;
 
    // Level Collection
    this._levels = this.getElementsByTagName('coral-sidenav-level');
 
    // Heading Collection
    this._headings = this.getElementsByTagName('coral-sidenav-heading');
 
    // Init the collection mutation observer
    this.items._startHandlingItems(true);
 
    // Initialize content MO
    this._observer = new MutationObserver(this._handleMutations.bind(this));
    this._observer.observe(this, {
      childList: true,
      subtree: true
    });
  }
 
  /**
   The Collection Interface that allows interacting with the items that the component contains.
 
   @type {Collection}
   @readonly
   */
  get items() {
    // just init on demand
    if (!this._items) {
      this._items = new SelectableCollection({
        host: this,
        itemTagName: 'coral-sidenav-item',
        itemBaseTagName: 'a',
        onItemAdded: this._validateSelection,
        onItemRemoved: this._validateSelection
      });
    }
    return this._items;
  }
 
  /**
   Returns the first selected item in the sidenav. The value <code>null</code> is returned if no element is
   selected.
 
   @type {SideNavItem}
   @readonly
   */
  get selectedItem() {
    return this.items._getFirstSelected();
  }
 
  /**
   The sidenav's variant. See {@link SideNavVariantEnum}.
 
   @type {String}
   @default SideNavVariantEnum.DEFAULT
   @htmlattribute variant
   @htmlattributereflected
   */
  get variant() {
    return this._variant || variant.DEFAULT;
  }
 
  set variant(value) {
    value = transform.string(value).toLowerCase();
    this._variant = validate.enumeration(variant)(value) && value || variant.DEFAULT;
    this._reflectAttribute('variant', this._variant);

    this.classList.toggle(`${CLASSNAME}--multiLevel`, this._variant === variant.MULTI_LEVEL);
 
    if (this.variant === variant.MULTI_LEVEL) {
      // Don't hide the selected item level
      const selectedItem = this.selectedItem;
      const ignoreLevel = selectedItem && selectedItem.parentNode;
 
      // Hide every other level that doesn't contain the selected item
      for (let i = 0 ; i < this._levels.length ; i++) {
        if (this._levels[i] !== ignoreLevel) {
          this._levels[i].setAttribute('_expanded', 'off');
        }
      }
    }
  }
 
  _onItemClick(event) {
    const item = event.matchedTarget;
 
    if (!item.selected) {
      item.selected = true;
    }
  }
 
  _onItemFocusIn(event) {
    const item = event.matchedTarget;
 
    item._elements.container.classList.add('focus-ring');
  }
 
  _onItemFocusOut(event) {
    const item = event.matchedTarget;
 
    item._elements.container.classList.remove('focus-ring');
  }
 
  _onItemSelectedChanged(event) {
    event.stopImmediatePropagation();
 
    this._validateSelection(event.target);
  }
 
  _validateSelection(item) {
    const selectedItems = this.items._getAllSelected();
    // Last selected item wins if multiple selection while not allowed
    item = item || selectedItems[selectedItems.length - 1];
 
    // Deselect other selected items
    if (itEem && item.hasAttribute('selected') && selectedItems.length > 1) {
      selectedItems.forEach((selectedItem) => {
        if (selectedItem !== item) {
          // Don't trigger change events
          this._preventTriggeringEvents = true;
          selectedItem.removeAttribute('selected');
        }
      });
 
      // We can trigger change events again
      thIis._preventTriggeringEvents = false;
    }

    // Expand multi level
    this._expandLevels();
 
    // Notify of change
    this._triggerChangeEvent();
  }
 
  _expandLevels() {
    const selectedItem = this.selectedItem;
    if (selectedItem) {
      let level = selectedItem.closest('coral-sidenav-level');
 
      // Expand until root
      while (level) {
        level.setAttribute('_expanded', 'on');
 
        const prev = level.previousElementSibling;
        if (prev && prev.matches('a[is="coral-sidenav-item"]')) {
          prev.setAttribute('aria-expanded', 'true');
        }
 
        level = level.parentNode && level.parentNode.closest('coral-sidenav-level');
      }
 
      // Expand corresponding item level
      level = selectedItem.nextElementSibling;
      if (level && level.tagName === 'CORAL-SIDENAV-LEVEL') {
        level.setAttribute('_expanded', 'on');
        selectedItem.setAttribute('aria-expanded', 'true');
      }
    }
  }
 
  _triggerChangeEvent() {
    const selectedItem = this.selectedItem;
    const oldSelection = this._oldSelection;
 
    if (!this._preventTriggeringEvents && selectedItem !== oldSelection) {
      this.trigger('coral-sidenav:change', {
        oldSelection: oldSelection,
        selection: selectedItem
      });
 
      this._oldSelection = selectedItem;
    }
  }
 
  _syncLevel(el, isRemoved) {
    if (isRemoved) {
      if (el.id && isLevel(el)) {
        const item = this.querySelector(`a[is="coral-sidenav-item"][aria-controls="${el.id}"]`);
        item && item.removeAttribute('aria-controls');
      } else if (el.id && (isHeading(el) || isItem(el))) {
        const level = this.querySelector(`coral-sidenav-level[aria-labelledby="${el.id}"]`);
        level && level.removeAttribute('aria-labelledby');
        this._syncLevel(level);
      }
    } else if (isLevel(el)) {
      const prev = el.previousElementSibling;
      if (prev && (isHeading(prev) || isItem(prev))) {
        prev.id = prev.id || commons.getUID();
        el.setAttribute('aria-labelledby', prev.id);
 
        if (isItem(prev)) {
          el.id = el.id || commons.getUID();
          prev.setAttribute('aria-controls', el.id);
        }
      }
    } else if (isHeading(el) || isItem(el)) {
      const next = el.nextElementSibling;
      if (next && isLevel(next)) {
        el.id = el.id || commons.getUID();
        next.setAttribute('aria-labelledby', el.id);
 
        if (isItem(el)) {
          next.id = next.id || commons.getUID();
          el.setAttribute('aria-controls', next.id);
        }
      }
    }
  }
 
  _syncHeading(heading) {
    heading.classList.add(`${CLASSNAME}-heading`);
    heading.setAttribute('role', 'heading');
  }
 
  _handleMutations(mutations) {
    mutations.forEach((mutation) => {
      // Sync added levels and headings
      for (let i = 0 ; i < mutation.addedNodes.length ; i++) {
        const addedNode = mutation.addedNodes[i];
 
        // a11y
        this._syncLevel(addedNode);
 
        // a11y
        if (isHeading(addedNode)) {
          this._syncHeading(addedNode);
        }
 
        if (isLevel(addedNode)) {
          this._validateSelection(addedNode.querySelector('a[is="coral-sidenav-item"][selected]'));
        }
      }
 
      // Sync removed levels
      for (let k = 0 ; k < mutation.removedNodes.length ; k++) {
        const removedNode = mutation.removedNodes[k];
 
        this._syncLevel(removedNode, true);
 
        if (isLevel(removedNode)) {
          this._validateSelection();
        }
      }
    });
  }
 
  /**
   Returns {@link SideNav} variants.
 
   @return {SideNavVariantEnum}
   */
  static get variant() {
    return variant;
  }
 
  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat(['variant']);
  }
 
  /** @ignore */
  render() {
    super.render();
 
    this.classList.add(CLASSNAME);
 
    // Default reflected attributes
    if (!this._variant) {
      this.variant = variant.DEFAULT;
    }
 
    // a11y
    for (let i = 0 ; i < this._levels.length ; i++) {
      this._syncLevel(this._levels[i]);
    }
 
    // a11y
    for (let i = 0 ; i < this._headings.length ; i++) {
      this._syncHeading(this._headings[i]);
    }
 
    // Don't trigger events once connected
    this._preventTriggeringEvents = true;
    this._validateSelection();
    this._preventTriggeringEvents = false;
 
    this._oldSelection = this.selectedItem;
  }
 
  /**
   Triggered when {@link SideNav} selected item has changed.
 
   @typedef {CustomEvent} coral-sidenav:change
 
   @property {SideNavItem} detail.oldSelection
   The prior selected item.
   @property {SideNavItem} detail.selection
   The newly selected item.
   */
});
 
export default SideNav;