All files / coral-component-buttongroup/src/scripts ButtonGroup.js

95.35% Statements 287/301
90.34% Branches 187/207
97.96% Functions 48/49
95.35% Lines 287/301

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                                                                                2x             2x                 2x 1790x   1790x     2x                   2x 2x   2x           286x   286x   286x 286x   286x   286x   286x                             286x   286x                 2x               12x               24x   24x   24x           24x   10x   10x     10x 6x       10x     10x 6x   14x   12x   12x     12x               62x 62x 62x     62x   186x 186x               25x 25x 25x     25x   25x   25x   25x   75x 75x   75x   9x 66x 66x                 75x               4x 4x 4x   4x 4x 2x   2x       4x 4x       4x               8x 8x 8x   8x 2x 2x           8x 8x 2x     8x               2x 2x   2x   2x 2x       2x               2x 2x   2x   2x 2x       2x               16x 16x                 1696x   1696x 1432x     1696x 1122x 606x 606x   516x     1122x   574x     1696x 1696x   1696x     1696x 606x     606x 6x                   722x 722x 722x   722x   48x   48x 2x         722x 552x 552x                 524x             578x 578x 578x   578x 280x     298x               530x 530x   530x 386x                               1966x 1966x   1966x   1966x 838x 220x     838x 470x     838x 198x   1128x 1128x 156x     1128x 1108x 682x     1108x 372x     20x 20x         1966x 1962x             80x     80x   240x   240x               236x 140x   140x   194x     194x                 2928x 574x       2354x 1190x     1164x 1164x   1164x 346x       1164x   1164x     1164x               122x     122x   354x 354x 354x   354x 10x       354x 18x 18x                   346x 346x 346x 346x   346x 186x 160x 160x       346x   346x   1038x         346x 1038x 1038x 1038x 1038x   1038x 1038x                       990x   650x   650x   650x   136x   136x 134x     514x   46x   46x   46x 92x 46x                               236x   236x   236x 76x       236x   236x   236x 1412x   1412x   1392x     20x         236x   236x     236x           2991x 286x                       2991x                         14093x     468x 468x   468x         468x   468x 186x   186x       186x 282x 160x   160x   122x   122x                           36x     56x   56x                       120x     156x 98x       58x                     231x 140x     91x 91x                       103x                   58x   58x   58x 76x     58x     24x   22x 2x       22x                           1850x     34x   34x   34x 34x   34x 102x   34x                         3480x     10x   10x   10x   10x   10x 30x 30x     10x                  
/**
 * 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 {BaseFormField} from '../../../coral-base-formfield';
import {Button} from '../../../coral-component-button';
import {SelectableCollection} from '../../../coral-collection';
import base from '../templates/base';
import {transform, validate, commons} from '../../../coral-utils';
import {Decorator} from '../../../coral-decorator';
 
/**
 Enumeration for {@link ButtonGroup} selection options.
 
 @typedef {Object} ButtonGroupSelectionModeEnum
 
 @property {String} NONE
 None is default, selection of buttons doesn't happen based on click.
 @property {String} SINGLE
 Single selection mode, button group behaves like radio input elements.
 @property {String} MULTIPLE
 Multiple selection mode, button group behaves like checkbox input elements.
 */
const selectionMode = {
  NONE: 'none',
  SINGLE: 'single',
  MULTIPLE: 'multiple'
};
 
/** @const Selector used to recognized an item of the ButtonGroup */
const ITEM_SELECTOR = 'button[is="coral-button"]';
 
/**
 Extracts the value from the item in case no explicit value was provided.
 @param {HTMLElement} item
 the item whose value will be extracted.
 @returns {String} the value that will be submitted for this item.
 @private
 */
const itemValueFromDOM = function (item) {
  const attr = item.getAttribute('value');
  // checking explicitely for null allows to differenciate between non set values and empty strings
  return attr !== null ? attr : item.textContent.replace(/\s{2,}/g, ' ').trim();
};
 
const CLASSNAME = '_coral-ButtonGroup';
 
