All files / coral-component-multifield/src/scripts Multifield.js

94.3% Statements 298/316
80.14% Branches 117/146
94.55% Functions 52/55
94.3% Lines 298/316

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                                                2x 2x 2x 2x 2x                         2x 2x   2x           164x   164x   164x     164x                                     164x   164x     164x       164x     164x     164x 264x 5538x 6204x 6204x   6204x                           164x           164x   164x                 2x                   248x 206x 206x 206x 206x 206x   206x 102x   102x 22x 22x 22x     102x     206x 46x 46x   46x 160x 160x 132x   132x                         178x 178x 178x 308x                 324x                             12x   12x 12x   12x 12x   12x     12x   12x   12x 12x 12x   12x     12x                   12x 12x   12x     12x 12x   12x 6x   6x 2x   4x       12x   12x 6x   6x   6x 6x         12x   12x                     35x   35x 7x     28x   28x 16x 16x   12x         12x         12x 12x 12x                     20x 20x 20x   20x                   21x   21x 21x 21x 21x 13x                       4x 4x   4x       4x 4x 4x 4x   4x 2x     4x 4x                   10x 10x   10x       10x 10x 10x 10x   10x 8x 8x     10x 10x                   4x 4x   4x       4x 4x 4x 4x   4x 2x     4x 4x                   4x 4x   4x       4x 4x 4x 4x   4x 2x     4x 4x                   2x 2x   2x 2x 2x 2x     2x         2x             10x 10x 10x 10x 10x   10x 10x 10x 20x 2x 18x 8x                   10x 10x 10x   10x 10x     10x 20x 10x 10x 10x 10x 10x 10x 10x 10x 10x   10x 8x     10x 2x 2x                     10x 10x 10x 10x 10x 10x 10x 20x 8x 12x 2x     20x 20x 20x   10x 10x 10x 10x           10x 8x 6x     8x 2x       8x 8x         8x   8x                 2x 2x   2x 2x               2x 2x   2x 2x               182x   182x 170x   170x     182x 36x       182x             52x   52x     52x 24x       52x                   394x   394x 122x 272x 8x                     382x 382x 382x 642x 642x 642x     642x 616x                 316x   316x   182x                     182x               160x   160x   160x   160x     160x   160x 148x       160x   160x 146x     160x   160x                                                       2226x 164x                     2226x                           6390x     160x       160x      
/**
 * 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 '../../../coral-component-textfield';
import {BaseComponent} from '../../../coral-base-component';
import MultifieldCollection from './MultifieldCollection';
import {commons, i18n, validate, transform} from '../../../coral-utils';
import {Decorator} from '../../../coral-decorator';
 
const CLASSNAME = '_coral-Multifield';
const IS_DRAGGING_CLASS = 'is-dragging';
const IS_AFTER_CLASS = 'is-after';
const IS_BEFORE_CLASS = 'is-before';
const TEMPLATE_SUPPORT = 'content' in document.createElement('template');
 
/**
 @class Coral.Multifield
 @classdesc A Multifield component that enables adding, reordering, and removing multiple instances of a component.
 Multifield partially supports the <code>template</code> element in IE 11. If adding/removing items in the template
 is required, <code>template.content</code> should be used.
 Child elements can be given a special attribute to enable functionality:
 - <code>[coral-multifield-add]</code>. Click to add an item.
 @htmltag coral-multifield
 @extends {HTMLElement}
 @extends {BaseComponent}
 */
