All files / coral-component-masonry/src/scripts Masonry.js

79.17% Statements 323/408
74.21% Branches 187/252
85.9% Functions 67/78
79.17% Lines 323/408

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 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210                                                  2x     2x                           2x                                       2x                                 2x             2x 27x   27x 27x       2x 32x       2x 108x             2x                 2x       2x                         2x 2x   2x           172x   172x   172x 172x 172x 172x 172x 172x 172x   172x 172x 172x 172x 172x       172x                                           172x   172x               172x   172x   172x                 2x     76x   76x               76x   76x         76x 76x 76x   76x 20x 20x       76x 56x   56x 52x     4x 4x 4x 4x 4x 4x 4x   4x               4x     4x   4x 4x                           10x       10x   8x 8x   8x 4x 4x     8x 4x 4x     8x 4x   4x       2x     2x       2x 2x 2x         2x 2x           2x   2x               161x   161x 161x 666x               666x 18x 18x   18x 12x     648x 648x 648x               161x       161x 8x   153x           620x   620x   620x 366x   626x   626x 4x     626x   254x   128x   128x 6x 12x   6x 6x       6x       620x         620x 620x   620x 68x 32x         36x           68x           314x   314x 250x 50x         314x         22x 20x 20x 20x                                                   1280x   1280x 443x   443x 443x     443x     443x               124x     124x       124x 124x 66x   66x                     234x   110x   124x                                   654x 654x   654x 503x     151x 62x   89x                   151x   151x 217x       151x   151x           151x 217x       151x   151x   151x   151x 64x       151x   151x 21x   21x             151x   151x     151x               172x 172x 172x   172x                 172x       172x             426x 426x   426x         738x     738x         738x 406x     406x   406x 406x             16x 16x   16x             406x     406x 390x       16x       16x   14x 14x 14x 14x 14x 14x   14x       2x               406x   406x     406x 101x               16x   16x             16x   16x 16x       16x 16x               80x 16x     80x 74x     80x                                                                                                                                                                                                                                   172x   172x   172x   172x   170x       172x 100x     172x 150x       172x   172x   172x 172x   172x   172x 312x     172x 172x 172x   172x                                                   2738x 172x                     2738x                         986x     262x 262x   262x   262x   262x 166x   166x 6x     96x   96x 6x       262x                                     747x     190x 190x   190x         190x 188x 186x   186x   186x   2x                         12x                     1448x                           145x     24x 24x   24x                       408x     6x 6x   6x 12x                                             564x     10x   10x           10x   10x     10x   8x 8x 2x   2x 2x             10x   10x   10x                       20x     2x   2x     2x     2x       2x 2x                             20x     2x   2x     2x     2x       2x
/**
 * 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 MasonryItem from './MasonryItem';
import {SelectableCollection} from '../../../coral-collection';
import {validate, transform, commons, i18n} from '../../../coral-utils';
import {Decorator} from '../../../coral-decorator';
import MasonryItemAccessibilityState from "./MasonryItemAccessibilityState";
 
const CLASSNAME = '_coral-Masonry';
 
/** @ignore */
const isMacLike = /(Mac|iPhone|iPod|iPad)/i.test(window.navigator.platform);
 
/**
 Enumeration for {@link Masonry} selection options.
 
 @typedef {Object} MasonrySelectionModeEnum
 
 @property {String} NONE
 None is default, selection of Masonry items doesn't happen based on click.
 @property {String} SINGLE
 Single selection mode, Masonry behaves like radio input elements.
 @property {String} MULTIPLE
 Multiple selection mode, Masonry behaves like checkbox input elements.
 */
const selectionMode = {
  NONE: 'none',
  SINGLE: 'single',
  MULTIPLE: 'multiple'
};
 
/**
 Enumeration for {@link Masonry} layouts.
 
 @typedef {Object} MasonryLayoutsEnum
 
 @property {String} FIXED_CENTERED
 A Layout with fixed width centered items.
 @property {String} FIXED_SPREAD
 A layout with fixed width and evenly spread items.
 @property {String} VARIABLE
 A layout with variable width items.
 @property {String} DASHBOARD
 A layout with variable width items which are expanded in their height to fill gaps.
 */
const layouts = {
  FIXED_CENTERED: 'fixed-centered',
  FIXED_SPREAD: 'fixed-spread',
  VARIABLE: 'variable',
  DASHBOARD: 'dashboard'
};
 
/**
 Enumeration values to enable/disable aria grid support for {@link Masonry}.
 
 @typedef {Object} MasonryAriaGridEnum
 
 @property {String} ON
 Turn on auto aria grid roles.
 @property {String} OFF
 OFF is default. Turn off auto aria grid roles.
 */
const ariaGrid = {
  ON: 'on',
  OFF: 'off'
};
 