/**
 @class Coral.ButtonGroup
 @classdesc A ButtonGroup component that can be used as a selection form field.
 @htmltag coral-buttongroup
 @extends {HTMLElement}
 @extends {BaseComponent}
 @extends {BaseFormField}
 */
const ButtonGroup = Decorator(class extends BaseFormField(BaseComponent(HTMLElement)) {
  /** @ignore */
  constructor() {
    super();
 
    // Store template
    this._elements = {};
    base.call(this._elements);
 
    // Pre-define labellable element
    this._labellableElement = this;
 
    // save initial selection (used for reset)
    this._initalSelectedValues = [];
 
    // Attach events
    this._delegateEvents(commons.extend(this._events, {
      'click button[is="coral-button"]': '_onButtonClick',
 
      'capture:focus button[is="coral-button"]': '_onButtonFocus',
      'capture:blur button[is="coral-button"]': '_onButtonBlur',
 
      'key:up button[is="coral-button"]': '_onButtonKeyUpLeft',
      'key:left button[is="coral-button"]': '_onButtonKeyUpLeft',
      'key:down button[is="coral-button"]': '_onButtonKeyDownRight',
      'key:right button[is="coral-button"]': '_onButtonKeyDownRight',
      'key:home button[is="coral-button"]': '_onButtonKeyHome',
      'key:end button[is="coral-button"]': '_onButtonKeyEnd',
 
      'coral-button:_valuechanged button[is="coral-button"]': '_onButtonValueChanged',
      'coral-button:_selectedchanged button[is="coral-button"]': '_onButtonSelectedChanged'
    }));
 
    // Init the mutation observer but we don't handle the initial items in the constructor
    this.items._startHandlingItems(true);
  }
 
  /**
   The Collection Interface that allows interacting with the items that the component contains.
 
   @type {SelectableCollection}
   @readonly
   */
  get items() {
    // we do lazy initialization of the collection
    if (!this._items) {
      this._items = new SelectableCollection({
        host: this,
        itemBaseTagName: 'button',
        itemTagName: 'coral-button',
        itemSelector: ITEM_SELECTOR,
        onlyHandleChildren: true,
        onItemAdded: this._onItemAdded,
        onItemRemoved: this._onItemRemoved,
        onCollectionChange: this._onCollectionChange
      });
    }
 
    return this._items;
  }
 
  /**
   Selection mode of Button group
 
   @type {String}
   @default ButtonGroupSelectionModeEnum.NONE
   @htmlattribute selectionmode
   @htmlattributereflected
   */
  get selectionMode() {
    return this._selectionMode || selectionMode.NONE;
  }
 
  set selectionMode(value) {
    vaIlue = transform.string(value).toLowerCase();
    this._selectionMode = validate.enumeration(selectionMode)(value) && value || selectionMode.NONE;
    this._reflectAttribute('selectionmode', this._selectionMode);

    // update select element if multiple
    // this is required while appplying default selection
    // if selection mode is single first elem gets selected but for multiple its not
    this._elements.nativeSelect.multiple = this._selectionMode === selectionMode.MULTIPLE;
 
    // Sync
    if (this._selectionMode === selectionMode.SINGLE) {
      this.setAttribute('role', 'radiogroup');
 
      // makes sure the internal options are properly initialized
      this._syncItemOptions();
 
      // we make sure the selection is valid by explicitly finding a candidate or making sure just 1 item is
      // selected
      this._validateSelection();
    } else if (this._selectionMode === selectionMode.MULTIPLE) {
      this.setAttribute('role', 'group');
 
      // makes sure the internal options are properly initialized
      this._syncItemOptions();
    } else {
      this.setAttribute('role', 'group');
 
      this._removeItemOptions();
    }
  }
 
  /**
   Name used to submit the data in a form.
   @type {String}
   @default ""
   @htmlattribute name
   @htmlattributereflected
   */
  get name() {
    return this._elements.nativeSelect.name;
  }
 
  set name(value) {
    this._reflectAttribute('name', value);
 
    this._elements.nativeSelect.name = value;
  }
 
  /**
   This field's current value.
   @type {String}
   @default ""
   @htmlattribute value
   */
  get value() {
    return this._elements.nativeSelect.value;
  }
 
  set value(value) {
    if (this.selectionMode === selectionMode.NONE) {
      return;
    }
 
    // we proceed to select the provided value
    this._selectItemByValue([value]);
  }
 
  /**
   Returns an Array containing the selected buttons.
 
   @type {Array.<HTMLElement>}
   @readonly
   */
  get selectedItems() {
    if (this.seElectionMode === selectionMode.MULTIPLE) {
      return this.items._getAllSelected();
    }
 
    const item = this.selectedItem;
    return item ? [item] : [];
  }

  /**
   Returns the first selected button in the Button Group. The value <code>null</code> is returned if no button is
   selected.
 
   @type {HTMLElement}
   @readonly
   */
  get selectedItem() {
    return this.selectionMode === selectionMode.MULTIPLE ?
      this.items._getFirstSelected() :
      this.items._getLastSelected();
  }
 
  /**
   Current selected values as submitted during form submission.
 
   @type {Array.<String>}
   */
  get values() {
    const values = [];
 
    // uses the nativeSelect since it holds the truth of what will be submitted with the form
    coEnst selectedOptions = this._elements.nativeSelect.querySelectorAll(':checked');
    for I(let i = 0, selectedOptionsCount = selectedOptions.length ; i < selectedOptionsCount ; i++) {
      values.push(selectedOptions[i].value);
    }
 
    return values;
  }
 
  set values(values) {
    if (Array.isArray(values) && this.selectionMode !== selectionMode.NONE) {
      // just keeps the first value if selectionMode is not multiple
      if (this.selectionMode !== selectionMode.MULTIPLE && values.length > 1) {
        values = [values[0]];
      }
 
      // we proceed to select the provided values
      this._selectItemByValue(values);
    }
  }E
 
  /**
   Whether this field is disabled or not.
   @type {Boolean}
   @default false
   @htmlattribute disabled
   @htEmlattributereflected
   */
  get disabled() {
    return this._disabled || false;
  }
 
  set disabled(value) {
    this._disabled = transform.booleanAttr(value);
    this._reflectAttribute('disabled', this._disabled);
 
    const isDisabled = this.disabled || this.readOnly;
    this._elements.nativeSelect.disabled = isDisabled;
    // Also update for all the items the disabled property so it matches the native select.
    this.items.getAll().forEach((item) => {
      item.disabled = isDisabled;
    });
    this[isDisabled ? 'setAttribute' : 'removeAttribute']('aria-disabled', isDisabled);
  }
E
  /**I
   Whether this field is readOnly or not. Indicating that the user cannot modify the value of the control.
   @type {Boolean}
   @default false
   @htmlattribute readonly
   @htmlattributereflected
   */
  get readOnly() {
    return this._readOnly || false;
  }
 
  set readOnly(value) {
    this._readOnly = transform.booleanAttr(value);
    this._reflectAttribute('readonly', this._readOnly);
 
    this._elements.nativeSelect.disabled = this.readOnly || this.disabled;
    // Also update for all the items the disabled property so it matches the native select.
    thEis.items.getAll().forEach((item) => {
      itIem.disabled = this.disabled || this.readOnly && !item.hasAttribute('selected');
      item[this.readOnly ? 'setAttribute' : 'removeAttribute']('aria-disabled', true);
    });
    // aria-readonly is not permitted on elements with role="radiogroup" or role="group"
    this.removeAttribute('aria-readonly');
  }
 
  /**
   Whether this field is required or not.
   @type {Boolean}
   @default false
   @htmlattribute required
   @htEmlattributereflected
   */
  get required() {
    return this._required || false;
  }
 
  set required(value) {
    this._required = transform.booleanAttr(value);
    this._reflectAttribute('required', this._required);
 
    this._elements.nativeSelect.required = this.required;
    // aria-required is permitted on elements with role="radiogroup" but not with role="group"
    if (this.selectionMode !== selectionMode.SINGLE) {
      this.removeAttribute('aria-required');
    }
  }
 
  /**
   Inherited from {@link BaseFormField#labelledBy}.
   */
  get labelledBy() {
    return super.labelledBy;
  }
 
  set labelledBy(value) {
    super.labelledBy = value;
    this._elements.nativeSelect.setAttribute('aria-labelledby', this.labelledBy);
  }
 
  /**
   Inherited from {@link BaseFormField#reset}.
   */
  reset() {
    // reset the values to the initial values
    this.values = this._initalSelectedValues;
  }
 
  /** @private */
  _onButtonClick(event) {
    // uses matchTarget to make sure the buttons is handled and not an internal component
    const item = event.matchedTarget;
 
    this._onButtonFocus(event);
 
    if (this.readOnly) {
      event.preventDefault();
      event.stopImmediatePropagation();
      return;
    }
 
    if (this.selectionMode === selectionMode.SINGLE) {
      // prevent event only if selectionMode is not of type none
      event.preventDefault();
 
      // first unselect the other element
      const selectedItems = this.items._getAllSelected();
 
      // we deselect the previously selected item
      if (selectedItems.length !== 0 && selectedItems[0] !== item) {
        this._toggleItemSelection(selectedItems[0], false);
      }
 
      // forces the selection on the clicked item
      this._toggleItemSelection(item, true);
 
      // if the same button was clicked we do not need to trigger an event
      if (selectedItems[0] !== item) {
        this.trigger('change');
      }
    } else if (this.selectionMode === selectionMode.MULTIPLE) {
      // prevent event only if selectionMode is not of type none
      event.preventDefault();
 
      this._toggleItemSelection(item);
 
      // since we toggle the selection we always trigger a change event
      this.trigger('change');
    }
  }
 
  /** @private */
  _onButtonFocus(event) {
    const item = event.matchedTarget;
    const buttons = this.items.getAll();
    const buttonsCount = buttons.length;
 
    let button;
    for (let i = 0 ; i < buttonsCount ; i++) {
      // stores the reference
      button = buttons[i];
      button.setAttribute('tabindex', button === item ? 0 : -1);
    }
  }
 
  /** @private */
  _onButtonBlur(event) {
    const item = event.matchedTarget;
    const buttons = this.items.getAll();
    const buttonsCount = buttons.length;
 
    let button;
    let tabindex;
    const selectedItemsLength = this.selectedItems.length;
    const firstSelectable = this.items._getFirstSelectable();
    let isSelected = false;
    for (let i = 0 ; i < buttonsCount ; i++) {
      // stores the reference
      button = buttons[i];
      isSelected = button.hasAttribute('selected');
      if (this.selectionMode === selectionMode.SINGLE) {
        // selected item should be tabbable
        tabindex = isSelected ? 0 : -1;
      } else if (this.selectionMode === selectionMode.MULTIPLE) {
        tabindex =
          // if no items are selected, first item should be tabbable
          !selectedItemsLength && i === 0 ||
          // if the element losing focus is selected, it should be tabbable
          isSelected && button === item ||
          // if the element losing focus is not selected, the last selected item should be tabbable
          !item.hasAttribute('selected') &&
          button === (this.selectedItems[selectedItemsLength - 1] || firstSelectable) ? 0 : -1;
      } else {
        // first item should be tabbable
        tabindex = button === firstSelectable ? 0 : -1;
      }
      button.setAttribute('tabindex', tabindex);
    }
  }
 
  /** @private */
  _onButtonKeyUpLeft(event) {
    event.preventDefault();
 
    const item = event.matchedTarget;
    let button = item.previousElementSibling;
E
    // skip disabled items
    while (!button || (button.disabled || button.nodeName !== 'BUTTON')) {
      if (!button) {
        button = this.items._getLastSelectable();
      } else {
        button = button.previousElementSibling;
      }
    }
 
    if (button !== item) {
      if (this.selectionMode === selectionMode.SINGLE) {
        button.click();
      }
      this._setFocusToButton(button);
    }
  }
 
  /** @private */
  _onButtonKeyDownRight(event) {
    event.preventDefault();
 
    const item = event.matchedTarget;
    let button = item.nextElementSibling;
 
    // skip disabled items
    while (!button || (button.disabled || button.nodeName !== 'BUTTON')) {
      if (!button) {
        button = this.items._getFirstSelectable();
      } else {
        button = button.nextElementSibling;
      }
    }
 
    if (button !== item) {
      if (this.selectionMode === selectionMode.SINGLE) {
        button.click();
      }
      this._setFocusToButton(button);
    }
  }
 
  /** @private */
  _onButtonKeyHome(event) {
    event.preventDefault();
 
    const item = event.matchedTarget;
    const button = this.items._getFirstSelectable();
 
    if (button !== item) {
      if (this.selectionMode === selectionMode.SINGLE) {
        button.click();
      }
      this._setFocusToButton(button);
    }
  }
 
  /** @private */
  _onButtonKeyEnd(event) {
    event.preventDefault();
 
    const item = event.matchedTarget;
    const button = this.items._getLastSelectable();
 
    if (button !== item) {
      if (this.selectionMode === selectionMode.SINGLE) {
        button.click();
      }
      this._setFocusToButton(button);
    }
  }
 
  /** @private */
  _setFocusToButton(button) {
    if (button) {
      button.focus();
    }
  }
 
  /** @private */
  _onItemAdded(item) {
    // Store variant to be able to reset it when item is removed
    item._initialVariant = item._initialVariant || item.variant;
 
    // Force action variant
    if (!(item.variant === Button.variant.ACTION || item.variant === Button.variant.QUIET_ACTION)) {
      item.variant = item.variant === Button.variant.QUIET ? Button.variant.QUIET_ACTION : Button.variant.ACTION;
    }
 
    if (this.selectionMode !== selectionMode.NONE) {
      if (this.selectionMode === selectionMode.SINGLE) {
        item.setAttribute('role', 'radio');
        item.setAttribute('tabindex', item.hasAttribute('selected') ? 0 : -1);
      } else {
        item.setAttribute('role', 'checkbox');
      }
      item.setAttribute('aria-checked', item.hasAttribute('selected'));
    } else {
      item.removeAttribute('role');
    }
 
    item.disabled = this.disabled || this.readOnly && !item.hasAttribute('selected');
 
    item[this.readOnly ? 'setAttribute' : 'removeAttribute']('aria-disabled', true);
 
    this._addItemOption(item);
 
    // Handle the case where we might have multiple items selected while single selection mode is on
    if (this.selectionMode === selectionMode.SINGLE) {
      const selectedItems = this.items._getAllSelected();
      // The last added item will stay selected
      if (selectedItems.length > 1 && item.hasAttribute('selected')) {
        item.removeAttribute('selected');
      }
    }
  }
 
  /** @private */
  _onItemRemoved(item) {
    // Restore variant
    item.variant = item._initialVariant;
    item._initialVariant = undefined;
    item.removeAttribute('role');
E
    if (!item.parentNode) {
      // Remove the item from the initial selected values
      const index = this._initalSelectedValues.indexOf(item.value);
      if (index !== -1) {
        this._initalSelectedValues.splice(index, 1);
      }
    }
 
    // delete option
    if (item.option) {
      item.option.parentNode.removeChild(item.option);
      item.option = undefined;
    }
  }
 
  /** @private */
  _onCollectionChange() {
    // we need to make sure that the state of the selectionMode is valid
    this._validateSelection();
  }E
 
  /** @private */
  _onButtonSelectedChanged(event) {
    event.stopImmediatePropagation();
 
    const button = event.target;
    const isSelected = button.hasAttribute('selected');
 
    // when in single mode, we need to make sure the current selection is valid
    if (this.selectionMode === selectionMode.SINGLE) {
      this._validateSelection(isSelected ? button : null);
    } else {
      // we simply toggle the selection
      this._toggleItemSelection(button, isSelected);
    }
  }
 
  /** @private */
  _onButtonValueChanged(event) {
    event.stopImmediatePropagation();
 
    const button = event.target;
    // Make sure option is attached before setting the value
    if (this.selectionMode !== selectionMode.NONE) {
      button.option.value = itemValueFromDOM(button);
    }
  }
 
  /**
   Toggles the selected state of the item. When <code>selected</code> is provided, it is set as the current state. If
   the value is ommited, then the selected is toggled.
 
   @param {HTMLElement} item
   Item whose selection needs to be updated.
   @param {Boolean} [selected]
   Whether the item is selected. If it is not provided, then it is toggled.
 
   @private
   */
  _toggleItemSelection(item, selected) {
    const ariaCheckedAttr = item.getAttribute('aria-checked');
    const tabIndexAttr = item.getAttribute('tabindex');
 
    // if selected is provided it is used to enforce the selection, otherwise we toggle the current state
    selected = typeof selected !== 'undefined' ? selected : !item.hasAttribute('selected');
 
    // only manipulates the attributes when necessary to avoid unnecessary mutations
    if (selected) {
      if (!item.hasAttribute('selected')) {
        item.setAttribute('selected', '');
      }
 
      if (ariaCheckedAttr !== 'true') {
        item.setAttribute('aria-checked', true);
      }
 
      if (this.selectionMode === selectionMode.SINGLE && tabIndexAttr !== '0') {
        item.setAttribute('tabindex', 0);
      }
    } else if (!selected) {
      if (item.hasAttribute('selected')) {
        item.removeAttribute('selected');
      }
 
      if (this.selectionMode !== selectionMode.NONE) {
        if (ariaCheckedAttr !== 'false') {
          item.setAttribute('aria-checked', false);
        }
 
        if (this.selectionMode === selectionMode.SINGLE && tabIndexAttr !== '-1') {
          item.setAttribute('tabindex', -1);
        }
      } else {
        item.removeAttribute('aria-checked');
        item.removeAttribute('tabindex');
      }
    }
 
    // if element.option is present - absent when selection mode changed to none
    if (item.option) {
      item.option.selected = selected;
    }
  }
 
  _selectItemByValue(values) {
    // queries all the buttons to change their selection state
    const buttons = this.items.getAll();
    let item;
 
    for (let i = 0, buttonsCount = buttons.length ; i < buttonsCount ; i++) {
      // stores the reference
      item = buttons[i];
 
      // if the value is inside the new values array it should be selected
      this._toggleItemSelection(item, values.indexOf(itemValueFromDOM(item)) !== -1);
    }
  }
 
  /** @private */
  _setInitialValues() {
    if (this.selectionMode !== selectionMode.NONE) {
      const selectedItems = this.selectedItems;
      for (let i = 0, selectedItemsCount = selectedItems.length ; i < selectedItemsCount ; i++) {
        // Store _initalSelectedValues for reset
        this._initalSelectedValues.push(selectedItems[i].value);
 
        // Same goes for native select
        this._addItemOption(selectedItems[i]);
      }
    }
  }
 
  /** @private */
  _addItemOption(item) {
    if (this.selectionMode === selectionMode.NONE) {
      return;
    }

    // if already attached return
    if (item.option) {
      return;
    }
 
    const option = document.createElement('option');
    option.value = itemValueFromDOM(item);
 
    if (item.hasAttribute('selected')) {
      option.setAttribute('selected', '');
    }
 
    // add it to DOM. In single selectionMode the first item gets selected automatically
    item.option = option;
    this._elements.nativeSelect.add(option);
 
    // we make sure the options reflect the state of the button
    this._toggleItemSelection(item, item.hasAttribute('selected'));
  }
 
  /** @private */
  _removeItemOptions() {
    // Find all buttons and try attaching corresponding option elem
    const buttons = this.items.getAll();
 
    let item;
    for (let i = 0, buttonsCount = buttons.length ; i < buttonsCount ; i++) {
      // stores the reference
      item = buttons[i];
 
      item.removeAttribute('role');
      item.removeAttribute('aria-checked');
 
      // single we are removing the options, selection must also go away
      if (item.hasAttribute('selected')) {
        this._toggleItemSelection(item, false);
      }
 
      // we clear the related option element
      if (item.option) {
        item.option.parentNode.removeChild(item.option);
        delete item.option;
      }
    }
  }
 
  /** @private */
  _syncItemOptions() {
    // finds all buttons and try attaching corresponding option elem
    const buttons = this.items.getAll();
    const buttonsCount = buttons.length;
    let i = 0;
 
    let role = null;
    if (this.selectionMode === selectionMode.SINGLE) {
      role = 'radio';
    } else if (this.selectionMode === selectionMode.MULTIPLE) {
      role = 'checkbox';
    }
 
    let button;
    let isSelected = false;
 
    for (i ; i < buttonsCount ; i++) {
      // try attaching corresponding input element
      this._addItemOption(buttons[i]);
    }
 
    // We need to set the right state for the native select AFTER all buttons have been added
    // (as we can't disable options while there is only one option attached [at least in FF])
    for (i = buttonsCount - 1 ; i >= 0 ; i--) {
      button = buttons[i];
      isSelected = button.hasAttribute('selected');
      button.option.selected = isSelected;
      button.setAttribute('aria-checked', isSelected);
 
      if (role) {
        button.setAttribute('role', role);
      } else {
        button.removeAttribute('role');
      }
    }
  }
 
  /** @private */
  _validateSelection(item) {
    // when selectionMode = single, we need to force a selection
    if (this.selectionMode === selectionMode.SINGLE) {
      // gets the current selection
      const selection = this.items._getAllSelected();
      const selectionCount = selection.length;
 
      // if no item is currently selected, we need to find a candidate
      if (selectionCount === 0) {
        // gets the first candidate for selection
        const selectable = this.items._getFirstSelectable();
 
        if (selectable) {
          this._toggleItemSelection(selectable, true);
        }
      }
      // more items are selected, so we find a single item and deselect everything else
      else if (selectionCount > 1) {
        // if no item was provided we force the selection on the first item
        item = item || selection[0];
 
        // we make sure the item is selected, this is important to match the options with the selection
        this._toggleItemSelection(item, true);
 
        for (let i = 0 ; i < selectionCount ; i++) {
          if (selection[i] !== item) {
            this._toggleItemSelection(selection[i], false);
          }
        }
      }
    }
  }
 
  /**
   Returns {@link ButtonGroup} selection options.
 
   @return {ButtonGroupSelectionModeEnum}
   */
  static get selectionMode() {
    return selectionMode;
  }
 
  static get _attributePropertyMap() {
    return commons.extend(super._attributePropertyMap, {
      selectionmode: 'selectionMode'
    });
  }
 
  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat([
      'selectionmode',
      'selectionMode'
    ]);
  }
 
  /** @ignore */
  render() {
    super.render();
 
    this.classList.add(CLASSNAME);
 
    // Default reflected attributes
    if (!this._selectionMode) {
      this.selectionMode = selectionMode.NONE;
    }
 
    // Create a fragment
    const frag = document.createDocumentFragment();
 
    // Render the template
    frag.appendChild(this._elements.nativeSelect);
 
    // Clean up
    while (this.firstChild) {
      const child = this.firstChild;
      if (child.nodeType === Node.TEXT_NODE ||
        child.getAttribute('handle') !== 'nativeSelect') {
        // Add non-template elements to the content
        frag.appendChild(child);
      } else {
        // Remove anything else
        this.removeChild(child);
      }
    }
 
    // Append the fragment to the component
    this.appendChild(frag);
 
    // Need to store and set the initially selected values in the native select so that it can reset
    this._setInitialValues();
 
    // Call onItemAdded and onCollectionChange on the existing items
    this.items._startHandlingItems();
  }
});
 
export default ButtonGroup;