All files / coral-component-quickactions/src/scripts QuickActions.js

81.26% Statements 386/475
63.96% Branches 181/283
86.49% Functions 64/74
81.26% Lines 386/475

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 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307                                                              2x                       2x                                 2x                                   2x         2x 2x                   2x 2x   2x           102x   102x   102x 102x 102x 102x 102x 102x 102x 102x 102x   102x 82x       102x   102x   102x       102x                                       102x   102x 102x 102x 102x 102x 102x 102x 102x   102x 102x 102x   102x     102x   102x                 2x     194x         194x                 1014x   1014x   446x       568x   568x 568x       568x       568x             88x   88x         88x   88x 88x 88x 88x                                                             598x 598x 98x 98x     500x                                   12x 12x   12x 12x   6x 6x     6x 6x                             100x 100x 100x                         14x                       2x                       2x   2x             8x   8x 8x                             610x                         306x 36x   36x       270x 54x     270x   270x     270x 260x           10x 10x               270x 270x 270x 270x 270x 270x 270x       270x 260x 10x 10x 10x     270x 270x 270x 270x 270x 270x 270x 270x 270x 270x                   100x   100x   100x 2x     98x     98x 98x   98x             98x 98x 98x   98x   98x 576x   576x 550x         98x 98x 98x 98x 98x   98x     98x 80x 8x   72x     18x       98x 402x   402x   402x 402x       98x   98x 80x   8x 70x       8x 20x       8x   72x     80x     18x   18x     98x     98x             98x                   198x   198x   198x 194x   194x 96x   96x   96x 96x 320x     96x     98x                   12x   12x 12x 12x   12x                   12x   12x                       4x   4x 4x       4x       4x 4x 2x     4x                                 10x   10x             10x   10x 10x   10x               6x   6x 6x 6x     6x 6x 6x 6x 6x 6x     6x                                     2x   2x 2x                 2x   2x     2x 2x                 2x   2x     2x 2x               6x   6x               6x   6x 6x                     6x   6x               6x   6x 6x                 4x   4x   4x       4x 4x   4x     4x 4x   4x   4x         6x 6x   6x         28x 22x   22x 22x 22x 22x     22x 22x 22x               24x 19x 19x 19x     19x 13x 13x                 12x         12x   12x   12x               18x   18x                                                                                                                       2x   2x           32x 2x     2x                   4x 4x   4x       4x   4x   4x             2x               4x 4x                                           304x   304x               296x   296x 54x   54x   54x   54x                 56x 2x   2x 2x     56x 2x   2x 2x               340x   340x 340x   340x 44x 44x 44x 44x     340x   340x 44x 44x 44x             456x 228x             228x                         228x   228x   228x   228x   186x   186x 186x                                 112x   112x   112x   112x 2x               112x   112x   112x   112x   112x 224x   224x 58x       112x 112x 112x   112x   112x 112x   112x             112x   112x   112x 8x 8x           2x                       226x 102x               226x                             100x     8x   8x                           828x                                   106x                                   954x       174x   174x
/**
 * 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 {Icon} from '../../../coral-component-icon';
import {Button} from '../../../coral-component-button';
import {AnchorButton} from '../../../coral-component-anchorbutton';
import {ButtonList, AnchorList} from '../../../coral-component-list';
import {ExtensibleOverlay, Overlay} from '../../../coral-component-overlay';
import {Collection} from '../../../coral-collection';
import QuickActionsItem from './QuickActionsItem';
import '../../../coral-component-popover';
import base from '../templates/base';
import {transform, validate, commons, i18n} from '../../../coral-utils';
import {Decorator} from '../../../coral-decorator';
 
const BUTTON_FOCUSABLE_SELECTOR = '._coral-QuickActions-item:not([disabled]):not([hidden])';
 
/**
 Enumeration for {@link QuickActions} interaction options.
 
 @typedef {Object} QuickActionsInteractionEnum
 
 @property {String} ON
 Show when the target is hovered or focused and hide when the mouse is moved out or focus is lost.
 @property {String} OFF
 Do not show or hide automatically.
 */
const interaction = {
  ON: 'on',
  OFF: 'off'
};
 
/**
 Enumeration for {@link QuickActions} anchored overlay target options.
 
 @typedef {Object} QuickActionsTargetEnum
 
 @property {String} PARENT
 Use the parent element in the DOM.
 @property {String} PREVIOUS
 Use the previous sibling element in the DOM.
 @property {String} NEXT
 Use the next sibling element in the DOM.
 */
const target = {
  PARENT: '_parent',
  PREVIOUS: '_prev',
  NEXT: '_next'
};
 
/**
 Enumeration for {@link QuickActions} placement options.
 
 @typedef {Object} QuickActionsPlacementEnum
 
 @property {String} TOP
 QuickActions inset to the top of the target.
 @property {String} CENTER
 QuickActions inset to the center of the target.
 @property {String} BOTTOM
 QuickActions inset to the bottom the target.
 */
const placement = {
  TOP: 'top',
  CENTER: 'center',
  BOTTOM: 'bottom'
};
 
const OFFSET = 10;
 
const CLASSNAME = '_coral-QuickActions';
 