// IE does not set the complete property to true if an image cannot be loaded. This code must be outside of the
// masonry to make sure that the listener catches images which fail loading before the masonry is initalized.
// @polyfill ie11
document.addEventListener('error', (event) => {
  const target = event.target;
  if (target && target.tagName === 'IMG') {
    target._loadError = true;
  }
}, true);
 
// Ignore children which are being removed
coEnst itemFilter = (element) => element && element.tagName === 'CORAL-MASONRY-ITEM' && !element.hasAttribute('_removing');
 
// Filter out items being removed
const isRemovingOrRemoved = (item) => item.hasAttribute('_removing') || !item.parentNode;
 
/**
 * Returns the position of the second element relative to the first element.
 */
const relativePosition = (el1, el2) => {
  const rect1 = el1.getBoundingClientRect();
  const rect2 = el2.getBoundingClientRect();
  return {
    left: rect2.left - rect1.left,
    top: rect2.top - rect1.top
  };
};
 
const weightedDistance = (x1, y1, x2, y2, unitWidth, unitHeight) => Math.sqrt(Math.pow((x2 - x1) / unitWidth, 2) + Math.pow((y2 - y1) / unitHeight, 2));

const getPreviousItem = (item) => {
  const previousItem = item.previousElementSibling;
  return itemFilter(previousItem) ? previousItem : null;
};
 
/**
 @class Coral.Masonry
 @classdesc A Masonry component that allows to lay out items in a masonry grid.
 @htmltag coral-masonry
 @extends {HTMLElement}
 @extends {BaseComponent}
 */
