All files / coral-component-columnview/src/scripts ColumnViewColumn.js

93.64% Statements 162/173
88.78% Branches 87/98
89.74% Functions 35/39
93.64% Lines 162/173

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 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588                                                  2x   2x   2x   2x 2x 2x                   2x 2x   2x           346x   346x   346x                         346x       346x 346x 346x   346x 346x   346x   346x                   2x         76x 4x       72x   16x     56x           1488x             14x   14x 14x   14x   14x 6x   6x 6x 6x 6x   6x 6x 6x   6x 28x 28x       6x   28x 22x           14x   14x 2x                           338x   338x 64x     274x 274x   274x   274x   274x     274x                       168x   168x 168x   168x   116x   52x   52x           168x 14x       154x 116x   116x     116x 16x     116x       154x             32x     32x       32x     32x       32x   32x                                       72x 60x     12x   12x       12x   12x   12x   12x                                   472x   472x 316x 8x         472x             472x 472x     472x 318x         318x     472x 472x   472x 160x         160x                     378x   378x     378x 113x                               387x 371x                             700x   612x 38x   574x 24x       612x               32x     32x     32x             346x   346x   346x   346x 196x     346x   346x     346x   28x 22x         346x   346x   346x       346x 346x   346x               346x 346x             840x                       16x     346x       346x 346x                           6076x 346x                 6076x                       26x                     1006x                             4560x     322x   322x 322x   322x   322x 322x 322x 322x 1404x     322x                
/**
 * 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 ColumnViewCollection from './ColumnViewCollection';
import isInteractiveTarget from './isInteractiveTarget';
import selectionMode from './selectionMode';
import {commons, transform, validate} from '../../../coral-utils';
import {Decorator} from '../../../coral-decorator';
 
const CLASSNAME = '_coral-MillerColumns-item';
 
// The number of milliseconds for which scroll events should be debounced.
const SCROLL_DEBOUNCE = 100;
 
// Height if every item to avoid using offsetHeight during calculations.
const ITEM_HEIGHT = 40;
 
// Flag to check if window load was called
let WINDOW_LOAD = false;
window.addEventListener('load', () => {
  WINDOW_LOAD = true;
});
 
/**
 @class Coral.ColumnView.Column
 @classdesc A ColumnView Column component
 @htmltag coral-columnview-column
 @extends {HTMLElement}
 @extends {BaseComponent}
 */