const Multifield = Decorator(class extends BaseComponent(HTMLElement) {
  /** @ignore */
  constructor() {
    super();
 
    this.setAttribute('id', this.id || commons.getUID());
 
    // Attach events
    const events = {
      'coral-dragaction:dragstart coral-multifield-item': '_onDragStart',
      'coral-dragaction:drag coral-multifield-item': '_onDrag',
      'coral-dragaction:dragend coral-multifield-item': '_onDragEnd',
 
      'click [coral-multifield-add]': '_onAddItemClick',
      'click ._coral-Multifield-remove': '_onRemoveItemClick',
      'click [coral-multifield-move]': '_onClickDragHandle',
      'key:up [coral-multifield-move]': '_onMoveItemUp',
      'key:pageup [coral-multifield-move]': '_onMoveItemUp',
      'key:down [coral-multifield-move]': '_onMoveItemDown',
      'key:pagedown [coral-multifield-move]': '_onMoveItemDown',
      'key:home [coral-multifield-move]': '_onMoveItemHome',
      'key:end [coral-multifield-move]': '_onMoveItemEnd',
      'key:esc [coral-multifield-move]': '_onMoveItemEsc',
      'click [coral-multifield-up]': '_onUpClick',
      'click [coral-multifield-down]': '_onDownClick',
      'capture:blur [coral-multifield-move]': '_onBlurDragHandle',
      'change coral-multifield-item-content > input': '_onInputChange'
    };
 
    events[`global:key:escape #${this.id} > [coral-multifield-move]`] = '_onMoveItemEsc';
 
    this._delegateEvents(events);
 
    // Templates
    this._elements = {
      template: this.querySelector(`#${this.id} > template[coral-multifield-template]`) || document.createElement('template')
    };
    this._elements.template.setAttribute('coral-multifield-template', '');
 
    // In case <template> is not supported
    this._handleTemplateSupport(this._elements.template);
 
    // Template support: move nodes added to the <template> to its content fragment
    this._observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        for (let i = 0 ; i < mutation.addedNodes.length ; i++) {
          const addedNode = mutation.addedNodes[i];
          const template = this.template;
 
          if (template.contains(addedNode) && template !== addedNode) {
            // Move the node to the template content
            template.content.appendChild(addedNode);
            // Update all items content with the template content
            this.items.getAll().forEach((item) => {
              this._renderTemplate(item);
            });
            this._updatePosInSet();
          }
        }
      });
    });
 
    // Watch for changes to the template element
    this._Iobserver.observe(this, {
      childList: true,
      subtree: true
    });

    // Init the collection mutation observer
    this.items._startHandlingItems(true);
  }

  /**
   The Collection Interface that allows interacting with the Coral.Multifield items that the component contains.
 
   @type {MultifieldCollection}
   @readonly
   */
  get items() {
    // just init on demand
    if (!this._items) {
      this._items = new MultifieldCollection({
        host: this,
        itemTagName: 'coral-multifield-item',
        // allows multifields to be nested
        itemSelector: ':scope > coral-multifield-item',
        onlyHandleChildren: true,
        onItemAdded: this._onItemAdded,
        onItemRemoved: this._onItemRemoved
      });
    }
    return this._items;
  }
 
  /**
   The Multifield template element. It will be used to render a new item once the element with the attribute
   <code>coral-multifield-add</code> is clicked. It supports the <code>template</code> tag. While specifying the
   template from markup, it should include the <code>coral-multifield-template</code> attribute.
   NOTE: On IE11, only <code>template.content</code> is supported to add/remove elements to the template.
 
   @type {HTMLElement}
   @contentzone
   */
  get template() {
    return this._getContentZone(this._elements.template);
  }
 
  set template(value) {
    this._setContentZone('template', value, {
      handle: 'template',
      tagName: 'template',
      insert: function (template) {
        this.appendChild(template);
      },
      set: function (content) {
        // Additionally add support for template
        this._handleTemplateSupport(content);
      }
    });
  }
 
  /**
   Whether this multifield is readOnly or not. Indicating that the user cannot modify the value of the multifield fields.
   @type {Boolean}
   @default false
   @htmlattribute readonly
   @htmlattributereflected
   */
   get readOnlyE() {
    return this._readOnly || false;
  }
 
  set readOnly(value) {
    value = transform.booleanAttr(value);
    this._readOnly = value;
    this._reflectAttribute('readonly', value);
 
    this.items.getAll().forEach((item) => {
      item[value ? 'setAttribute' : 'removeAttribute']('_readonly', '');
    });
 
    let addBtn = this.querySelector('[coral-multifield-add]');
    if (addBtn) {
      addBtn.disabled = value;
    }
 
  }
 
  /**
    Specifies the minimum number of items multifield should render.
    If component contains less items, remaining items will be added.
 
    @type {Number}
    @default 0
    @htmlattribute min
    @htmlattributereflected
    */
  get Imin() {
    return this._min || 0;
  }

  set min(value) {
    const self = this;
    value = transform.number(value);

    if(value && validate.valueMustChange(self._min, value)) {
      self._min = value;
      self._reflectAttribute('min', value);
      self._validateMinItems();
    }
  }
 
  static get _attributePropertyMap() {
    return commons.extend(super._attributePropertyMap, {
      Ereorderupdown: 'reorderUpDown',
      readonly: 'readOnly'
    });
  }
 
  /**
   Whether this multifield require up and down buttons.
   @type {Boolean}
   @default false
   @htmlattribute reorderupdown
   @htmlattributereflected
   */
  get reorderUpDown() {
    return this._reorderUpDown || false;
  }
 
  set reorderUpDown(value) {
     valueI = transform.booleanAttr(value);
     this._reorderUpDown = value;
     this._reflectAttribute('reorderupdown', value);
  }
 
  /**
   * Validates minimum items required. will add items, if validation fails.
   * @param schedule schedule validation in next frame
   * @ignore
   */
  _validateMinItems(schedule) {
    // only validate when multifield is connected
    if(this._disconnected === false) {
      Econst self = this;
      const items = self.items;
      let currentLength = items.length;
      leEt currentMin = self.min;
      let deletable = true;
 
      if(currentLength <= currentMin) {
        let itemsToBeAdded = currentMin - currentLength;
 
        for(let i = 0; i < itemsToBeAdded; i++) {
          let item = document.createElement('coral-multifield-item');
          items.add(item);
          item._readOnly = this.readOnly;
        }
 
        deletable = !deletable;
      }
 
      if(!schedule) {
        window.cancelAnimationFrame(self._updateItemsDeletableId);
        delete self._updateItemsDeletableId;
        self._updateItemsDeletable(items.getAll(), deletable);
      } else if(!self._updateItemsDeletableId) {
        self._updateItemsDeletableId = window.requestAnimationFrame(() => {
          delete self._updateItemsDeletableId;
          self._updateItemsDeletable(items.getAll(), deletable);
        });E
      }
    }
  }
 
  /**
   * Change the deletable property of passed items to the specified deletable value
   * @ignore
   */
  _updateItemsDeletable(items, deletable) {
    deletable = transform.boolean(deletable);
    items = !Array.isArray(items) ? [items] : items;
 
    items.forEach(function(item) {
      item._deletable = deletable;
    });
  }
 
  /** @ignore */
  _handleTemplateSupport(template) {
    // @polyfill IE
    if (!TEMPLATE_SUPPORT && !template.content) {
      const frag = document.createDocumentFragment();
      while (template.firstChild) {
        frag.appendChild(template.firstChild);
      }
      template.content = frag;
    }
  }
 
  /** @ignore */
  _onAddItemClick(event) {
    if (event.matchedTarget.closest('coral-multifield') === this) {
      this.items.add(document.createElement('coral-multifield-item'));
 
      // Wait for MO to render item template
      window.requestAnimationFrame(() => {
        this.trigger('change');
 
        this._trackEvent('click', 'add item button', event);
 
        // Focus the newly created input if it can receive focus
        var addBtn = event.target;
        const items = this.items.getAll();
        const setsize = items.length;
        const itemToFocus = items[setsize - 1];
        const focusableItem = itemToFocus.querySelector(commons.TABBABLE_ELEMENT_SELECTOR);
 
        if (focusableItem.hasAttribute('disabled')) {
          addBtn.focus();
        } else {
          focusableItem.focus();
        }
      });
    }
  }
 
  /** @ignore */
  _onRemoveItemClick(event) {
    if (event.matchedTarget.closest('coral-multifield') === this) {
      const item = event.matchedTarget.closest('coral-multifield-item');
      if (item) {
        // manage focus when item is removed
        let itemToFocus;
        const items = this.items.getAll();
        const setsize = items.length;
        if (setsize > 1) {
          const itemIndex = items.indexOf(item);
          if (itemIndex === setsize - 1) {
            itemToFocus = items[itemIndex - 1];
          } else {
            itemToFocus = items[itemIndex + 1];
          }
        }
        item.remove();
        if (itemToFocus) {
          itemToFocus._elements.remove.focus();
        } else {
          itemToFocus = this.querySelector('[coral-multifield-add]');
          if (itemToFocus) {
            itemToFocus.focus();
          }
        }
      }
 
      this.trigger('change');
 
      this._trackEvent('click', 'remove item button', event);
    }
  }I

  /**
   * Toggles keyboard accessible dragging of the current multifield item.
   * @ignore
   */
  _toggleItemDragging(multiFieldItem, dragging = false) {
    if (multiFieldItem._dragging === dragging) {
      return;
    }
    multiFieldItem._dragging = dragging;
    if (dragging) {
      this._oldBefore = multiFieldItem.previousElementSibling;
      this._before = multiFieldItem.nextElementSibling;
    } else {
      this.trigger('coral-multifield:beforeitemorder', {
        item: multiFieldItem,
        oldBefore: this._oldBefore,
        before: this._before
      });
      this.trigger('coral-multifield:itemorder', {
        item: multiFieldItem,
        oldBefore: this._oldBefore,
        before: multiFieldItem.nextElementSibling
      });
      this.trigger('change');
      this._oldBefore = null;
      Ithis._before = null;
    }
  }
 
  /**
   * Clicking dragHandle toggles keyboard accessible dragging of the current multifield item.
   * @ignore
   */
  _onClickDragHandle(event) {
    event.preventDefault();
    event.stopPropagation();
    const multiFieldItem = event.matchedTarget.closest('coral-multifield-item');
    this._toggleItemDragging(multiFieldItem, !multiFieldItem._dragging);
  }
 
  /**
   * When the drag handle blurs, cancel dragging, leaving item where it is.
   * @ignore
   */
  _onBlurDragHandle(event) {
    const dragHandle = event.matchedTarget;
    const multiFieldItem = dragHandle.closest('coral-multifield-item');
    commons.nextFrame(() => {
      if (document.activeElement !== dragHandle) {
        this._toggleItemDragging(multiFieldItem, false);
      }
    });
  }