const Masonry = Decorator(class extends BaseComponent(HTMLElement) {
  /** @ignore */
  constructor() {
    super();
 
    // Defaults
    this._loaded = false;
    this._layouted = false;
    this._layoutScheduled = false;
    this._forceDebounce = false;
    this._debounceId = null;
 
    this._newItems = [];
    this._tabbableItem = null;
 
    //a11y
    this._defaultAriaRole = "group";
 
    this._ariaGrid = ariaGrid.OFF;
    this._preservedAriaRole = this._defaultAriaRole;
    this._preservedParentAriaRole = null;
 
    this._elements = {
      accessibilityState: this.querySelector('coral-masonry-item-accessibilitystate') || new MasonryItemAccessibilityState()
    };
 
    this._delegateEvents({
      'global:resize': '_onWindowResize',
 
      // Loaded
      'global:load': '_updateLoaded',
      'capture:load img': '_updateLoaded',
      'capture:error img': '_updateLoaded',
 
      // Drag and drop
      'coral-dragaction:dragstart coral-masonry-item': '_onItemDragStart',
      'coral-dragaction:dragover coral-masonry-item': '_onItemDragMove',
      'coral-dragaction:dragend coral-masonry-item': '_onItemDragEnd',
 
      'coral-masonry-item:_selecteditemchanged': '_onMasonrySelectedItemChanged',
 
      // Keyboard
      'capture:focus coral-masonry-item': '_onItemFocus',
 
      // Selection
      'click coral-masonry-item': '_onItemClick',
      'key:space coral-masonry-item': '_onItemClick',
 
      // Messenger
      'coral-masonry-item:_messengerconnected': '_onMessengerConnected'
    });
 
    // Relayout when child elements change or are added/removed
    // Should this mutation observer become a bottleneck, it could be replaced with a resize listener
    this._observer = new MutationObserver(this._scheduleLayout.bind(this, 'mutation'));
    this._observer.observe(this, {
      childList: true,
      subtree: true,
      characterData: true,
      attributes: true
    });
 
    // Used for eventing
    this._oldSelection = [];
 
    // Init the collection mutation observer
    this.items._startHandlingItems(true);
  }
 
  /**
   Allows to interact with the masonry items.
 
   @type {SelectableCollection}
   @readonly
   */
  get items() {
    if (!this._items) {
      this._items = new SelectableCollection({
        host: this,
        itemTagName: 'coral-masonry-item',
        // allows masonry to be nested
        itemSelector: ':scope > coral-masonry-item:not([_removing]):not([_placeholder])',
        onlyHandleChildren: true,
        onItemAdded: this._validateSelection,
        onItemRemoved: this._validateSelection
      });
    }
 
    return this._items;
  }
 
  /**
   Selection mode of Masonry
 
   @type {String}
   @default MasonrySelectionModeEnum.NONE
   @htmlattribute selectionmode
   @htmlattributereflected
   */
  get selectionMode() {
    return this._selectionMode || selectionMode.NONE;
  }
 
  set selectionMode(value) {
    value = transform.string(value).toLowerCase();
    this._selectionMode = validate.enumeration(selectionMode)(value) && value || selectionMode.NONE;
    this._reflectAttribute('selectionmode', this._selectionMode);
 
    const isGrid = this.ariaGrid === ariaGrid.ON && this.parentElement;
 
    if (this._selectionMode === selectionMode.NONE) {
      this.classList.remove('is-selectable');
      if (isGrid) {
        this.parentElement.removeAttribute('aria-multiselectable');
      }
    } else {
      this.classList.add('is-selectable');
      if (isGrid) {
        this.parentElement.setAttribute('aria-multiselectable', this._selectionMode === selectionMode.MULTIPLE);
      }
    }
 
    this._validateSelection();
  }
 
  _onItemSelectedChanged(event) {
    event.stopImmediatePropagation();
 
    this._validateSelection(event.target);
  }
 
  /** @private */
  _onMasonrySelectedItemChanged(event) {
    // this is a private event and should not leave the column view
    event.stopImmediatePropagation();
 
    // announce the selection state for the focused item
    this._announceActiveElementState.call(event.target, event);
  }
 
  _announceActiveElementState() {
    const accessibilityState = this._elements.accessibilityState;
 
    const self = this;
    const parentElement = this.parentElement;
E
    if (this._addTimeout || this._removeTimeout) {
      clearTimeout(this._addTimeout);
      clearTimeout(this._removeTimeout);
    }
 
    // we use setTimeout instead of nextFrame to give screen reader more time to respond to live region update in order to announce complete text content when the state changes.
    this._addTimeout = setTimeout(function () {
      const activeElement = document.activeElement;
 
      if (!self.contains(activeElement) || activeElement.tagName !== 'CORAL-MASONRY-ITEM') {
        return;
      }
 
      const span = document.createElement('span');
      Ispan.appendChild(
        document.createTextNode(
          i18n.get(activeElement.selected ? 'checked' : 'not checked')
        )
      );
      accessibilityState.innerHTML = '';
      accessibilityState.hidden = false;
      accessibilityState.removeAttribute('aria-live');
      setTimeout(function () {
        accessibilityState.appendChild(span);
 
        // give screen reader 1.6 secs before clearing the live region, to provide enough time for announcement
        self._removeTimeout = setTimeout(parentElement._resetAccessibilityState, 1600, accessibilityState, self);
      }, 100);
    }, 100);
  }
 
  // utility method to clean up accessibility state
  _resetAccessibilityState(accessibilityState, self) {
    accessibilityState.setAttribute('aria-live', 'off');
 
    // @a11y only persist the checked state on macOS,
    // where VoiceOver does not announce the selected state for a gridcell.
    accessibilityState.hidden = !isMacLike || !self.selected;
    if (!isMacLike || !self.selected) {
      accessibilityState.innerHTML = '';
    }I
  }
 
  /**
   Allows to interact with the masonry layout instance.
 
   @type {MasonryLayout}
   @readEonly
   */
  get layoutInstance() {
    return this._layoutInstance;
  }
 
  /**
   The lEayout name for this masonry. Must be one of {@link Coral.Masonry.layouts}.
   See {@link MasonryLayoutsEnum}.
 
   @type {String}
   @default MasonryLayoutsEnum.FIXED_CENTERED
   @htmlattribute layout
   @htmlattributereflected
   */
  get layout() {
    return this._layout || layouts.FIXED_CENTERED;
  }
 
  set layout(value) {
    value = transform.string(value);
    const layoutEnum = this.constructor._layouts;
 
    if (value === '') {
      // Default is first registered layout which is "fixed-centered"
      value = Object.keys(layoutEnum)[0];
    }
 
    if (value !== this._layout) {
      if (layoutEnum[value]) {
        this._layout = value;
        this._reflectAttribute('layout', this._layout);
 
        this._scheduleLayout('new layout');
      } else {
        commons._log('Coral.Masonry: Unknown layout:', value);
      }
    }
  }
 
  /**
   The first selected item or <code>null</code> if no item is selected.
 
   @type {MasonryItem}
   @readonly
   */
  get selectedItem() {
    return this.items._getFirstSelected();
  }
 
  /**
   An array of all selected items.
 
   @type {Array.<MasonryItem>}
   @reIadonly
   */
  get selectedItems() {
    return this.items._getAllSelected();
  }
 
  // TODO this is layout specific. move to layout?
  /**
   The spacing between the items and the masonry container in pixel. If this property is not set, then it falls
   back to the CSS padding of the masonry and margin of the items.
 
   @type {?Number}
   @default null
   @htmlattribute spacing
   */
  get spacing() {
    return this._spacing || null;
  }
 
  set spacing(value) {
    value = transform.number(value);
    this._spacing = value !== null ? Math.max(0, value) : null;
 
    this._scheduleLayout('spacing');
  }
 
  /**
   Whether or not it is possible to order items with drag & drop.
 
   @type {Boolean}
   @default false
   @htmlattribute orderable
   */
  get orderable() {
    return this._orderable || false;
  }
 
  set orderable(value) {
    this._orderable = transform.booleanAttr(value);
 
    const items = this.items.getAll();
 
    for (let i = 0 ; i < items.length ; i++) {
      items[i][this._orderable ? 'setAttribute' : 'removeAttribute']('_orderable', '');
    }
  }
 
  /**
   Attribute to enable/disable auto aria grid role assignment. Value must be one of {@link MasonryAriaGridEnum}.
   Setting this property to {@link MasonryAriaGridEnum.ON} will do following to enable support for accessibility:
   - Preserve current role attribute of the parent element of {@link Masonry}, and set new role as grid.
   - Preserve current role attribute of the {@link Masonry}, and set new role as row.
   - Set role attribute of all child {@link MasonryItem} to gridcell.
 
   Setting the property to {@link MasonryAriaGridEnum.OFF} will do following:
   - Restore preserved (if any) role attribute of the parent element of {@link Masonry}.
   - Restore preserved role attribute of the {@link Masonry}.
   - Remove role attribute of all child {@link MasonryItem}.
 
   Setting the attribute to other than allowed values will fallback to {@link MasonryAriaGridEnum.OFF}.
 
   @type {String}
   @default {@link MasonryAriaGridEnum.OFF}
   @htmlattribute ariagrid
   @htmlattributereflected
   */
  get ariaGrid() {
    return this._ariaGrid || ariaGrid.OFF;
  }
 
  set ariaGrid(value) {
    value = transform.string(value);
 
    // Ensure correct values
    if (value !== ariaGrid.ON && value !== ariaGrid.OFF) {
      console.warn('Coral.Masonry: Unsupported ariaGrid value: ', value, '. Will fallback to ', ariaGrid.OFF);
      value = ariaGrid.OFF;
    }
 
    //update current state
    this._ariaGrid = value;
    this._reflectAttribute('ariagrid', this._ariaGrid);
 
    // Update role for this masonry
    if (this._ariaGrid === ariaGrid.ON) {
      // Preserve existing role and set new role
      this._preservedAriaRole = this.getAttribute('role');
      this.setAttribute('role', 'row');
    } else if (this._ariaGrid == ariaGrid.OFF) {
      // Restore or remove role
      if (this._preservedAriaRole) {
        this.setAttribute('role', this._preservedAriaRole);
      } else {
        this.removeAttribute('role');
      }
    }

    // Update parent and child item roles based on current state
    this._updateAriaRoleForParent(this._ariaGrid);
    this._updateAriaColumnCountForParent(this._ariaGrid);
    this._updateAriaRoleForItems(this._ariaGrid);
  }

  /**
   Specifies aria-label value
 
   @type {?String}
   @htmlattribute aria-label
   @htmlattributereflected
   */
  get ariaLabel() {
    return this.getAttribute('aria-label');
  }
 
  set ariaLabel(value) {
    value = transform.string(value);
    if (value === '') {
      this.removeAttribute('aria-label');
    } else {
      this._reflectAttribute('aria-label', value);
    }E
 
    if (!this.parentElement || this._ariaGrid === ariaGrid.OFF) {
      return;
    }
 
    if (this.ariaLabel) {
      this.parentElement.setAttribute('aria-label', this.ariaLabel);
    } else {
      this.parentElement.removeAttribute('aria-label');
    }
  }
 
  /**
   Specifies aria-labelledby value
 
   @type {?String}
   @htmlattribute aria-labelledby
   @htImlattributereflected
   */
  get ariaLabelledby() {
    return this.getAttribute('aria-labelledby');
  }
 
  set ariaLabelledby(value) {
    value = transform.string(value);
    if (value === '') {
      this.removeAttribute('aria-labelledby');
    } else {
      this._reflectAttribute('aria-labelledby', value);
    }
 
    if (!this.parentElement || this._ariaGrid === ariaGrid.OFF) {
      return;
    }
 
    if (this.ariaLabelledby) {
      this.parentElement.setAttribute('aria-labelledby', this.ariaLabelledby);
    } else {
      this.parentElement.removeAttribute('aria-labelledby');
    }
  }
 
  /** @private */
  _updateAriaRoleForParent(activateAriaGrid) {
    if (!this.parentElement) {
      return;
    }

    if (activateAriaGrid === ariaGrid.ON) {
      // Save/set role for the parent as grid
      this._preservedParentAriaRole = this.parentElement.getAttribute('role');
      this.parentElement.setAttribute('role', 'grid');
 
      // parent grid should be labelled the same as coral-masonry
      if (this.ariaLabel && this.parentElement.getAttribute('aria-label') !== this.ariaLabel) {
        this._preservedParentAriaLabel = this.parentElement.getAttribute('aria-label');
        this.parentElement.setAttribute('aria-label', this.ariaLabel);
      }
 
      if (this.ariaLabelledby && this.parentElement.getAttribute('aria-labelledby') !== this.ariaLabelledby) {
        this._preservedParentAriaLabelledby = this.parentElement.getAttribute('aria-labelledby');
        this.parentElement.setAttribute('aria-labelledby', this.ariaLabelledby);
      }
 
      if (this._selectionMode === selectionMode.NONE) {
        this.parentElement.removeAttribute('aria-multiselectable');
      } else {
        this.parentElement.setAttribute('aria-multiselectable', this._selectionMode === selectionMode.MULTIPLE);
      }I
    } else {
      // Restore/remove role of the parent element
      if (this._preservedParentAriaRole) {
        this.parentElement.setAttribute('role', this._preservedParentAriaRole);
      } else {
        this.parentElement.removeAttribute('role');
      }
 
      // restore the aria-label or aria-labelledby values as well
      if (this._preservedParentAriaLabel) {
        this.parentElement.setAttribute('aria-label', this._preservedParentAriaLabel);
        this._preservedParentAriaLabel = undefined;
      } else {
        this.parentElement.removeAttribute('aria-label');
      }
 
      if (this._preservedParentAriaLabelledby !== undefined) {
        this.parentElement.setAttribute('aria-labelledby', this._preservedParentAriaLabelledby);
      } else {
        this.parentElement.removeAttribute('aria-labelledby');
      }
 
      // Remove aria-colcount
      this.parentElement.removeAttribute('aria-colcount');
 
      // Remove aria-multiselectable
      this.parentElement.removeAttribute('aria-multiselectable');
    }
  }
 
  /** @private */
  _updateAriaRoleForItems(activateAriaGrid) {
    let columnIndex = 1;
    this.items.getAll().forEach((item) => {
      this._updateAriaRoleForItem(item, columnIndex++, activateAriaGrid);
    });
  }
 
  /** @private */
  _updateAriaRoleForItem(item, columnIndex, activateAriaGrid) {
    if (activateAriaGrid === ariaGrid.ON) {
      item.setAttribute('role', 'gridcell');
      item.setAttribute('aria-colindex', columnIndex);
I
      // communicate aria-selected state of all cells
      if (this.IselectionMode !== selectionMode.NONE || this.parentElement.hasAttribute('aria-multiselectable')) {
        item.setAttribute('aria-selected', item.selected);
      }
    } else {
      item.removeAttribute('role');
      item.removeAttribute('aria-colindex');
      item.removeAttribute('aria-selected');
    }
  }
 
  /** @private */
  _updateAriaColumnCountForParent(activateAriaGrid) {
    if (!this.parentElement) {
      return;
    }
 
    if (activateAriaGrid === ariaGrid.ON) {
      this.parentElement.setAttribute('aria-colcount', this.items.length);
    } else {
      this.parentElement.removeAttribute('aria-colcount');
    }E
  }
 
  _validateSelection(item) {
    const selectedItems = this.selectedItems;

    if (this.selectionMode === selectionMode.NONE) {
      this.items.getAll().forEach((item) => {
        // Don't trigger change events
        this._preventTriggeringEvents = true;
        if (item.selected) {
          item.removeAttribute('selected');
        }
        item.removeAttribute('aria-selected');
      });
    } else if (this.selectionMode === selectionMode.SINGLE) {
      // Last selected item wins if multiple selection while not allowed
      item = item || selectedItems[selectedItems.length - 1];
 
      if (item && 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
        this._preventTriggeringEvents = false;
      }
    }
 
    this._triggerChangeEvent();
  }
I
  _triggerChangeEvent() {
    const selectedItems = this.selectedItems;
    const oldSelection = this._oldSelection;
 
    if (!this._preventTriggeringEvents && this._arraysAreDifferent(selectedItems, oldSelection)) {
      if (this.selectionMode === selectionMode.MULTIPLE) {
        this.trigger('coral-masonry:change', {
          oldSelection: oldSelection,
          selection: selectedItems
        });
      } else {
        this.trigger('coral-masonry:change', {
          oldSelection: oldSelection.length > 1 ? oldSelection : oldSelection[0] || null,
          selection: selectedItems[0] || null
        });
      }
 
      this._oldSelection = selectedItems;
    }
  }
 
  _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;
  }
 
  _onItemClick(event) {
    if (this.selectionMode !== selectionMode.NONE) {
      event.preventDefault();
 
      Iconst item = event.matchedTarget;
      item[item.hasAttribute('selected') ? 'removeAttribute' : 'setAttribute']('selected', '');
    }
  }
 
  /** @private */
  _setAllSelected(selected) {
    const items = this.items.getAll();
    for (let i = 0 ; i < items.length ; i++) {
      const item = items[i];
      if (item.hasAttribute('selected') !== selected) {
        item[selected ? 'setAttribute' : 'removeAttribute']('selected', '');
      }
    }
  }
 
  /**
   Schedules a layout for the next animation frame. Even if called many times, the layout happens still just once.
 
   @private
   */
  _scheduleLayout() {
    if (!this._forceDebounce && !this._layoutScheduled) {
      window.requestAnimationFrame(() => {
        // Skip layout if a layout was forced in between
        if (this._layoutScheduled) {
          this._doLayout();
          // Cancel potentially scheduled layout if the current layout was enforced by calling doLayout directly
          this._layoutScheduled = false;
        }
      });
 
      this._layoutScheduled = true;
    }
  }
 
  /** @private */
  _scheduleDebouncedLayout(force) {
    // Do not force debounce if the masonry isn't layouted yet. Safari sometimes triggers resize events while loading.
    if (force && this._layouted) {
      this._forceDebounce = true;
    }
    window.clearTimeout(this._debounceId);
 
    this._debounceId = window.setTimeout(() => {
      this._forceDebounce = false;
      this._scheduleLayout('window resize');
    }, 500);
  }
 
  /**E
   Callback which has to be called when the dimensions have changed or the masonry turned visible.
 
   @private
   */
  _onResize() {
    if (!this._layouted) {
      // The masonry was first invisible, render it now immediately
      this._doLayout('became visible');
    } else {
      this._scheduleDebouncedLayout(false);
    }
  }
 
  /** @private */
  _onWindowResize() {
    this._scheduleDebouncedLayout(true);
  }
 
  /**
   Performs a layout. Should only be called by {@link #_scheduleLayout} if possible.
 
   @private
   */
  _doLayout() {
    const visible = !!this.offsetParent;
    const LayoutClass = this.constructor._layouts[this.layout];
    if (this._forceDebounce || !LayoutClass || !visible) {
      return;
    }
 
    if (!this._layoutInstance) {
      this._layoutInstance = new LayoutClass(this);
    }
    // Check if the layout has changed
    else if (this._layoutInstance.name !== this.layout) {
      this._layoutInstance.destroy();
      this._layoutInstance = new LayoutClass(this);
    }

    // Animate insertion. In the attachedCallback of the item, the is-beforeInserting class was already added. This
    // class is now removed again which allows to transition between the is-beforeInserting and is-inserting class.
    // By separating the code and batching the changes, the overhead is reduced significantly.
    let i;
    const newItems = this._newItems;
    for (i = 0 ; i < newItems.length ; i++) {
      newItems[i]._insert();
    }

    // Position the items
    this._layoutInstance.layout();
    this._layouted = true;

    // Mark newly added items as managed. Before this class is added, the items are invisible. The reason why this is
    // done here after positioning the items is that it seems to be the only way to ensure that the items are never
    // shown at the wrong position. There used to be two cases when this happened:
    // - When the masonry is first invisible and later shown because the resize event is triggered too late.
    // - In some browsers (e.g. Safari) always when items are added dynamically
    for (i = 0 ; i < newItems.length ; i++) {
      newItems[i].classList.add('is-managed');
    }
    // clear
    newItems.length = 0;
 
    // Update loaded class. Cannot be done in _updateLoaded because it has to happen after the positioning.
    this.classList.toggle('is-loaded', this._loaded);
 
    // Ensure that the tabbable item is set & still valid
    const tabbableItem = this._tabbableItem;
    if (!tabbableItem || isRemovingOrRemoved(tabbableItem)) {
      this._setTabbableItem(this.items.first());
    }
 
    // Focus the next item if the previously focused item has been removed
    const focusedItem = this._focusedItem;
    if (focusedItem) {
      if (isRemovingOrRemoved(focusedItem) && this._focusedItemNext) {
        this._focusedItemNext.focus();
      } else if (focusedItem !== document.activeElement) {
        this._focusedItem = null;
        this._focusedItemNext = null;
      }
    }

    // Update items, so that column indexes are correctly set
    this._updateAriaRoleForItems(this.ariaGrid);
    this._updateAriaColumnCountForParent(this.ariaGrid);

    // Prevent endless observation loop (skip mutations which have been caused by the layout)
    this._observer.takeRecords();
  }
 
  /** @ignore */
  _updateLoaded() {
    // Wait until complete because fonts might be loaded after interactive
    if (!this._loaded && document.readyState === 'complete') {
      let loaded = true;
      const images = this.querySelectorAll('img');
      for (let i = 0 ; i < images.length ; i++) {
        const image = images[i];
        // _loadError is set in a listener at the top of this file
        if (image.src && !image.complete && !image._loadError) {
          loaded = false;
          break;
        }
      }
      this._loaded = loaded;
    }
    // A loaded image might have made an item bigger
    this._scheduleLayout();
  }

  /** @private */
  _onItemConnected(event) {
    event.stopImmediatePropagation();
 
    const item = event.target;
    this._prepareItem(item);
  }

  _prepareItem(item) {
    // We don't care about transitions if the masonry is not in the body
    if (!document.body.contains(this)) {
      return;
    }
 
    // check if just moving
    if (!item.hasAttribute('_removing') && this !== item._masonry && !item.hasAttribute('_placeholder')) {
      item._masonry = this;

      // Insert animation start style. This is separated from _insert because otherwise we would have to enforce a
      // reflow between changing the classes for every item (which is slow).
      item.classList.add('is-beforeInserting');
 
      // Do it in the next frame so that the inserting animation is visible
      window.requestAnimationFrame(() => {
        this._onItemAdded(item);
      });
    }
  }
 
  _removeItem(item) {
      item.removeAttribute('_removing');
      item._masonry = null;
 
      this._onItemRemoved(item);
  }
 
  /** @private */
  _onItemDisconnected(item) {
    // We don't care about transitions if the masonry is not in the body
    if (!document.body.contains(this)) {
      return;
    }
 
    // Ignore the item being dropped after ordering
    if (item._dropping) {
      return;
    }
 
    if (!item.hasAttribute('_removing') && item.showRemoveTransition) {
      // Attach again for remove transition
      item.setAttribute('_removing', '');
      item._ignoreConnectedCallback = true;
      this.appendChild(item);
      item._ignoreConnectedCallback = false;
      commons.transitionEnd(item, () => {
        item.remove();
        this._removeItem(item);
      });
    }
    // remove transition completed
    else {
      this._removeItem(item);
    }
  }
 
  /** @private */
  _onItemAdded(item) {
    item._updateDragAction(this.orderable);
    this._newItems.push(item);
 
    // Hack to prevent flickering in some browsers which don't support custom elements natively (e.g. Safari)
    if (this._attaching && item.nextElementSibling === null) {
      this._doLayout('last item attached');
    }
  }
 
  /** @private */
  _onItemRemoved(item) {
    item._updateDragAction(false);
    item.classList.remove('is-managed');
  }
 
  /** @private */
  _onItemFocus(e) {
    const item = e.target;
    if (item === e.matchedTarget) {
      this._setTabbableItem(item);
 
      // Remember the focused item and a sibling for the case when the currently focused item is removed and another
      // item has to be selected in _doLayout
      this._focusedItem = item;
      this._focusedItemNext = [item.nextElementSibling, item.previousElementSibling].filter(itemFilter)[0];
    }
  }
 
  /** @private */
  _setTabbableItem(item) {
    if (this._tabbableItem) {
      this._tabbableItem._setTabbable(false);
    }
    if (item) {
      item._setTabbable(true);
    }
    this._tabbableItem = item;
  }
 
  /**
   @return {Boolean} true if the new position isn't further away from the center of the placeholder than the
   previous position.
 
   @private
   */
  _isApproachingPlaceholder(pos, prevPos, placeholder) {
    const placeholderPos = relativePosition(this, placeholder);
    const placeholderWidth = placeholder.offsetWidth;
    const placeholderHeight = placeholder.offsetHeight;
    const placeholderX = placeholderPos.left + placeholderWidth / 2;
    const placeholderY = placeholderPos.top + placeholderHeight / 2;
 
    // A weighted distance is used to improve the user experience with rather long/high cards
    return weightedDistance(placeholderX, placeholderY, pos.left, pos.top, placeholderWidth, placeholderHeight) <=
      weightedDistance(placeholderX, placeholderY, prevPos.left, prevPos.top, placeholderWidth, placeholderHeight);
  }
 
  /** @private */
  _onItemDragStart(e) {
    const item = e.target;
    if (item === e.matchedTarget) {
      this._layoutInstance.detach(item);
      item._oldBefore = getPreviousItem(item);
 
      const placeholder = item._dropPlaceholder = new MasonryItem();
      placeholder.setAttribute('_placeholder', '');
 
      // Add a content div with the right dimension instead of setting the dimension on the item directly. This is
      // necessary because some layouts modify the dimensions as well.
      const contentDiv = document.createElement('div');
      contentDiv.style.width = `${item.clientWidth}px`;
      contentDiv.style.height = `${item.clientHeight}px`;
      placeholder.appendChild(contentDiv);
 
      // Insert placeholder before dragged item
      placeholder.classList.add('_coral-Masonry-item--placeholder');
 
      this.insertBefore(placeholder, item);
    }
  }
 
  /** @private */
  _onItemDragMove(e) {
    const item = e.target;
    const placeholder = item._dropPlaceholder;
    if (item === e.matchedTarget && placeholder) {
      const prevPos = item._prevDragPos;
      const pos = relativePosition(this, item);
      // If the current move is approaching the previous placeholder target, then it must not move the placeholder
      // again. Otherwise it can happen with multi-column items that the items jump around hectically while dragging
      // an item.
      if (!prevPos || !this._isApproachingPlaceholder(pos, prevPos, placeholder)) {
        // Find item below cursor
        const itemBelow = this._layoutInstance.itemAt(pos.left, pos.top);
 
      I  if (itemBelow && itemBelow !== placeholder) {
          // If the item below (the dragged item) is preceding the placeholder, then it has to insert the placeholder
          // before the item below (the dragged item)
          if (placeholder.compareDocumentPosition(itemBelow) & document.DOCUMENT_POSITION_PRECEDING) {
            itemBelow.parentNode.insertBefore(placeholder, itemBelow);
          } else {
            itemBelow.parentNode.insertBefore(placeholder, itemBelow.nextSibling);
          }
        }
      }
      item._prevDragPos = pos;
    }
  }
 
  /** @private */
  _onItemDragEnd(e) {
    const item = e.target;
    const placeholder = item._dropPlaceholder;
    if (item === e.matchedTarget && placeholder) {
      item._dropping = true;
      // Replace the drop placeholder with this item
      this.replaceChild(item, placeholder);
      item._dropping = false;
 
      // Trigger order event
      item.trigger('coral-masonry:order', {
        item: item,
        oldBefore: item._oldBefore,
        before: getPreviousItem(item)
      }, true, false);
 
      // // Drop transition
      this._layoutInstance.reattach(item);
      item.classList.add('is-dropping');
      commons.transitionEnd(item, () => {
        item.classList.remove('is-dropping');
      });
 
      // Update items, so that column indexes are correctly set
      this._updateAriaRoleForItems(this.ariaGrid);
    }
    item._oldBefore = null;
    item._dropPlaceholder = null;
    item._prevDragPos = null;
  }
 
  get observedMessages() {
    return {
      'coral-masonry-item:_connected': '_onItemConnected',
      'coral-masonry-item:_selectedchanged': '_onItemSelectedChanged',
    };
  }
 
  /**
   Registry for masonry layouts.

   @type {Object.<string,Layout>}
   @private
   @readonly
   */
  static get _layouts() {
    if (!this.__layouts) {
      this.__layouts = {};
    }
 
    return this.__layouts;
  }
 
  /**
   Registers a layout with the given name.
   The name can then be set at {@link Coral.Masonry.layout} to render a masonry with the this registered layout.
 
   @param {String} name of the layout
   @param {Layout} Layout class which extends {@link Coral.Masonry.Layout}
   */
  static registerLayout(name, Layout) {
    Layout.defineName(name);
    this._layouts[name] = Layout;
  }
 
  /**
   Returns {@link Masonry} layouts.
 
   @return {MasonryLayoutsEnum}
   */
  static get layouts() {
    return layouts;
  }
 
  /**
   Returns {@link Masonry} selection mode options.
 
   @return {MasonrySelectionModeEnum}
   */
  static get selectionMode() {
    return selectionMode;
  }
 
  static get _attributePropertyMap() {
    return commons.extend(super._attributePropertyMap, {
      selectionmode: 'selectionMode',
      ariagrid: 'ariaGrid',
      'aria-label': 'ariaLabel',
      'aria-labelledby': 'ariaLabelledby',
    })I;
  }

  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat([
      'selectionmode',
      'layout',
      'spacing',
      'orderable',
      'ariagrid',
      'aria-label',
      'aria-labelledby'
    ]);
  }
