All files / coral-component-tree/src/scripts TreeItem.js

87.74% Statements 136/155
80.46% Branches 70/87
96.3% Functions 26/27
87.74% Lines 136/155

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 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485                                                2x                       2x             2x   2x 4x     2x                 2x 2x   2x           676x   676x   676x       676x         676x 676x       676x   676x                 2x               254x             104x 104x 104x   104x 12x               2x   2x                       2x   2x                       670x   670x 670x 670x 670x 670x   670x 670x 670x 670x 670x 670x   670x                                         670x 518x     670x   670x 670x 670x   670x 150x   150x 30x         670x 670x   670x   670x 732x   732x   72x   72x 660x   360x     300x       670x 24x       670x                                                         16x                     16x     670x       670x                           1776x 676x                       1776x                         2372x     724x   724x 724x 724x   724x   724x 724x 724x 724x   724x 156x 156x 568x 6x 6x     724x 46x   678x     724x         724x   724x   724x   54x 54x 28x   26x       54x 40x       54x 24x   30x           54x 54x     670x   670x 640x 640x                               1408x         674x 674x   674x   674x                         1434x     104x   104x   104x   104x   104x 104x   104x       104x                         74x     12x   12x   12x   12x   12x                      
/**
 * 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 {Collection} from '../../../coral-collection';
import {Icon} from '../../../coral-component-icon';
import treeItem from '../templates/treeItem';
import {transform, commons, i18n, validate} from '../../../coral-utils';
import {Decorator} from '../../../coral-decorator';
 
const CLASSNAME = '_coral-TreeView-item';
 
/**
 Enumeration for {@link TreeItem} variants.
 
 @typedef {Object} TreeItemVariantEnum
 
 @property {String} DRILLDOWN
 Default variant with icon to expand/collapse subtree.
 @property {String} LEAF
 Variant for leaf items. Icon to expand/collapse subtree is hidden.
 */
const variant = {
  /* Default variant with icon to expand/collapse subtree. */
  DRILLDOWN: 'drilldown',
  /* Variant for leaf items. Icon to expand/collapse subtree is hidden. */
  LEAF: 'leaf'
};
 
const ALL_VARIANT_CLASSES = [];
 
for (const variantValue in variant) {
  ALL_VARIANT_CLASSES.push(`${CLASSNAME}--${variant[variantValue]}`);
}
 
const IS_TOUCH_DEVICE = 'ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0;
 
/**
 @class Coral.Tree.Item
 @classdesc A Tree item component
 @htmltag coral-tree-item
 @extends {HTMLElement}
 @extends {BaseComponent}
 */