I
  /**
   * Moves multiField item selected for dragging up one index position in the multifield collection.
   * @ignore
   */
  _onMoveItemUp(event) {
    const dragHandle = event.matchedTarget;
    const dragElement = dragHandle.closest('coral-multifield-item');
    if (!dragElement._dragging) {
      return;
    }
    event.preventDefault();
    event.stopPropagation();
    const items = this.items.getAll();
    const dragElementIndex = items.indexOf(dragElement);
    if (dragElementIndex > 0) {
      this.insertBefore(dragElement, dragElement.previousElementSibling);
    }
    dragElement._dragging = true;
    dragHandle.focus();
  }
 
  /**
   * Moves multiField item selected for dragging down one index position in the multifield collection.
   * @ignore
   */
  _onMoveItemDown(event) {
    coInst dragHandle = event.matchedTarget;
    const dragElement = dragHandle.closest('coral-multifield-item');
    if (!dragElement._dragging) {
      return;
    }
    event.preventDefault();
    event.stopPropagation();
    const items = this.items.getAll();
    const dragElementIndex = items.indexOf(dragElement);
    if (dragElementIndex < items.length - 1) {
      const nextElement = dragElement.nextElementSibling;
      this.insertBefore(dragElement, nextElement.nextElementSibling);
    }
    dragElement._dragging = true;
    dragHandle.focus();
  }
 
  /**
   * Moves multiField item selected for dragging to start of multifield collection.
   * @ignore
   */
  _onMoveItemHome(event) {
    const dragHandle = event.matchedTarget;
    let dragElement = dragHandle.closest('coral-multifield-item');
    if (!dragElement._dragging) {
      return;
    }
    evEent.preventDefault();
    event.stopPropagation();
    const items = this.items.getAll();
    const dragElementIndex = items.indexOf(dragElement);
    if (dragElementIndex > 0) {
      this.insertBefore(dragElement, this.items.first());
    }
    dragElement._dragging = true;
    dragHandle.focus();
  }
 
  /**
   * Moves multiField item selected for dragging to end of multifield collection.
   * @ignore
   */
  _onMoveItemEnd(event) {
    const dragHandle = event.matchedTarget;
    let dragElement = dragHandle.closest('coral-multifield-item');
    ifE (!dragElement._dragging) {
      return;
    }
    event.preventDefault();
    event.stopPropagation();
    const items = this.items.getAll();
    const dragElementIndex = items.indexOf(dragElement);
    if (dragElementIndex < items.length - 1) {
      this.insertBefore(dragElement, this.items.last().nextElementSibling);
    }
    dragElement._dragging = true;
    dragHandle.focus();
  }
 
  /**
   * Cancels keyboard drag and drop operation, restoring item to its previous location.
   * @ignore
   */
  _onMoveItemEsc(event) {
    const dragHandle = event.matchedTarget;
    const multiFieldItem = dragHandle.closest('coral-multifield-item');
    if (multiFieldItem._dragging && this._oldBefore && this._before) {
      Eevent.stopPropagation();
      this.insertBefore(multiFieldItem, this._before);
      dragHandle.focus();
    }
    thisE._toggleItemDragging(multiFieldItem, false);
  }
 
  _onInputChange(event) {
    this._trackEvent('change', 'input', event);
  }
 
  /** @ignore */
  _onDragStart(event) {
    if (event.target.closest('coral-multifield') === this) {
      document.body.classList.add('u-coral-closedHand');
 
      const dragElement = event.detail.dragElement;
      const items = this.items.getAll();
      const dragElementIndex = items.indexOf(dragElement);
 
      // Toggle dragging state on multifield item.
      dragElement._dragging = true;
      dragElement.classList.add(IS_DRAGGING_CLASS);
      items.forEach((item, i) => {
        if (i < dragElementIndex) {
          item.classList.add(IS_BEFORE_CLASS);
        } else if (i > dragElementIndex) {
          item.classList.add(IS_AFTER_CLASS);
        }
      });
    }
  }
 
  /** @ignore */
  _onDrag(event) {
    if (event.target.closest('coral-multifield') === this) {
      const items = this.items.getAll();
      Elet marginBottom = 0;
 
      if (items.length) {
        marginBottom = parseFloat(window.getComputedStyle(items[0]).marginBottom);
      }
 
      items.forEach((item) => {
        if (!item.classList.contains(IS_DRAGGING_CLASS)) {
          const dragElement = event.detail.dragElement;
          const dragElementBoundingClientRect = dragElement.getBoundingClientRect();
          const itemBoundingClientRect = item.getBoundingClientRect();
          const dragElementOffsetTop = dragElementBoundingClientRect.top;
          const itemOffsetTop = itemBoundingClientRect.top;
 
          const isAfter = dragElementOffsetTop < itemOffsetTop;
          const itemReorderedTop = `${dragElementBoundingClientRect.height + marginBottom}px`;
 
          item.classList.toggle(IS_AFTER_CLASS, isAfter);
          item.classList.toggle(IS_BEFORE_CLASS, !isAfter);
 
          if (item.classList.contains(IS_AFTER_CLASS)) {
            item.style.top = items.indexOf(item) < items.indexOf(dragElement) ? itemReorderedTop : '';
          }
 
          if (item.classList.contains(IS_BEFORE_CLASS)) {
            const afterDragElement = items.indexOf(item) > items.indexOf(dragElement);
            item.style.top = afterDragElement ? `-${itemReorderedTop}` : '';
          }
        }
      });
    }
  }
 
  /** @ignore */
  _onDragEnd(event) {
    if (event.target.closest('coral-multifield') === this) {
      document.body.classList.remove('u-coral-closedHand');
 
      const dragElement = event.detail.dragElement;
      const items = this.items.getAll();
      const beforeArr = [];
      const afterArr = [];
 
      items.forEach((item) => {
        if (item.classList.contains(IS_AFTER_CLASS)) {
          afterArr.push(item);
        } else if (item.classList.contains(IS_BEFORE_CLASS)) {
          beforeArr.push(item);
        }
 
        item.classList.remove(IS_DRAGGING_CLASS, IS_AFTER_CLASS, IS_BEFORE_CLASS);
        item.style.top = '';
        item.style.position = '';
      });
 
      const oldBefore = dragElement.previousElementSibling;
      Econst before = afterArr.shift();
      const after = beforeArr.pop();
      const beforeEvent = this.trigger('coral-multifield:beforeitemorder', {
        item: dragElement,
        oldBefore: oldBefore,
        before: before
      });
 
      if (!beforeEvent.defaultPrevented) {
        if (before) {
          this.insertBefore(dragElement, before);
        }
      E  if (after) {
          this.insertBefore(dragElement, after.nextElementSibling);
        }
 
        // Toggle dragging state on multifield item.
        dragElement._dragging = false;
 
        this.trigger('coral-multifield:itemorder', {
          item: dragElement,
          oldBefore: oldBefore,
          before: before
        });
 
        this.trigger('change');
 
        dragElement._elements.move.focus();
      }
    }
  }
 
  /** @ignore */
  _onUpClick(event) {
    const upHandle = event.matchedTarget;
    const shiftElement = upHandle.closest('coral-multifield-item');
    if(shiftElement.previousElementSibling.tagName === 'CORAL-MULTIFIELD-ITEM') {
      this.insertBefore(shiftElement, shiftElement.previousElementSibling);
    }
  }
 
  /** @ignore */
  _onDownClick(event) {
    const upHandle = event.matchedTarget;
    const shiftElement = upHandle.closest('coral-multifield-item');
    if(shiftElement.nextElementSibling.tagName === 'CORAL-MULTIFIELD-ITEM') {
      this.insertBefore(shiftElement.nextElementSibling, shiftElement);
    }
  }
 
  /** @private */
  _onItemAdded(item) {
    const self = this;
    // Update the item content with the template content
    if (item.parentNode === self) {
      self._renderTemplate(item);
      self._updatePosInSet();
    }
 
    if(self.items.length === self.min + 1) {
      self._validateMinItems();
    }
 
    // a11y
    self._handleRoleList();
  }
 
  /** @private */
  _onItemRemoved() {
    const self = this;
    self._updatePosInSet();
 
    // only validate when required
    if(self.items.length <= self.min) {
      self._validateMinItems();
    }
 
    // a11y
    self._handleRoleList();
  }
 
  /**
   * handle role list of the multifield based on number of items
   * @private
   */
  _handleRoleList() {
    const self = this;
    if (self.items.length > 0 && self.getAttribute('role') !== 'list') {
      self.setAttribute('role', 'list');
    } else if (self.items.length === 0 && self.getAttribute('role') === 'list') {
      self.removeAttribute('role');
    }
  }
 
  /**
   * update aria-posinset and aria-setsize for each item in the collection
   * @private
   */
  _updatePosInSet() {
    consIt items = this.items.getAll();
    const setsize = items.length;
    items.forEach((item, i) => {
      item.setAttribute('aria-posinset', i + 1);
      item.setAttribute('aria-setsize', setsize);
      item.setAttribute('aria-label', i18n.get('({0} of {1})', i + 1, setsize));
      // so long as item content is not another multifield,
      // add aria-labelledby so that the item is labelled by its content and itself.
      if (!item.querySelector('coral-multifield')) {
        item.setAttribute('aria-labelledby', `${item.id}-content ${item.id}`);
      }
    });
  }
 
  /** @private */
  _renderTemplate(item) {
    const content = item.content || item.querySelector('coral-multifield-item-content') || item;
 
    // Insert the template if item content is empty
    if (!content.firstChild) {
      // @polyfill IE
      if (!TEMPLATE_SUPPORT) {
        // Before cloning, put the nested templates content back in the DOM
        const nestedTemplates = this.template.content.querySelectorAll('template[coral-multifield-template]');
 
        Array.prototype.forEach.call(nestedTemplates, (template) => {
          while (template.content.firstChild) {
            template.appendChild(template.content.firstChild);
          }
        });
      }
 
      // Clone the template and append it to the item content
      content.appendChild(document.importNode(this.template.content, true));
    }
  }
 
  get _contentZones() {
    return {template: 'template'};
  }
 
  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat([
      'min',
      'readonly',
      'reorderupdown'
    ]);
  }
 
  /** @ignore */
  render() {
    super.render();
 
    this.classList.add(CLASSNAME, 'coral-Well');
 
    // a11y
    this._handleRoleList();
 
    // a11y Add aria-label to the add button if exists to give context to screen reader users
    const coralMultifieldAddBtn = this.querySelector('[coral-multifield-add]');
    if (coralMultifieldAddBtn){
      coralMultifieldAddBtn.setAttribute("aria-label","Add");
    }
 
    // Assign the content zones, moving them into place in the process
    this.template = this._elements.template;
 
    // Prepare items content based on the given template
    this.items.getAll().forEach((item) => {
      this._renderTemplate(item);
    });
 
    // update aria-posinset and aria-setsize for each item in the collection
    this._updatePosInSet();
 
    this._validateMinItems(true);
  }
 
  /**
   Triggered when the {@link Multifield} item are reordered.
 
   @typedef {CustomEvent} coral-multifield:beforeitemorder
 
   @property {MultifieldItem} detail.item
   The item to be ordered.
   @property {MultifieldItem} detail.oldBefore
   Ordered item next sibling before the swap. If <code>null</code>, the item was the last item.
   @property {MultifieldItem} detail.before
   Ordered item will be inserted before this sibling item. If <code>null</code>, the item is inserted at the end.
   */
 
  /**
   Triggered when the {@link Multifield} item are reordered.
 
   @typedef {CustomEvent} coral-multifield:itemorder
 
   @property {MultifieldItem} detail.item
   The ordered item.
   @property {MultifieldItem} detail.oldBefore
   Ordered item next sibling before the swap. If <code>null</code>, the item was the last item.
   @property {MultifieldItem} detail.before
   Ordered item was inserted before this sibling item. If <code>null</code>, the item was inserted at the end.
   */
});
 
export default Multifield;