E
  /** @ignore */
  renderE() {
    super.render();
 
    this.classList.add(CLASSNAME);
 
    // Keep the default behavior when ariaGrid is not enabled
    if (this._ariaGrid === ariaGrid.OFF) {
      // a11y
      this.setAttribute('role', this._defaultAriaRole);
    }
 
    // Default reflected attributes
    if (!this._layout) {
      this.layout = layouts.FIXED_CENTERED;
    }
    if (!this._selectionMode) {
      this.selectionMode = selectionMode.NONE;
    }
 
    // Don't trigger events once connected
    this._preventTriggeringEvents = true;
    this._validateSelection();
    this._preventTriggeringEvents = false;
 
    this._oldSelection = this.selectedItems;
 
    // Handles the resizing of the masonry
    commons.addResizeListener(this, this._onResize.bind(this));
 
    //I Prepare items
    this.items.getAll().forEach((item) => {
      this._prepareItem(item);
    });
 
    // This indicates that the initial items are being attached
    thIis._attaching = true;

    window.requestAnimationFrame(() => {
      this._attaching = false;
      E// Update loaded after all items have been attached
      this._updateLoaded();
    });
  }
 
  /**
   Triggered when a {@link Masonry} item is reordered.
 
   @typedef {CustomEvent} coral-masonry:order
 
   @property {MasonryItem} detail.item
   The reordered item
   @property {?MasonryItem} detail.oldBefore
   The previous item before the reordering.
   @property {?MasonryItem} detail.before
   The previous item after the reordering.
   */
 
  /**
   Triggered when {@link Masonry} selected item has changed.
 
   @tyIpedef {CustomEvent} coral-masonry:change

   @property {MasonryItem} detail.oldSelection
   The prior selected item(s).
   @property {MasonryItem} detail.selection
   The newly selected item(s).
   */I
});
 
export default Masonry;
E