/**
 @class Coral.QuickActions
 @classdesc A QuickActions component is an overlay component that reveals actions when interacting with a container.
 Hovering the target will display the QuickActions. They can also be launched by pressing the shift + F10 key combination
 when the target is focused.
 @htmltag coral-quickactions
 @extends {Overlay}
 */
const QuickActions = Decorator(class extends ExtensibleOverlay {
  /** @ignore */
  constructor() {
    super();
 
    // Override defaults
    this._overlayAnimationTime = Overlay.FADETIME;
    this._alignMy = Overlay.align.CENTER_TOP;
    this._alignAt = Overlay.align.CENTER_TOP;
    this._lengthOffset = OFFSET;
    this._inner = true;
    this._target = target.PREVIOUS;
    this._placement = placement.TOP;
    this._focusOnShow = Overlay.focusOnShow.OFF;
    this._scrollOnFocus = Overlay.scrollOnFocus.OFF;
 
    if (!this.id) {
      this.id = commons.getUID();
    }
 
    // Flag
    this._openedBefore = false;
 
    // Debounce timer
    this._timeout = null;
 
    // Template
    base.call(this._elements, {commons, i18n});
 
    const events = {
      'global:resize': '_onWindowResize',
      'mouseout': '_onMouseOut',
 
      // Keyboard interaction
      'key:home': '_onHomeKeypress',
      'key:end': '_onEndKeypress',
      'key:pagedown': '_onButtonKeypressNext',
      'key:right': '_onButtonKeypressNext',
      'key:down': '_onButtonKeypressNext',
      'key:pageup': '_onButtonKeypressPrevious',
      'key:left': '_onButtonKeypressPrevious',
      'key:up': '_onButtonKeypressPrevious',
 
      'capture:focus': '_onFocus',
      'capture:blur': '_onBlur',
 
      // Buttons
      'click > ._coral-QuickActions-item:not([handle="moreButton"])': '_onButtonClick',
      'click > ._coral-QuickActions-item[handle="moreButton"]': '_onMoreButtonClick',
 
      //Messenger
      'coral-quickactions-item:_messengerconnected': '_onMessengerConnected'
    };
 
    const overlayId = this._elements.overlay.id;
 
    // Overlay
    events[`global:capture:coral-overlay:beforeopen #${overlayId}`] = '_onOverlayBeforeOpen';
    events[`global:capture:coral-overlay:beforeclose #${overlayId}`] = '_onOverlayBeforeClose';
    events[`global:capture:coral-overlay:open #${overlayId}`] = '_onOverlayOpen';
    events['global:capture:coral-overlay:close'] = '_onOverlayClose';
    events[`global:capture:coral-overlay:positioned #${overlayId}`] = '_onOverlayPositioned';
    events[`global:capture:coral-overlay:_animate #${overlayId}`] = '_onAnimate';
    events[`global:capture:mouseout #${overlayId}`] = '_onMouseOut';
    events[`global:capture:click #${overlayId} [coral-list-item]`] = '_onButtonListItemClick';
 
    // Cache bound event handler functions
    this._onTargetMouseEnter = this._onTargetMouseEnter.bind(this);
    this._onTargetKeyUp = this._onTargetKeyUp.bind(this);
    this._onTargetMouseLeave = this._onTargetMouseLeave.bind(this);
 
    // Events
    this._delegateEvents(events);
 
    // delegates the item handling to the collection
    this.items._startHandlingItems(true);
  }
 
  /**
   Returns the inner overlay to allow customization.
 
   @type {Popover}
   @readonly
   */
  get overlay() {
    return this._elements.overlay;
  }
 
  /**
   The Item collection.
 
   @type {Collection}
   @readonly
   */I
  get items() {
    // we do lazy initialization of the collection
    if (!this._items) {
      this._items = new Collection({
        host: this,
        itemTagName: 'coral-quickactions-item',
        onItemRemoved: this._onItemRemoved,
        onCollectionChange: this._onCollectionChange
      });
    }
 
    return this._items;
  }
 
  /**
   The number of items that are visible in QuickActions (excluding the show more actions button) before a collapse
   is enforced. A value <= 0 disables this feature and shows as many items as possible. Regardless of this
   property, the QuickActions will still fit within their target's width.
 
   @type {Number}
   @default 4
   @htmlattribute threshold
   @htmlattributereflected
   */E
  get thIreshold() {
    return typeof this._threshold === 'number' ? this._threshold : 4;
  }
 
  set threshold(value) {
    this._threshold = transform.number(value);
    this._reflectAttribute('threshold', this._threshold);
  }
 
  /**
   The placement of the QuickActions. The value may be one of 'top', 'center' and 'bottom' and indicates the vertical
   alignment of the QuickActions relative to their container.
   See {@link OverlayPlacementEnum}.
 
   @type {String}
   @default OverlayPlacementEnum.TOP
   @htmlattribute placement
   */I
  get placement() {
    return super.placement;
  }
 
  set Eplacement(value) {
    value = transform.string(value).toLowerCase();
    this._placement = validate.enumeration(placement)(value) && value || placement.TOP;
 
    this.reposition();
  }
 
  /**
   Whether the QuickActions should show when the target is interacted with. See {@link QuickActionsInteractionEnum}.
 
   @type {String}
   @default QuickActionsInteractionEnum.ON
   @name interaction
   @htmlattribute interaction
   */
  get interaction() {
    return super.interaction;
  }
 
  set interaction(value) {
    super.interaction = value;

    if (this.interaction === interaction.ON) {
      this._addTargetEventListeners();
    } else {
      this._removeTargetEventListeners();
    }
  }
 
  /**
   Inherited from {@link Overlay#target}.
   */
  get target() {
    return super.target;
  }
 
  set Etarget(value) {
    // avoid popper initialization while connecting for first time and not opened.
    this._EavoidPopperInit = this.open || this._popper ? false : true;
 
    super.target = value;
 
    const targetElement = this._getTarget(value);
    const prevTargetElement = this._previousTarget;
    const targetHasChanged = targetElement !== prevTargetElement;
 
    if (targetElement && targetHasChanged) {
      // Remove listeners from the previous target
      if (prevTargetElement) {
        const previousTarget = this._getTarget(prevTargetElement);
        if (previousTarget) {
          this._removeTargetEventListeners(previousTarget);
          targetElement.removeAttribute('aria-haspopup');
          targetElement.removeAttribute('aria-owns');
        }
      }
 
      // Set up listeners for the new target
      this._addTargetEventListeners();
 
      let ariaOwns = targetElement.getAttribute('aria-owns');
      ariaOwns = ariaOwns && ariaOwns.length ? `${ariaOwns.trim()}  ${this.id}` : this.id;
 
      EtargetElement.setAttribute('aria-owns', ariaOwns);
      // Mark the target as owning a popup
      targetElement.setAttribute('aria-haspopup', 'true');
E
      // Cache for use as previous target
      this._previousTarget = targetElement;
    }
    delete thEis._avoidPopperInit;
  }
 
  get observedMessages() {
    return {
      'coral-quickactions-item:_contentchanged': '_onItemChange',
      'coral-quickactions-item:_iconchanged': '_onItemChange',
      'coral-quickactions-item:_hrefchanged': '_onItemChange',
      'coral-quickactions-item:_typechanged': '_onItemTypeChange'
    };
  }
  /**
   Inherited from {@link Overlay#open}.
   */
  get open() {
    return super.open;
  }

  set open(value) {
    // If opening and stealing focus, on close, focus should be returned
    // to the element that had focus before QuickActions were opened.
    if (value &&
      this._focusOnShow !== this.constructor.focusOnShow.OFF) {
      this.returnFocusTo(document.activeElement);
    }
 
    super.open = value;
 
    this._openedOnce = true;
 
    // Position once we can read items layout in the next frame
    window.requestAnimationFrame(() => {
      if (this.open && !this._openedBefore) {
        // we iterate over all the items initializing them in the correct order
        const items = this.items.getAll();
        for (let i = 0, itemCount = items.length ; i < itemCount ; i++) {
          this._attachItem(items[i], i);
        }
 
        this._openedBefore = true;
      }
 
      if (this.open) {
        this._layout();
      }
 
      // we toggle "is-selected" on the target to indicate that the over is open
      const targetElement = this._getTarget();
      if (targetElement) {
        targetElement.classList.toggle('is-selected', this.open);
      }
    });
  }
 
  _getButtonWidth() {
    if (this.closest('.coral--large')) {
      // 40px button width + 10px left margin
      return 50;
    } else {
      // 32px button width + 8px left margin
      return 40;
    }
  }
 
  /** @ignore */
  _getTarget(targetValue) {
    //E Use passed target
    targetValue = targetValue || this.target;
 
    if (targetValue instanceof Node) {
      // Just return the provided Node
      return targetValue;
    }
 
    // Dynamically get the target node based on target
    let newTarget = null;
    if (typeof targetValue === 'string') {
      if (targetValue === target.PARENT) {
        newTarget = this.parentNode;
      } else {
        // Delegate to Coral.Overlay for _prev, _next and general selector
        newTarget = super._getTarget(targetValue);
      }
    }
 
    return newTarget;
  }
 
  /** @ignore */
  _addTargetEventListeners(targetElement) {
    targetElement = targetElement || this._getTarget();
 
    if (!targetElement) {
      return;
    }
 
    // Interaction-sensitive listeners
    if (this.interaction === interaction.ON) {
      // We do not have to worry about the EventListener being called twice as duplicates are discarded
      targetElement.addEventListener('mouseenter', this._onTargetMouseEnter);
      targetElement.addEventListener('keyup', this._onTargetKeyUp);
      targetElement.addEventListener('keydown', this._onTargetKeyDown);
      targetElement.addEventListener('mouseleave', this._onTargetMouseLeave);
    }
  }
 
  /** @ignore */
  _removeTargetEventListeners(targetElement) {
    targetElement = targetElement || this._getTarget();
 
    if (!targetElement) {
      return;
    }
 
    targetElement.removeEventListener('mouseenter', this._onTargetMouseEnter);
    targetElement.removeEventListener('keyup', this._onTargetKeyUp);
    targetElement.removeEventListener('keydown', this._onTargetKeyDown);
    targetElement.removeEventListener('mouseleave', this._onTargetMouseLeave);
  }E
 
  /**
   Toggles whether or not an item is tabbable.
 
   @param {HTMLElement} item
   The item to process.
 
   @param {Boolean} tabbable
   Whether the item should be marked tabbable.
   @ignore
   */
  _toggleTabbable(item, tabbable) {
    if (item) {
      if (tabbable) {
        if (item.hasAttribute('tabIndex')) {
          item.removeAttribute('tabIndex');
        }
      } else {
        item.setAttribute('tabIndex', '-1');
      }
    }E
  }
 
  /**
   Gets the subsequent or previous focusable neighbour relative to an Item button.
 
   @param {HTMLElement} current
   The current button element from which to find the next selectable neighbour.
   @param {Boolean} [previous]
   Whether to look for a previous neighbour rather than a subsequent one.
 
   @returns {HTMLElement|undefined} The focusable neighbour. Undefined if no suitable neighbour found.
 
   @private
   */
  _getFocusableNeighbour(current, previous) {
    // we need to convert the result to an array in order to use .indexOf()
    const focusableButtons = Array.prototype.slice.call(this._getFocusableButtons());
    const index = focusableButtons.indexOf(current);
 
    if (index >= 0) {
      if (!previous) {
        // Pick the next focusable button
        if (index < focusableButtons.length - 1) {
          return focusableButtons[index + 1];
        }
      }
      // Pick the previous focusable button
      else if (index !== 0) {
        return focusableButtons[index - 1];
      }
    }
  }
 
  /**
   Gets the buttons, optionally excluding the more button.
 
   @param {Boolean} excludeMore
   WheIther to exclude the more button.

   @returns {NodeList} The NodeList containing all the buttons.

   @private
   */
  _getButtons(excludeMore) {
    let buttonSelector = '._coral-QuickActions-item';
    buttonSelector = excludeMore ? `${buttonSelector}:not([handle="moreButton"])` : buttonSelector;
 
    return this.querySelectorAll(buttonSelector);
  }
 
  /**
   An element is focusable if it is visible and not disabled.
 
   @returns {NodeList} A NodeList containing the focusable buttons.
 
   @private
   */
  _getFocusableButtons() {
    // since we use the hidden attribute to hide the items, we can rely on this attribute to determine if the button
    // is hidden, instead of using a more expensive :focusable selector
    return this.querySelectorAll(BUTTON_FOCUSABLE_SELECTOR);
  }
 
  /**
   Gets the first focusable button.
 
   @returns {HTMLElement|undefined}
   The first focusable button, undefined if none found.
   @ignore
   */
  _getFirstFocusableButton() {
    return this.querySelector(BUTTON_FOCUSABLE_SELECTOR);
  }
 
  /**
   Gets the last focusable button.
 
   @returns {HTMLElement|undefined}
   The last focusable button, undefined if none found.
   @ignore
   */
  _getLastFocusableButton() {
    const focusableButtons = this._getFocusableButtons();
    return focusableButtons[focusableButtons.length - 1];
  }E
 
  /** @ignore */
  _proxyClick(item) {
    const event = item.trigger('click');
 
    if (!event.defaultPrevented && this.interaction === interaction.ON) {
      this._hideAll();
    }
  }
 
  /**
   Gets data from an Item.
 
   @param {HTMLElement} item
   The Item to get the data from.
   @returns {Object}
   The Item data.
   @ignore
   */
  _getItemData(item) {
    return {
      htmlContent: item.innerHTML,
      textContent: item.textContent,
      // fallback to empty string in case it has no icon
      icon: item.getAttribute('icon') || ''
    };
  }
 
  /** @ignore */
  _attachItem(item, index) {
    // since the button has already been initialized we make sure it is up to date
    if (item._elements && item._elements.button) {
      this._updateItem(item);
      return;
    }
I
    // if the index was not provided, we need to calculate it
    if (typeof index === 'undefined') {
      index = Array.prototype.indexOf.call(this.items.getAll(), item);
    }
 
    const itemData = this._getItemData(item);
    const type = QuickActionsItem.type;
 
    let button;
    if (item.type === type.BUTTON) {
      button = new Button().set({
        icon: itemData.icon,
        iconsize: Icon.size.SMALL,
        type: 'button',
        tracking: 'off'
      }, true);
    } else if (item.type === type.ANCHOR) {
      button = new AnchorButton().set({
        icon: itemData.icon,
        iconsize: Icon.size.SMALL,
        href: item.href,
        tracking: 'off'
      }, true);
    }
 
    button.variant = Button.variant.QUIET_ACTION;
    button.classList.add('_coral-QuickActions-item');
    button.setAttribute('tabindex', '-1');
    buttonE.setAttribute('title', itemData.textContent.trim());
    button.setAttribute('aria-label', itemData.textContent.trim());
    button.setAttribute('role', 'menuitem');
 
    this.insertBefore(button, this.children[index]);
 
    // ButtonList Item
    let buttonListItem;
    if (item.type === type.BUTTON) {
      buttonListItem = new ButtonList.Item();
    } else if (item.type === type.ANCHOR) {
      buttonListItem = new AnchorList.Item();
      buttonListItem.href = item.href;
    }
 
    const buttonListItemParent = this._elements.buttonList;
 
    buttonListItem.tabIndex = -1;
    buttonListItem.content.innerHTML = itemData.htmlContent;
    buttonListItem.icon = itemData.icon;
    buttonListItem.setAttribute('role', 'menuitem');
    buttonListItemParent.insertBefore(buttonListItem, buttonListItemParent.children[index]);
 
    item._elements.button = button;
    itIem._elements.buttonListItem = buttonListItem;
    buttonListItem._elements.quickActionsItem = item;
    button._elements.quickActionsItem = item;
  }
 
  /**
   Layout calculation; collapses QuickActions as necessary.
   */
  _layout() {
    // Set the width of the QuickActions to match that of the target
    this._setWidth();
 
    const buttons = this._getButtons(true);
 
    if (!buttons.length) {
      return;
    }
 
    const buttonListItems = this._elements.buttonList.items.getAll();

    // Temporarily display the QuickActions so we can do the calculation
    const display = this.style.display;
    let temporarilyShown = false;
 
    if (!this.open) {
      this.style.left -= 10000;
      Ethis.style.top -= 10000;
      this.style.display = 'block';
      temporarilyShown = true;
    }
 
    coInst totalAvailableWidth = this.offsetWidth;

    let totalFittingButtons = 0;
    let widthUsed = 0;
    const buttonWidth = this._getButtonWidth();
    while (totalAvailableWidth > widthUsed) {
      widthUsed += buttonWidth;
 
      if (totalAvailableWidth > widthUsed) {
        totalFittingButtons++;
      }
    }
 
    // Remove one to avoid taking full width space
    totalFittingButtons--;
 
    const threshold = this.threshold;
    const handleThreshold = threshold > 0;
    const moreButtonsThanThreshold = handleThreshold && buttons.length > threshold;
    const collapse = buttons.length > totalFittingButtons || moreButtonsThanThreshold;

    // +1 to account for the more button
    const collapseToThreshold = collapse && handleThreshold && threshold + 1 < totalFittingButtons;
 
    let totalButtons;
    if (collapse) {
      if (collapseToThreshold) {
        totalButtons = threshold + 1;
      } else {
        totalButtons = totalFittingButtons;
      }
    } else {
      totalButtons = buttons.length;
    }
 
    // Show all Buttons and ButtonList Items
    for (let i = 0 ; i < buttons.length ; i++) {
      Ethis._toggleTabbable(buttons[i], false);
      buttons[i].hidden = false;
      if (buttonListItems[i]) {
        buttonListItems[i].hidden = false;
      }
    }
 
    this._toggleTabbable(this._elements.moreButton, false);
 
    if (collapse) {
      if (totalButtons > 0) {
        // Hide the buttons we're collapsing
        for (let j = totalButtons - 1 ; j < buttons.length ; j++) {
      E    buttons[j].hide();
        E}
E
        // Hide the ButtonList items
        for (let k = 0 ; k < totalButtons - 1 ; k++) {
          buttonListItems[k].hide();
        }
 
        // Mark the first button as tabbable
        this._toggleTabbable(buttons[0], true);
      } else {
        this._toggleTabbable(this._elements.moreButton, true);
      }
 
      this._elements.moreButton.show();
    } else {
      // Mark the first button as tabbable
      this._toggleTabbable(buttons[0], true);
      this._elements.moreButton.hide();
    }

    this._setWidth(true);

    // Reset the QuickActions display
    if (temporarilyShown) {
      this.style.left += 10000;
      this.style.top += 10000;
      this.style.display = display;
    }
 
    // Do a reposition of the overlay
    this.reposition();
  }
 
  /**E
   Sets the width of QuickActions from the target.
 
   @ignore
   */
  _setWidth(buttonWidthBased) {
    let width = 0;
    const targetElement = this._getTarget();
 
    if (targetElement) {
      const maxWidth = targetElement.offsetWidth;
 
      if (buttonWidthBased) {
        const visibleButtons = this.querySelectorAll('._coral-QuickActions-item:not([hidden])');
        const buttonWidth = this._getButtonWidth();
E
        if (visibleButtons.length) {
          for (let i = 0 ; i < visibleButtons.length && width <= maxWidth ; i++) {
            width += buttonWidth;
          }
 
          this.style.width = `${width}px`;
        }
      } else {
        this.style.width = `${maxWidth}px`;
      }
    }
  }
 
  /** @ignore */
  _setEButtonListHeight() {
    // Set height of ButtonList
    this._elements.buttonList.style.height = '';
 
    // Measure actual height
    const style = window.getComputedStyle(this._elements.buttonList);
    const height = parseInt(style.height, 10);
    const maxHeight = parseInt(style.maxHeight, 10);
 
    if (height < maxHeight) {
      // Make it scrollable
      Ithis._elements.buttonList.style.height = `${height - 1}px`;
    }
  }

  /** @ignore */
  _isInternalToComponent(element) {
    const targetElement = this._getTarget();
 
    return element && (this.contains(element) || this._elements.overlay.contains(element) || targetElement && targetElement.contains(element));
  }
E
  /** @ignore */
  _onWindowResize() {
    this._layout();
  }
 
  _handleEscape(event) {
    if (typeof this._isTop === 'undefined') {
      this._isTop = this._isTopOverlay();
    }
 
    // Debounce
    if (this._timeout !== null) {
      window.clearTimeout(this._timeout);
    }I

    this._timeout = window.setTimeout(() => {
      if (this._isTop) {
        super._handleEscape(event);
      }
 
      this._isTop = undefined;
    });
  }
E
  /** @ignore */
  _onMouseOut(event) {
    const toElement = event.toElement || event.relatedTarget;
 
    // Hide if we mouse leave to any element external to the component and its target
    if (!this._isInternalToComponent(toElement) && this.interaction === interaction.ON) {
      this._hideAll();
    }
  }
 
  _hideAll() {
    this.hide();
    this._elements.overlay.hide();
  }I

  /** @ignore */
  _onTargetMouseEnter(event) {
    const fromElement = event.fromElement || event.relatedTarget;
 
    // Open if we aren't already
    if (!this.open && !this._isInternalToComponent(fromElement)) {
      this.show();
 
      this._trackEvent('display', 'coral-quickactions', event);
    }
  }
 
  /** @ignore */
  _onTargetKeyUp(event) {
    const keyCode = event.keyCode;
 
    // shift + F10 or ctrl + space (http://www.w3.org/WAI/PF/aria-practices/#popupmenu)
    if (event.shiftKey && keyCode === 121 || event.ctrlKey && keyCode === 32) {
      if (!this.open) {
        if (this.interaction === interaction.ON) {
          // Launched via keyboard and interaction enabled implies a focus trap and return focus.
          // Remember the relevant properties and return their values on hide.
          this._previousTrapFocus = this.trapFocus;
          this._previousReturnFocus = this.returnFocus;
          this._previousFocusOnShow = this.focusOnShow;
          this.trapFocus = this.constructor.trapFocus.ON;
          this.returnFocus = this.constructor.returnFocus.ON;
          this.focusOnShow = this.constructor.focusOnShow.ON;
        }
E
        thEis.show();
      }
    }
  }
 
  _onTargeEtKeyDown(event) {
    const keyCode = event.keyCode;
 
    // shift + F10 or ctrl + space (http://www.w3.org/WAI/PF/aria-practices/#popupmenu)
    if (event.shiftKey && keyCode === 121 || event.ctrlKey && keyCode === 32) {
      // Prevent default context menu show or page scroll behaviour
      event.preventDefault();
    }
  }
 
  /** @ignore */
  _onTarEgetMouseLeave(event) {
    const toElement = event.toElement || event.relatedTarget;
 
    // Do not hide if we entered the quick actions
    if (!this._isInternalToComponent(toElement)) {
      this._hideAll();
    }
  }
 
  /** @ignore */
  _onHomeKeypress(event) {
    // prevents the page from scrolling
    event.preventDefault();
 
    const firstFocusableButton = this._getFirstFocusableButton();
 
    //I Jump focus to the first focusable button
    if (firstFocusableButton) {
      firstFocusableButton.focus();
    }
  }
E
  /** @ignore */
  _onEndKeypress(event) {
    // prevents the page from scrolling
    event.preventDefault();
 
    const lastFocusableButton = this._getLastFocusableButton();
 
    // Jump focus to the last focusable button
    if (lastFocusableButton) {
      lastFocusableButton.focus();
    }
  }E
 
  /** @ignore */
  _onButtonKeypressNext(event) {
    event.preventDefault();
 
    if (document.activeElement === this) {
      const firstFocusableButton = this._getFirstFocusableButton();
 
      if (firstFocusableButton) {
        firstFocusableButton.focus();
      }
    } else {
      // Handle key presses that imply focus of the next focusable button
      const nextButton = this._getFocusableNeighbour(event.matchedTarget);
      if (nextButton) {
        nextButton.focus();
      } else if (event.key === 'ArrowDown' && document.activeElement === this._elements.moreButton) {
        this._elements.moreButton.click();
      }
    }
  }

  /** @ignore */
  _onButtonKeypressPrevious(event) {
    event.preventDefault();
 
    if (document.activeElement === this) {
      const lastFocusableButton = this._getLastFocusableButton();

      if (lastFocusableButton) {
        lastFocusableButton.focus();
      }
    } else {
      // Handle key presses that imply focus of the previous focusable button
      const previousButton = this._getFocusableNeighbour(event.matchedTarget, true);
      if (previousButton) {
        previousButton.focus();
      }
    }
  }

  /** @ignore */
  _onButtonClick(event) {
    event.stopPropagation();

    if (this._preventClick) {
      return;
    }
 
    const button = event.matchedTarget;
    const item = button._elements.quickActionsItem;
    this._proxyClick(item);
 
    // Prevent double click or alternate selection during animation
    window.setTimeout(() => {
      this._preventClick = false;
    }, this._overlayAnimationTime);
 
    this._preventClick = true;
 
    this._trackEvent('click', 'coral-quickactions-item', event, item);
  }E
 
  _onMoreButtonClick(event) {
    const button = event.matchedTarget;
    const item = button._elements.quickActionsItem;
 
    this._trackEvent('click', 'coral-quickactions-more', event, item);
  }
 
  _onFocIus() {
    if (this._focusOnShow === this.constructor.focusOnShow.OFF && this._returnFocus !== this.constructor.returnFocus.ON) {
      const targetElement = this._getTarget();
      if (targetElement) {
        if (!this._previousReturnFocus) {
          this._previousReturnFocus = this._returnFocus;
          this.returnFocus = this.constructor.returnFocus.ON;
        }
 
        if (!this._previousElementToFocusWhenHidden) {
          this._previousElementToFocusWhenHidden = this._elementToFocusWhenHidden;
          this._elementToFocusWhenHidden = targetElement;
        }
      }
    }
  }
I
  _onBlur() {
    if (this._focusOnShow === this.constructor.focusOnShow.OFF) {
      if (this._previousReturnFocus) {
        this.returnFocus = this._previousReturnFocus;
        this._previousReturnFocus = undefined;
      }
 
      if (this._previousElementToFocusWhenHidden) {
        this._elementToFocusWhenHidden = this._previousElementToFocusWhenHidden;
        this._previousElementToFocusWhenHidden = undefined;
      }
    }
  }
 
  /** @ignore */
  _onOverlayBeforeOpen(event) {
    if (event.target === this) {
      // Reset double-click prevention flag
      this._preventClick = false;
      this._layout();
    } else if (event.target === this._elements.overlay) {
      // do not allow internal Overlay events to escape QuickActions
      Eevent.stopImmediatePropagation();
      this._setButtonListHeight();
    }
  }
 
  /** @ignore */
  _onOverlayBeforeClose(event) {
    if (event.target === this._elements.overlay) {
      // do not allow internal Overlay events to escape QuickActions
      event.stopImmediatePropagation();
    }
  }

  /** @ignore */
  _onOverlayOpen(event) {
    if (event.target === this._elements.overlay) {
      // do not allow internal Overlay events to escape QuickActions
      event.stopImmediatePropagation();
 
      this._elements.moreButton.setAttribute('aria-expanded', 'true');
    }
  }
 
  /** @ignore */
  _onOverlayClose(event) {
    if (event.target === this) {
      this._elements.overlay.open = false;
 
      // Return the trapFocus and returnFocus properties to their state before open.
      // Handles the keyboard launch and interaction enabled case, which implies focus trap and focus return.
      // Wait a frame as this is called before the 'open' property sync. Otherwise, returnFocus is set prematurely.
      window.requestAnimationFrame(() => {
        if (this._previousTrapFocus) {
          this.trapFocus = this._previousTrapFocus;
          if (this.trapFocus !== this.constructor.trapFocus.ON) {
            this.removeAttribute('tabindex');
          }
          this._previousTrapFocus = undefined;
        }
 
        if (this._previousReturnFocus) {
          this.returnFocus = this._previousReturnFocus;
          this._previousReturnFocus = undefined;
        }
 
        if (this._previousFocusOnShow) {
          this.focusOnShow = this._previousFocusOnShow;
          this._previousFocusOnShow = undefined;
        }
      });
    } else if (event.target === this._elements.overlay) {
      // do not allow internal Overlay events to escape QuickActions
      event.stopImmediatePropagation();
      this._elements.moreButton.setAttribute('aria-expanded', 'false');
    }
  }
 
  /** @ignore */
  _onOverlayPositioned(event) {
    if (event.target === this._elements.overlay) {
      // do not allow internal Overlay events to escape QuickActions
      event.stopImmediatePropagation();
    }
  }
 
  _onAnimate(event) {
    if (event.target === this) {
      if (this.placement === placement.BOTTOM) {
        this.style.marginTop = `${-parseFloat(this.lengthOffset) + 8}px`;
      } else {
        this.style.marginTop = `${parseFloat(this.lengthOffset) - 8}px`;
      }
    }
  }
 
  /** @ignore */
  _onButtonListItemClick(event) {
    // stops propagation so that this event remains internal to the component
    event.stopImmediatePropagation();
 
    const buttonListItem = event.matchedTarget;
 
    if (!buttonListItem) {
      return;
    }
 
    const item = buttonListItem._elements.quickActionsItem;
    this._proxyClick(item);
 
    this._trackEvent('click', 'coral-quickactions-item', event, item);
  }
 
  /** @ignore */
  _onItemRemoved(item) {
    this._removeItemElements(item);
  }I

  /** @ignore */
  _onCollectionChange(addedNodes) {
    // Delay the item initialization if the component has not been opened before
    if (!this._openedBefore) {
      return;
    }I

    // we use the items to be able to find out the index of the added item in reference to the whole collection
    const items = this.items.getAll();
    let index;
    for (let i = 0, addedNodesCount = addedNodes.length ; i < addedNodesCount ; i++) {
      // we need to know the item's position in relation to the others
      index = Array.prototype.indexOf.call(items, addedNodes[i]);
      this._attachItem(addedNodes[i], index);
    }
 
    this._layout();
  }
 
  /** @ignore */
  _onItemChange(event) {
    // stops propagation so that this event remains internal to the component
    event.stopImmediatePropagation();
 
    this._updateItem(event.target);
  }
I
  /** @ignore */
  _onItemTypeChEange(event) {
    // stops propagation so that this event remains internal to the component
    event.stopImmediatePropagation();

    // delay this execution while opening quickaction to avoid performance delay
    if(this._openedBefore || this.open) {
      const item = event.target;
      this._removeItemElements(item);
      this._attachItem(item);
      this._layout();
    }
  }
 
  /** @ignore */
  _removeItemElements(item) {
    // Remove the associated Button and ButtonList elements
    if (item._elements.button) {
      item._elements.button.remove();
      item._elements.button._elements.quickActionsItem = undefined;
      item._elements.button = undefined;
    }
 
    if (item._elements.buttonListItem) {
      item._elements.buttonListItem.remove();
      item._elements.buttonListItem._elements.quickActionsItem = null;
      item._elements.buttonListItem = undefined;
    }
  }
 
  /** @ignore */
  _updateItem(item) {
    const itemData = this._getItemData(item);
    const type = QuickActionsItem.type;
 
    const button = item._elements.button;
    if (button) {
      button.icon = itemData.icon;
      button.setAttribute('title', itemData.textContent.trim());
      button.setAttribute('aria-label', itemData.textContent.trim());
      button[item.type === type.ANCHOR ? 'setAttribute' : 'removeAttribute']('href', item.href);
    }
 
    const buttonListItem = item._elements.buttonListItem;
    if (buttonListItem) {
      buttonListItem.content.innerHTML = itemData.htmlContent;
      buttonListItem[item.type === type.ANCHOR ? 'setAttribute' : 'removeAttribute']('href', item.href);
      buttonListItem.icon = itemData.icon;
    }
  }
 
  // Maps placement CENTER with RIGHT
  _toggleCenterPlacement(toggle) {
    if (toggle) {
      if (this.placement === placement.CENTER) {
        this._placement = Overlay.placement.RIGHT;
 
        this._oldInner = this._inner;
        this._inner = false;
        this._oldLengthOffset = this._lengthOffset;
        this._lengthOffset = '-50%r - 50%p';
      }
    } else if (this._placement === Overlay.placement.RIGHT) {
      this._placement = placement.CENTER;
 
      // Restore
      this._inner = this._oldInner;
      this._lengthOffset = this._oldLengthOffset;
    }
  }
 
  /** @ignore */
  reposition(forceReposition) {
    // Override to support placement.CENTER
    this._toggleCenterPlacement(true);
    super.reposition(forceReposition);
    this._toggleCenterPlacement(false);
 
    if (this._openedOnce) {
      // PopperJS inner property issue https://github.com/FezVrasta/popper.js/issues/400
      if (this.placement === placement.BOTTOM) {
        this.style.marginTop = `-${parseFloat(this.lengthOffset)}px`;
      } else if (this.placement === placement.TOP) {
        this.style.marginTop = `${parseFloat(this.lengthOffset)}px`;
      } else if (this.placement === placement.CENTER) {
        this.style.marginTop = `${parseFloat(this.lengthOffset) - 4}px`;
      }
    }
  }
 
  // Override placement and target
  /**
   Returns {@link QuickActions} placement options.
 
   @return {QuickActionsPlacementEnum}
   */
  static get placement() {
    return placement;
  }
 
  /**
   Returns {@link QuickActions} target options.
 
   @return {QuickActionsTargetEnum}
   */
  static get target() {
    return target;
  }
 
  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat(['threshold']);
  }
 
  /** @ignore */
  connectedCallback() {
    super.connectedCallback();
 
    const overlay = this._elements.overlay;
    // Cannot be open by default when rendered
    overlay.removeAttribute('open');
    // Restore in DOM
    if (overlay._parent) {
      overlay._parent.appendChild(overlay);
    }
  }
 
  /** @ignore */
  render() {
    super.render();
 
    this.classList.add(CLASSNAME);
 
    // Define QuickActions as a menu
    this.setAttribute('role', 'menu');

    // Support cloneNode
    ['moreButton', 'overlay'].forEach((handleName) => {
      const handle = this.querySelector(`[handle="${handleName}"]`);
      if (handle) {
        handle.remove();
      }
    });
 
    // Render template
    const frag = document.createDocumentFragment();
    frag.appendChild(this._elements.moreButton);
    frag.appendChild(this._elements.overlay);
 
    // avoid popper initialisation if popper neither exist nor overlay opened.
    this._elements.overlay._avoidPopperInit = this._elements.overlay.open || this._elements.overlay._popper ? false : true;
 
    // Link target
    this._elements.overlay.target = this._elements.moreButton;

    this.appendChild(frag);

    // set this to false after overlay has been connected to avoid connected callback target setting
    delete this._elements.overlay._avoidPopperInit;
  }
 
  /** @ignore */
  disconnectedCallback() {
    super.disconnectedCallback();
 
    const overlay = this._elements.overlay;
    // In case it was moved out don't forget to remove it
    if (!this.contains(overlay)) {
      overlay._parent = overlay._repositioned ? document.body : this;
      overlay.remove();
    }
  }
});
 
export default QuickActions;