const ColumnViewColumn = Decorator(class extends BaseComponent(HTMLElement) {
  /** @ignore */
  constructor() {
    super();
 
    // Events
    this._delegateEvents({
      // we need to use capture as scroll events do not bubble
      'capture:scroll coral-columnview-column-content': '_onContentScroll',
      'click coral-columnview-column-content': '_onColumnContentClick',
 
      // item interaction
      'click coral-columnview-item': '_onItemClick',
      'click [coral-columnview-itemselect]': '_onItemSelectClick',
 
      // item events
      'coral-columnview-item:_activechanged coral-columnview-item': '_onItemActiveChange',
      'coral-columnview-item:_selectedchanged coral-columnview-item': '_onItemSelectedChange'
    });
 
    // Content zone
    this._elements = {
      content: this.querySelector('coral-columnview-column-content') || document.createElement('coral-columnview-column-content')
    };
 
    // default values
    this._bulkSelectionChange = false;
    this._oldSelection = [];
    this._oldActiveItem = null;
 
    // cache bound event handler functions
    this._onDebouncedScroll = this._onDebouncedScroll.bind(this);
    this._toggleItemSelection = this._toggleItemSelection.bind(this);
 
    // Init the collection mutation observer
    this.items._startHandlingItems(true);
  }
 
  /**
   The current active item.
 
   @type {HTMLElement}
   @readonly
   @default null
   */
  get activeItem() {
    return this.items._getAllActive()[0] || null;
  }
 
  /**
   The content of the column. This container is where the items should be added and is responsible for handling the
   scrolling.
 
   @type {ColumnViewColumnContent}
   @contentzone
   */
  get content() {
    return this._getContentZone(this._elements.content);
  }
 
  set content(value) {
    this._setContentZone('content', value, {
      handle: 'content',
      tagName: 'coral-columnview-column-content',
      insert: function (content) {
        content.classList.add('_coral-AssetList');
        this.appendChild(content);
      }
    });
  }
 
  /**
   The Collection Interface that allows interacting with the items that the component contains.
 
   @type {ColumnViewCollection}
   @readonly
   */
  get items() {
    // we do lazy initialization of the collection
    if (!this._items) {
      Ethis._items = new ColumnViewCollection({
        host: this,
        container: this._elements.content,
        itemTagName: 'coral-columnview-item',
        onItemAdded: this._toggleItemSelection,
        onCollectionChange: this._handleMutation
      });
    }
 
    return this._items;
  }E
 
  /**
   Returns the first selected item in the ColumnView. The value <code>null</code> is returned if no element is
   selected.
 
   @type {?HTMLElement}
   @readonly
   */
  get selectedItem() {
    return this._selectionMode !== selectionMode.NONE ? this.items._getFirstSelected() : null;
  }
 
  /**
   Returns an Array containing the set selected items inside this Column.
 
   @type {Array.<HTMLElement>}
   @readonly
   */
  get selectedItems() {
    return this._selectionMode !== selectionMode.NONE ? this.items._getAllSelected() : [];
  }
 
  /**
   Private property that indicates the selection mode. If the <code>Coral.ColumnView.Column</code> is not inside
   a <code>Coral.ColumnView</code> this value will be <code>undefined</code>.
   See {@link ColumnViewSelectionModeEnum}.
 
   @type {String}
   @htmlattribute _selectionmode
   @htmlattributereflected
   @private
   */
  get _selectionMode() {
    return this.__selectionMode;
  }
 
  set _selectionMode(value) {
    value = transform.string(value).toLowerCase();
    value = validate.enumeration(selectionMode)(value) && value || null;
 
    this._reflectAttribute('_selectionmode', value);
    
    if(validate.valueMustChange(this.__selectionMode, value)) {
      this.__selectionMode = value;
      let items = this.items.getAll();
      items.forEach(item => this._toggleItemSelection(item));
      this._setStateFromDOM();
    }
  }
 
  /**
   Returns an Array containing the last selected items inside this Column in selected order.
 
   @type {Array.<HTMLElement>}
   @private
   */
  get _lastSelectedItems() {
    return this.__lastSelectedItems || this.selectedItems;
  }
 
  set _lastSelectedItems(value) {
    this.__lastSelectedItems = value;
  }
 
  /** @private */
  _onItemClick(event) {
    if (isInteractiveTarget(event.target)) {
      return;
    }
 
    // since transform will kill the modification, we trigger the event manually
    if (event.matchedTarget.hasAttribute('active')) {
      // directly calls the event since setting the attribute will not trigger an event
      this._onItemActiveChange(event);
    } else {
      // sets the item as active. while handling mouse interaction, items are not toggled
      event.matchedTarget.active = true;
    }
  }
I
  _toggleItemSelection(item) {
    item[this._selectionMode !== selectionMode.NONE ? 'setAttribute' : 'removeAttribute']('_selectable', '');
  }
 
  /** @private */
  _onItemSelectClick(event) {
    if (this._selectionMode && this._selectionMode !== selectionMode.NONE) {
      // stops propagation so that active is not called as well
      event.stopPropagation();
 
      const item = event.matchedTarget.parentElement;
 
      // toggles the selection of the item
      const isSelected = item.hasAttribute('selected');
 
      // Handle multi-selection with shiftKey
      if (!isSelected && event.shiftKey && this._selectionMode === selectionMode.MULTIPLE) {
        const lastSelectedItem = this._lastSelectedItems[this._lastSelectedItems.length - 1];
 
        if (lastSelectedItem) {
          const items = this.items.getAll();
          const lastSelectedItemIndex = items.indexOf(lastSelectedItem);
          const selectedItemIndex = items.indexOf(item);
 
          // true : selection goes up, false : selection goes down
          const direction = selectedItemIndex < lastSelectedItemIndex;
          const selectionRange = [];
          let selectionIndex = lastSelectedItemIndex;
 
          // Retrieve all items in the range
          while (selectedItemIndex !== selectionIndex) {
            selectionIndex = direction ? selectionIndex - 1 : selectionIndex + 1;
            selectionRange.push(items[selectionIndex]);
          }
I
          // Select all items in the range silently
          selectionRange.forEach((rangeItem) => {
            // Except for item which is needed to trigger the selection change event
            if (rangeItem !== item) {
              rangeItem.set('selected', true, true);
            }
          });
        }
      }
 
      item[isSelected ? 'removeAttribute' : 'setAttribute']('selected', '');
 
      // if item was selected, make it active
      if (isSelected && !this._lastSelectedItems.length) {
        item.setAttribute('active', '');
      }
    }
  }
 
  /**
   Handles the item activation, this causes the current item to get active and sets the next column to the item's
   src.
 
   @private
   */
  _onItemActiveChange(event) {
    // we stop propagation since it is a private event
    event.stopImmediatePropagation();
 
    // ignores event handling due to bulk select operation
    if (this._bulkSelectionChange) {
      return;
    }
 
    const item = event.matchedTarget;
 
    this._bulkSelectionChange = true;
    // clears the selection and keeps the item active. this force only 1 item to be active per column
    thIis.items._deselectAndDeactivateAllExcept(item);
    this._bulkSelectionChange = false;
 
    // we check if the selection requires an event to be triggered
    this._validateColumnChange(item);
 
    // loads data using the item as the activator and 0 as the start since it is a new column
    this._loadItems(0, item);
  }
 
  /**
   Handles selecting multiple items in the same column. Selection could result in none, a single or multiple selected
   items.
 
   @private
   */
  _onItemSelectedChange(event) {
    // we stop propagation since it is a private event
    event.stopImmediatePropagation();

    // item that was selected
    const item = event.target;
    const isSelected = item.selected;
 
    if (isSelected) {
      // Remember the last selected item
      this._lastSelectedItems.push(item);
    } else {
      const removedItemIndex = this._lastSelectedItems.indexOf(item);
      if (removedItemIndex !== -1) {
        this._lastSelectedItems = this._lastSelectedItems.splice(removedItemIndex, 1);
      }
    }
 
    // ignores event handling due to bulk select operation
    if (this._bulkSelectionChange) {
      return;
    }
 
    // when the item is selected, we need to enforce the selection mode
    if (isSelected) {
      this._bulkSelectionChange = true;
      // when there is selection, no item can be active
      this.items._deactivateAll();
 
      // enforces the selection mode
      if (this._selectionMode === selectionMode.SINGLE) {
        this.items._deselectAllExcept(item);
      }
      this._bulkSelectionChange = false;
    }
 
    // we make sure the change event is triggered before the load event.
    this._validateColumnChange();
  }
 
  /** @ignore */
  _tryToLoadAdditionalItems() {
    // makes sure that not too many events are triggered (only one per frame)
    if (this._bulkCollectionChange) {
      return;
    }
 
    this._bulkCollectionChange = true;
 
    // we use setTimeout instead of nextFrame because macrotasks allow for more flexibility since they are less
    // aggressive in executing the code
    window.setTimeout(() => {
      // trigger 'coral-columnview:loaditems' asynchronously in order to be sure the application is done
      // adding/removing elements. Also make sure that only one event is triggered at once
 
      // bulkCollectionChange has to be reset before loading new items
      this._bulkCollectionChange = false;
      this._loadFittingAdditionalItems();
    }, 0);
  }
 
  /** @private */
  _onContentScroll() {
    window.clearTimeout(this._scrollTimeout);
    this._scrollTimeout = window.setTimeout(this._onDebouncedScroll, SCROLL_DEBOUNCE);
  }
 
  /**
   Handles the column click. When the column body is clicked, we need to deselect everything up to that column.
 
   @private
   */
  _onColumnContentClick(event) {
    // we make sure the content was clicked directly and not an item
    if (event.target !== event.matchedTarget || isInteractiveTarget(event.target)) {
      return;
    }
 
    event.preventDefault();
 
    // ignores event handling due to bulk select operation
    if (this._bulkSelectionChange) {
      return false;
    }
 
    this._bulkSelectionChange = true;
    // clears the current column
    this.items._deselectAndDeactivateAllExcept();
    this._bulkSelectionChange = false;
 
    // we check if the selection requires an event to be triggered
    this._validateColumnChange();
  }
 
  /** @private */
  _onDebouncedScroll() {
    const threshold = 20;
    if (this.content.scrollTop + this.offsetHeight >= this.content.scrollHeight - threshold) {
      this._loadItems(this.items.length, undefined);
    }
  }
 
  /** @private */
  _arraysAreDifferent(selection, oldSelection) {
    let diff = [];
 
    if (oldSelection.length === selection.length) {
      diff = oldSelection.filter((item) => selection.indexOf(item) === -1);
    }
 
    // since we guarantee that they are arrays, we can start by comparing their size
    return oldSelection.length !== selection.length || diff.length !== 0;
  }
 
  /** @private */
  _validateColumnChange(item) {
    const newActiveItem = this.activeItem;
    const oldActiveItem = this._oldActiveItem || null;
 
    // we have to force the event in case the same active item was clicked again, but still try to avoid triggering as
    // less events as possible
    if (newActiveItem !== oldActiveItem || item === newActiveItem) {
      this.trigger('coral-columnview-column:_activeitemchanged', {
        activeItem: newActiveItem,
        oldActiveItem: oldActiveItem
      });
 
      // we cache the active item for the next time
      this._oldActiveItem = newActiveItem;
    }
 
    const newSelection = this.selectedItems;
    const oldSelection = this._oldSelection;
 
    if (this._arraysAreDifferent(newSelection, oldSelection)) {
      this.trigger('coral-columnview-column:_selecteditemchanged', {
        selection: newSelection,
        oldSelection: oldSelection
      });
 
      // changes the old selection array since we selected something new
      this._oldSelection = newSelection;
    }
  }
 
  /**
   Loads additional Items if the current items of the column to not exceed its height and a path this.next is given.
 
   @private
   */
  _loadFittingAdditionalItems() {
    const itemsCount = this.items.length;
    // this value must match $columnview-item-height
    const itemsHeight = itemsCount * ITEM_HEIGHT;
 
    // we request more items if there is still space for them. in case the values are the same, we request more data
    // just to be sure, specially when the value is 0
    if (itemsHeight <= this.offsetHeight) {
      this._loadItems(itemsCount, undefined);
    }
  }
 
  /**
   Loads additional items. If the given item is not <code>active</code>, no data will be requested.
I
   @param {Number} count
   Amount of items in the column.
   @param {?HTMLElement} item
   Item that triggered the load.
 
   @private
   */
  _loadItems(count, item) {
    // if the given item is not active, it should not request data
    if (!item || item.hasAttribute('active')) {
      this.trigger('coral-columnview-column:_loaditems', {
        start: count,
        item: item
      });
    }
  }
 
  /**
   Updates the active and selected options from the DOM.
 
   @ignore
   */
  _setStateFromDOM() {
    // if the selection mode has not been set, we do no try to force selection
    if (this._selectionMode) {
      // single: only the last item is selected
      if (this._selectionMode === selectionMode.SINGLE) {
        this.items._deselectAllExceptLast();
      }
      // none: deselects everything
      else if (this._selectionMode === selectionMode.NONE) {
        this.items._deselectAllExcept();
      }
 
      // makes sure only one item is active
      this.items._deactivateAllExceptFirst();
    }
  }
 
  /** @private */
  _handleMutation() {
    this._setStateFromDOM();
 
    // in case items were added removed and selection changed
    this._validateColumnChange();
 
    // checks if more items can be added after the childlist change
    this._tryToLoadAdditionalItems();
  }
 
  get _contentZones() {
    return {'coral-columnview-column-content': 'content'};
  }
 
  static get _attributePropertyMap() {
    return commons.extend(super._attributePropertyMap, {
      _selectionmode: '_selectionMode'
    });
  }
 
  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat([
      '_selectionmode'
    ]);
  }
 
  /** @ignore */
  render() {
    super.render();
 
    this.classList.add(CLASSNAME);
    // @a11y
    if (!this.hasAttribute('role')) {
      this.setAttribute('role', 'group');
    }
 
    this.id = this.id || commons.getUID();
 
    // @todo: initial collection items needs to be triggered
 
    const content = this._elements.content;
 
    // when the content zone was not created, we need to make sure that everything is added inside it as a content.
    // this stops the content zone from being voracious
    if (!content.parentNode) {
      // move the contents of the item into the content zone
      while (this.firstChild) {
        content.appendChild(this.firstChild);
      }
    }
 
    // @a11y
    content.setAttribute('role', 'presentation');
 
    // Call content zone insert
    this.content = content;
 
    // handles the initial selection
    this._setStateFromDOM();
 
    // we keep a list of the last selection to determine if something changed. we need to do this after
    // validateSelection since it modifies the initial state based on the option
    this._oldSelection = this.selectedItems;
    this._oldActiveItem = this.activeItem;
 
    if (!WINDOW_LOAD) {
      E// instead of being super aggressive on requesting data, we use window onload so it is scheduled after
      // all the code has been executed, this way events can be added before
      window.addEventListener('load', () => {
        this._loadFittingAdditionalItems();
      });
    } else {
      // macro-task is necessary for the same reasons as listed above
      window.setTimeout(() => {
        this._loadFittingAdditionalItems();
      });
    }
  }
});
 
export default ColumnViewColumn;