const TreeItem = Decorator(class extends BaseComponent(HTMLElement) {
  /** @ignore */
  constructor() {
    super();
 
    // Prepare templates
    this._elements = {
      // Create or fetch the content zones
      content: this.querySelector('coral-tree-item-content') || document.createElement('coral-tree-item-content')
    };
    treeItem.call(this._elements, {Icon, commons});
 
    if (!this._elements.icon) {
      this._elements.icon = this._elements.header.querySelector('._coral-TreeView-indicator');
    }
 
    // Tells the collection to automatically detect the items and handle the events
    this.items._startHandlingItems();
  }
 
  /**
   The parent tree. Returns <code>null</code> if item is the root.
 
   @type {HTMLElement}
   @readonly
   */
  get parent() {
    Ereturn this._parent || null;
  }
 
  /**
   The content of this tree item.
 
   @type {TreeItemContent}
   @contentzone
   */
  get content() {
    return this._getContentZone(this._elements.content);
  }
 
  set content(value) {
    this._setContentZone('content', value, {
      handle: 'content',
      tagName: 'coral-tree-item-content',
      insert: function (content) {
        this._elements.header.appendChild(content);
      }
    });
  }
 
  /**
   The Collection Interface that allows interacting with the items that the component contains.
 
   @type {Collection}
   @readonly
   */
  get items() {
    // Construct the collection on first request
    if (!this._items) {
      this._items = new Collection({
        host: this,
        itemTagName: 'coral-tree-item',
        itemSelector: ':scope > coral-tree-item',
        onlyHandleChildren: true,
        container: this._elements.subTreeContainer,
        filter: this._filterItem.bind(this),
        onItemAdded: this._onItemAdded,
        onItemRemoved: this._onItemRemoved
      });
    }
 
    return this._items;
  }
I
  /**
   Whether the item is expanded. Expanded cannot be set to <code>true</code> if the item is disabled.
 
   @type {Boolean}
   @default false
   @htmlattribute expanded
   @htmlattributereflected
   */
  get expanded() {
    return this._expanded || false;
  }
 
  set expanded(value) {
    value = transform.booleanAttr(value);
    const triggerEvent = this.expanded !== value;
 
    this._expanded = value;
    this._reflectAttribute('expanded', this._expanded);
 
    const header = this._elements.header;
    const subTreeContainer = this._elements.subTreeContainer;
 
    this.classList.toggle('is-open', this._expanded);
    this.classList.toggle('is-collapsed', !this._expanded);
 
    if (this.variant !== variant.DRILLDOWN) {
      header.removeAttribute('aria-expanded');
      header.removeAttribute('aria-owns');
    } else if (this.items.length > 0) {
      header.setAttribute('aria-expanded', this._expanded);
      header.setAttribute('aria-owns', subTreeContainer.id);
    }
 
    if (this._expanded) {
      subTreeContainer.removeAttribute('aria-hidden');
    } else {
      subTreeContainer.setAttribute('aria-hidden', !this._expanded);
    }
 
    if (IS_TOUCH_DEVICE) {
      Iconst icon = header.querySelector('._coral-TreeView-indicator');
      icon.setAttribute('aria-label', i18n.get(this._expanded ? 'Collapse' : 'Expand'));
    }

    this.trigger('coral-tree-item:_expandedchanged');
 
    // Do animation in next frame to avoid a forced reflow
    window.requestAnimationFrame(() => {
      // Don't animate on initialization
      if (this._animate) {
        // Remove height as we want the drawer to naturally grow if content is added later
        commons.transitionEnd(subTreeContainer, () => {
          if (this.expanded) {
            subTreeContainer.style.height = '';
          } else {
            subTreeContainer.hidden = true;
          }

          // Trigger once the animation is over to inform coral-tree
          if (triggerEvent) {
            this.trigger('coral-tree-item:_afterexpandedchanged');
          }
        });
 
        // Force height to enable transition
        if (!this.expanded) {
          subTreeContainer.style.height = `${subTreeContainer.scrollHeight}px`;
        } else {
          subTreeContainer.hidden = false;
        }
 
        // We read the offset height to force a reflow, this is needed to start the transition between absolute values
        // https://blog.alexmaccaw.com/css-transitions under Redrawing
        // eslint-disable-next-line no-unused-vars
        const offsetHeight = subTreeContainer.offsetHeight;
 
        subTreeContainer.style.height = this.expanded ? `${subTreeContainer.scrollHeight}px` : 0;
      } else {
        // Make sure it's animated next time
        this._animate = true;
 
        // Hide it on initialization if closed
        if (!this.expanded) {
          subTreeContainer.style.height = 0;
          subTreeContainer.hidden = true;
        }
      }
    });
  }
 
  /**
   The item's variant. See {@link TreeItemVariantEnum}.
 
   @type {String}
   @default TreeItemVariant.DRILLDOWN
   @htmlattribute variant
   @htmlattributereflected
   */
  get variant() {
    return this._variant || variant.DRILLDOWN;
  }
 
  set variant(value) {
    value = transform.string(value).toLowerCase();
    this._variant = validate.enumeration(variant, value) && value || variant.DRILLDOWN;
 
    // removes every existing variant
    this.classList.remove(...ALL_VARIANT_CLASSES);
    this.classList.add(`${CLASSNAME}--${this._variant}`);
  }
 
  /**
   Whether the item is selected.
 
   @type {Boolean}
   @default false
   @htmlattribute selected
   @htmlattributereflected
   */
  get selected() {
    return this._selected || false;
  }
 
  set selected(value) {
    this._selected = transform.booleanAttr(value);
    this._reflectAttribute('selected', this._selected);
 
    this._elements.header.classList.toggle('is-selected', this._selected);
    this._elements.header.setAttribute('aria-selected', this._selected);
 
    const selectedState = this._elements.selectedState;
    selectedState.textContent = i18n.get(this._selected ? 'selected' : 'not selected');
 
    if (IS_TOUCH_DEVICE) {
      selectedState.setAttribute('aria-pressed', this._selected);
    }
 
    this.trigger('coral-tree-item:_selectedchanged');
  }
 
  /**
   Whether this item is disabled.
 
   @type {Boolean}
   @default false
   @htmlattribute disabled
   @htmlattributereflected
   */
  get disabled() {
    return this._disabled || false;
  }
 
  set disabled(value) {
    this._disabled = transform.booleanAttr(value);
    this._reflectAttribute('disabled', this._disabled);
 
    this._elements.header.classList.toggle('is-disabled', this._disabled);
    this._elements.header[this._disabled ? 'setAttribute' : 'removeAttribute']('aria-disabled', this._disabled);
 
    this.trigger('coral-tree-item:_disabledchanged');
  }
 
  /**
   @ignore
   */
  get hidden() {
    return this.hasAttribute('hidden');
  }
 
  set hidden(value) {
    this._reflectAttribute('hidden', transform.booleanAttr(value));
 
    // We redefine hidden to trigger an event
    this.trigger('coral-tree-item:_hiddenchanged');
  }
 
  /** @private */
  _filterItem(item) {
    // Handle nesting check for parent tree item
    // Use parentNode for added items
    // Use _parent for removed items
    return item.parentNode && item.parentNode.parentNode === this || item._parent === this;
  }
 
  /** @private */
  _onItemAdded(item) {
    item._parent = this;
 
    const header = this._elements.header;
    const subTreeContainer = this._elements.subTreeContainer;
    if (!header.hasAttribute('aria-owns')) {
      header.setAttribute('aria-owns', subTreeContainer.id);
    }
  }
 
  /** @private */
  _onItemRemoved(item) {
    item._parent = undefined;
 
    // If there are no items the subTreeContainer
    if (!this.items.length) {
      this._elements.header.removeAttribute('aria-owns');
    }
  }
 
  /**
   Handles the focus of the item.
 
   @ignore
   */
  focus() {
    this._elements.header.setAttribute('tabindex', '0');
    this._elements.header.focus();
  }
 
  /**
   Returns {@link TreeItem} variants.
 
   @return {TreeItemVariantEnum}
   */
  static get variant() {
    return variant;
  }
 
  get I_contentZones() {
    return {'coral-tree-item-content': 'content'};
  }
 
  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat(['selected', 'disabled', 'variant', 'expanded', 'hidden']);
  }
 
  /** @ignore */
  render() {
    super.render();
 
    this.classList.add(CLASSNAME);
 
    const header = this._elements.header;
    const subTreeContainer = this._elements.subTreeContainer;
    const content = this._elements.content;
    const selectedState = this._elements.selectedState;
 
    // a11ys
    content.id = content.id || commons.getUID();
    this.setAttribute('role', 'presentation');
    header.setAttribute('aria-labelledby', `${content.id} ${selectedState.id}`);
    header.setAttribute('aria-selected', this.selected);
    subTreeContainer.setAttribute('aria-labelledby', content.id);
    selectedState.textContent = i18n.get(this.selected ? 'selected' : 'not selected');
 
    if (IS_TOUCH_DEVICE) {
      const icon = this._elements.icon || header.querySelector('._coral-TreeView-indicator');
      if (icon && !icon.id) {
        icon.id = commons.getUID();
      }
      icon.setAttribute('role', 'button');
      icon.setAttribute('tabindex', '-1');
      icon.setAttribute('aria-labelledby', icon.id + ' ' + content.id);
      icon.setAttribute('aria-label', i18n.get(this.expanded ? 'Collapse' : 'Expand'));
      icon.setAttribute('style', 'outline: none !important');
      icon.removeAttribute('aria-hidden');
 
      selectedState.setAttribute('role', 'button');
      selectedState.setAttribute('tabindex', '-1');
      selectedState.setAttribute('aria-labelledby', content.id + ' ' + selectedState.id);
      selectedState.setAttribute('aria-pressed', this.selected);
      selectedState.setAttribute('style', 'outline: none !important');
    }
 
    // Default reflected attributes
    if (!this._variant) {
      this.variant = variant.DRILLDOWN;
    }
    this.expanded = this.expanded;
 
    // Render the template and set element references
    const frag = document.createDocumentFragment();
 
    const templateHandleNames = ['header', 'icon', 'subTreeContainer'];
 
    const subTree = this.querySelector('._coral-TreeView');
    if (subTree) {
      const items = subTree.querySelectorAll('coral-tree-item');
      for (let i = 0 ; i < items.length ; i++) {
        subTreeContainer.appendChild(items[i]);
      }
    }
 
    // Add templates into the frag
    frag.appendChild(header);
    frag.appendChild(subTreeContainer);
 
    // Assign the content zones, moving them into place in the process
    this.content = content;
 
    // Move any remaining elements into the content sub-component
    while (this.firstChild) {
      const child = this.firstChild;
      if (child.nodeName === 'CORAL-TREE-ITEM') {
        // Adding parent attribute to access the parent directly
        child._parent = this;
        // Add tree items to the sub tree container
        subTreeContainer.appendChild(child);
      } else if (child.nodeType === Node.TEXT_NODE ||
        child.nodeType === Node.ELEMENT_NODE && templateHandleNames.indexOf(child.getAttribute('handle')) === -1) {
        // Add non-template elements to the content
        content.appendChild(child);
      } else {
        // Remove anything else element
        this.removeChild(child);
      }
    }
 
    if (this.variant === variant.DRILLDOWN && this.items.length && !header.hasAttribute('aria-owns')) {
      header.setAttribute('aria-owns', subTreeContainer.id);
    }
I
    // Lastly, add the fragment into the container
    this.appendChild(frag);
  }
 
  /**
   Triggered when {@link TreeItem#selected} changed.
 
   @typedef {CustomEvent} coral-tree-item:_selectedchanged
 
   @private
   */
 
  /**
   Triggered when {@link TreeItem#expanded} changed.
 
   @typedef {CustomEvent} coral-tree-item:_expandedchanged
 
   @private
   */
 
  /**
   Triggered when {@link TreeItem#hidden} changed.
 
   @typedef {CustomEvent} coral-tree-item:_hiddenchanged
 
   @private
   */
 
  /**
   Triggered when {@link TreeItem#disabled} changed.
 
   @typedef {CustomEvent} coral-tree-item:_disabledchanged
 
   @private
   */
});

export default TreeItem;