All files / coral-component-popover/src/scripts Popover.js

97.55% Statements 199/204
90% Branches 117/130
95.56% Functions 43/45
97.55% Lines 199/204

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                                                    2x 2x   2x 104x       2x 12666x                             2x                                             2x                   2x   2x 14x 14x         2x 2x   2x 8x                   2x 2x   2x           3544x   3544x   3544x           3544x       3544x             3544x 3544x 3544x 3544x 3544x   3544x 7088x 10x   10x     7088x   3544x                   2x     6915x   6915x   6915x 6229x   6229x 6127x 6127x 6127x               204x       158x   158x             711x   711x 2x 709x 2x 707x   707x 681x           3224x       3224x   3224x 12x       3224x 104x   104x   104x           13520x   13520x 13520x 13520x                         6442x 6442x   6442x     6442x 5952x   5952x           3224x   3224x   3224x   3224x   3224x 9672x 9672x   9672x 1050x 1050x               3234x   3234x 3234x             440x   2x     438x   438x   438x   438x   158x   144x   144x   14x   14x   280x 42x   42x 2x       40x   40x               3216x   3216x   3216x   3216x 684x     3216x   2704x       3216x 2884x     3216x 2960x       3216x 3216x 3216x   3216x   3216x 260x     3216x 266x     3216x 248x       3216x 4788x   1458x     3216x   3216x 744x       3216x 2946x 8766x         3216x 3216x 3216x 3216x 3216x   3216x 3216x 3216x         4100x     3216x       3216x 3216x   3216x                           6360x     3216x       3216x   3216x       3216x     3216x                         9550x     3216x       3216x   3216x       3216x     3216x                             3228x         3224x 3224x   3224x     3224x     3224x     3224x   3224x   4x   4x   3220x   3220x   3116x         104x   104x                             2x     3220x 3220x   3220x   3220x                 24956x       6340x   6340x     6340x   6340x 2x     6340x   6340x                 31252x     599x   599x   599x 575x   575x 529x  
/**
 * 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 {ExtensibleOverlay, Overlay} from '../../../coral-component-overlay';
import {Icon} from '../../../coral-component-icon';
// Popover relies on Dialog styles partially
import '../../../coral-component-dialog';
import base from '../templates/base';
import {commons, transform, validate, i18n} from '../../../coral-utils';
import {Decorator} from '../../../coral-decorator';
 
const CLASSNAME = '_coral-Popover';
 
const OFFSET = 5;
 
// Used to map icon with variant
const capitalize = s => s.charAt(0).toUpperCase() + s.slice(1);
 
// If it's empty and has no non-textnode children
const _isEmpty = (el) => !el || el.children.length === 0 && el.textContent.replace(/\s*/g, '') === '';
 
/**
 Enumeration for {@link Popover} closable state.
 
 @typedef {Object} PopoverClosableEnum
 
 @property {String} ON
 Show a close button on the popover and close the popover when clicked.
 @property {String} OFF
 Do not show a close button. Elements with the <code>coral-close</code> attributes will still close the
 popover.
 */
const closable = {
  ON: 'on',
  OFF: 'off'
};
 
/**
 Enumeration for {@link Popover} variants.
 
 @typedef {Object} PopoverVariantEnum
 
 @property {String} DEFAULT
 A default popover without header icon.
 @property {String} ERROR
 A popover with an error header and icon, indicating that an error has occurred.
 @property {String} WARNING
 A popover with a warning header and icon, notifying the user of something important.
 @property {String} SUCCESS
 A popover with a success header and icon, indicates to the user that an operation was successful.
 @property {String} HELP
 A popover with a question header and icon, provides the user with help.
 @property {String} INFO
 A popover with an info header and icon, informs the user of non-critical information.
 */
const variant = {
  DEFAULT: 'default',
  ERROR: 'error',
  WARNING: 'warning',
  SUCCESS: 'success',
  HELP: 'help',
  INFO: 'info',
  _COACHMARK: '_coachmark'
};
 
// A string of all possible variant classnames
const ALL_VARIANT_CLASSES = [];
for (const variantValue in variant) {
  if (variantValue !== 'COACHMARK') {
    ALL_VARIANT_CLASSES.push(`_coral-Dialog--${variant[variantValue]}`);
  }
}
 
// A string of all possible placement classnames
const placement = Overlay.placement;
const ALL_PLACEMENT_CLASSES = [];
for (const placementKey in placement) {
  EALL_PLACEMENT_CLASSES.push(`${CLASSNAME}--${placement[placementKey]}`);
}
 
/**
 @class Coral.Popover
 @classdesc A Popover component for small overlay content.
 @htmltag coral-popover
 @extends {Overlay}
 */
const Popover = Decorator(class extends ExtensibleOverlay {
  /** @ignore */
  constructor() {
    super();
 
    // Prepare templates
    this._elements = commons.extend(this._elements, {
      // Fetch or create the content zone elements
      header: this.querySelector('coral-popover-header') || document.createElement('coral-popover-header'),
      content: this.querySelector('coral-popover-content') || document.createElement('coral-popover-content'),
      footer: this.querySelector('coral-popover-footer') || document.createElement('coral-popover-footer')
    });
    base.call(this._elements, {i18n});
 
    // Events
    this._delegateEvents({
      'global:capture:click': '_handleClick',
      'coral-overlay:positioned': '_onPositioned',
      'coral-overlay:_animate': '_onAnimate',
    });
 
    // Override defaults from Overlay
    this._focusOnShow = this.constructor.focusOnShow.ON;
    this._trapFocus = this.constructor.trapFocus.ON;
    this._returnFocus = this.constructor.returnFocus.ON;
    this._overlayAnimationTime = this.constructor.FADETIME;
    this._lengthOffset = OFFSET;
 
    // Listen for mutations
    ['header', 'footer'].forEach((name) => {
      this[`_${name}Observer`] = new MutationObserver(() => {
        this._hideContentZoneIfEmpty(name);
        this._toggleFlyout();
      });
 
      // Watch for changes
      this._observeContentZone(name);
    });
  }
 
  /**
   The popover's content element.
 
   @contentzone
   @name content
   @type {PopoverContent}
   */
  get content() {
    return this._getContentZone(this._elements.content);
  }
 
  set content(value) {
    this._setContentZone('content', value, {
      handle: 'content',
      tagName: 'coral-popover-content',
      insert: function (content) {
        content.classList.add('_coral-Dialog-content');
        const footer = this.footer;
        // The content should always be before footer
        this.insertBefore(content, this.contains(footer) && footer || null);
      }
    });
  }
 
  /**
   The popover's header element.
 
   @contentzone
   @name header
   @type {PopoverHeader}
   */
  get header() {
    return this._getContentZone(this._elements.header);
  }
 
  set header(value) {
    this._setContentZone('header', value, {
      handle: 'header',
      tagName: 'coral-popover-header',
      insert: function (header) {
        header.classList.add('_coral-Dialog-title');
        this._elements.headerWrapper.insertBefore(header, this._elements.headerWrapper.firstChild);
      },
      set: function () {
        // Stop observing the old header and observe the new one
        this._observeContentZone('header');
 
        // Check if header needs to be hidden
        this._hideContentZoneIfEmpty('header');
      }
    });
  }
 
  /**
   The popover's footer element.
 
   @type {PopoverFooter}
   @contentzone
   */
  get footer() {
    return this._getContentZone(this._elements.footer);
  }
 
  set footer(value) {
    this._setContentZone('footer', value, {
      handle: 'footer',
      tagNameI: 'coral-popover-footer',
      insert: function (footer) {
        footer.classList.add('_coral-Dialog-footer');
        // The footer should always be after content
        this.appendChild(footer);
      },
      set: function () {
        // Stop observing the old header and observe the new one
        this._observeContentZone('footer');
I
        // Check if header needs to be hidden
        this._hideContentZoneIfEmpty('footer');
      }
    });
  }
 
  /**
   The popover's variant. See {@link PopoverVariantEnum}.
 
   @type {String}
   @default PopoverVariantEnum.DEFAULT
   @htmlattribute variant
   @htmlattributereflected
   */
  get variant() {
    return this._variant || variant.DEFAULT;
  }
 
  set variant(value) {
    value = transform.string(value).toLowerCase();
    this._variant = validate.enumeration(variant)(value) && value || variant.DEFAULT;
    this._reflectAttribute('variant', this._variant);
 
    //E Insert SVG icon
    this._insertTypeIcon();
 
    // Remove all variant classes
    this.classList.remove(...ALL_VARIANT_CLASSES);
 
    // Toggle dialog mode
    this._toggleFlyout();
 
    if (this._variant === variant._COACHMARK) {
      // ARIA
      this.setAttribute('role', 'dialog');
 
      this._toggleCoachMark(true);
    } else {
      this._toggleCoachMark(false);
 
      if (this._variant === variant.DEFAULT) {
        // ARIA
        if (!this.hasAttribute('role')) {
          this.setAttribute('role', 'dialog');
        }
      } else {
        // Set new variant class
        this.classList.add(`_coral-Dialog--${this._variant}`);
 
        // ARIA
        this.setAttribute('role', 'alertdialog');
      }
    }
  }
 
  /**
   Whether the popover should have a close button. See {@link PopoverClosableEnum}.
 
   @type {String}
   @default PopoverClosableEnum.OFF
   @htmlattribute closable
   @htmlattributereflected
   */
  get closable() {
    return this._closable || closable.OFF;
  }
 
  set closable(value) {
    value = transform.string(value).toLowerCase();
    this._closable = validate.enumeration(closable)(value) && value || closable.OFF;
    this._reflectAttribute('closable', this._closable);
 
    this._elements.closeButton.style.display = this._closable === closable.ON ? 'block' : 'none';
  }
 
  /**
   Inherited from {@link Overlay#target}.
   */
  get target() {
    return super.target;
  }
 
  set target(value) {
    // avoid popper initialization while connecting for first time and not opened.
    this._avoidPopperInit = this.open || this._popper ? false : true;
 
    super.target = value;
 
    // Coach Mark specific
    const target = this._getTarget();
    if (target && target.tagName === 'CORAL-COACHMARK') {
      this.setAttribute('variant', variant._COACHMARK);
    }
 
    this._setAriaExpandedOnTarget();
 
    delete this._avoidPopperInit;
  }
 
  /**
   Inherited from {@link Overlay#open}.
   */
  get open() {
    return super.open;
  }
 
  set open(value) {
    super.open = value;
 
    const target = this._getTarget();
    if (target) {
      const is = target.getAttribute('is');
      if (is === 'coral-button' || is === 'coral-anchorbutton') {
        target.classList.toggle('is-selected', this.open);
      }
 
      this._setAriaExpandedOnTarget();
    }
  }
 
  /**
   @ignore
 
   Not supported anymore.
   */
  get icon() {
    return this._icon || '';
  }
 
  set icon(value) {
    this._icon = transform.string(value);
  }
 
  _setAriaExpandedOnTarget() {
    const target = this._getTarget();
    if (target) {
      const hasPopupAttribute = target.hasAttribute('aria-haspopup');
      if (hasPopupAttribute || target.querySelector('[aria-haspopup]') !== null) {
        const targetElements = hasPopupAttribute ? [target] : target.querySelectorAll('[aria-haspopup]');
        targetElements.forEach((targetElement) => targetElement.setAttribute('aria-expanded', this.open));
      }
    }
  }
 
  _onPositioned(event) {
    if (this.open) {
      // Set arrow placement
      this.classList.remove(...ALL_PLACEMENT_CLASSES);
      this.classList.add(`${CLASSNAME}--${event.detail.placement}`);
    }
  }
 
  _onAnimate() {
    // popper attribute
    const popperPlacement = this.getAttribute('x-placement');

    // popper takes care of setting left, top to 0 on positioning
    if (popperPlacement === 'left') {
      this.style.left = '8px';
    } else if (popperPlacement === 'top') {
      this.style.top = '8px';
    } else if (popperPlacement === 'right') {
      this.style.left = '-8px';
    } else if (popperPlacement === 'bottom') {
      this.style.top = '-8px';
    }
  }
 
  _insertTypeIcon() {
    if (this._elements.icon) {
      this._elements.icon.remove();
    }
 
    let variantValue = this.variant;
 
    // Warning icon is same as ERROR icon
    if (variantValue === variant.WARNING || variantValue === variant.ERROR) {
      variantValue = 'alert';
    }
 
    // Inject the SVG icon
    if (variantValue !== variant.DEFAULT && variantValue !== variant._COACHMARK) {
      const iconName = capitalize(variantValue);
      this._elements.headerWrapper.insertAdjacentHTML('beforeend', Icon._renderSVG(`spectrum-css-icon-${iconName}Medium`, ['_coral-Dialog-typeIcon', `_coral-UIIcon-${iconName}Medium`]));
      this._elements.icon = this.querySelector('._coral-Dialog-typeIcon');
    }
  }
 
  _observeContentZone(name) {
    const observer = this[`_${name}Observer`];
    if (observer) {
      observer.disconnect();
      observer.observe(this._elements[name], {
        // Catch changes to childList
        childList: true,
        // Catch changes to textContent
        characterData: true,
        // Monitor any child node
        subtree: true
      });
    }
  }
 
  _hideContentZoneIfEmpty(name) {
    const contentZone = this._elements[name];
    const target = name === 'header' ? this._elements.headerWrapper : contentZone;
 
    // If it's empty and has no non-textnode children, hide the header
    const hiddenValue = _isEmpty(contentZone);
 
    // Only bother if the hidden status has changed
    if (hiddenValue !== target.hidden) {
      target.hidden = hiddenValue;

      // Reposition as the height has changed
      this.reposition();
    }
  }
 
  _toggleCoachMark(isCoachMark) {
    this.classList.toggle('_coral-CoachMarkPopover', isCoachMark);
    this._elements.headerWrapper.classList.toggle('_coral-Dialog-header', !isCoachMark);
    this._elements.headerWrapper.classList.toggle('_coral-CoachMarkPopover-header', isCoachMark);
 
    ['header', 'content', 'footer'].forEach((contentZone, i) => {
      const el = this[contentZone];
      const type = i === 0 ? 'title' : contentZone;
 
      if (el) {
        el.classList.toggle(`_coral-Dialog-${type}`, !isCoachMark);
        el.classList.toggle(`_coral-CoachMarkPopover-${type}`, isCoachMark);
      }
    });
  }
 
  _toggleFlyout() {
    // Flyout mode is when there's only content in default variant
    const isFlyout = this._variant === variant._COACHMARK ||
      this._variant === variant.DEFAULT && _isEmpty(this.header) && _isEmpty(this.footer);
 
    this.classList.toggle(`${CLASSNAME}--dialog`, !isFlyout);
    this._elements.tip.hidden = isFlyout;
  }
 
  /** @private */
  _handleClick(event) {
    if (this.interaction === this.constructor.interaction.OFF) {
      // Since we use delegation, just ignore clicks if interaction is off
      return;
    }
 
    const eventTarget = event.target;
    const targetEl = this._getTarget();
 
    const eventIsWithinTarget = targetEl ? targetEl.contains(eventTarget) : false;
 
    if (eventIsWithinTarget) {
      // When target is clicked
 
      if (!this.open && !targetEl.disabled) {
        // Open if we're not already open and target element is not disabled
        this.show();
 
        this._trackEvent('display', 'coral-popover', event);
      } else {
        this.hide();
 
        this._trackEvent('close', 'coral-popover', event);
      }
    } else if (this.open && !this.contains(eventTarget)) {
      const target = eventTarget.closest('._coral-Overlay');
      // Also check if the click element is inside an overlay which target could be inside of this popover
      if (target && this.contains(target._getTarget())) {
        return;
      }
 
      // Close if we're open and the click was outside of the target and outside of the popover
      this.hide();
 
      this._trackEvent('close', 'coral-popover', event);
    }
  }
 
  get _contentZones() {
    return {
      'coral-popover-header': 'header',
      'coral-popover-content': 'content',
      'coral-popover-footer': 'footer'
    };
  }
 
  /**
   Returns {@link Popover} variants.

   @return {PopoverVariantEnum}
   */
  static get variant() {
    return variant;
  }
 
  /**
   Returns {@link Popover} close options.
 
   @return {PopoverClosableEnum}
   */
  static get closable() {
    return closable;
  }
 
  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat([
      'closable',
      'variant'
    ]);
  }
I
  /** @ignore */
  render() {
    super.render();
 
    this.classList.add(CLASSNAME);
 
    // ARIA
    if (!this.hasAttribute('role')) {
      this.setAttribute('role', 'dialog');
    }
 
    if (!this.hasAttribute('aria-live')) {
      // This helped announcements in certain screen readers
      this.setAttribute('aria-live', 'assertive');
    }
 
    // Default reflected attributes
    if (!this._variant) {
      this.variant = variant.DEFAULT;
    }
    if (!this._closable) {
      this.closable = closable.OFF;
    }
 
    // // Fetch the content zones
    const header = this._elements.header;
    const content = this._elements.content;
    const footer = this._elements.footer;
 
    // Verify if a content zone is provided
    const contentZoneProvided = this.contains(content) && content || this.contains(footer) && footer || this.contains(header) && header;
 
    // Remove content zones so we can process children
    if (header.parentNode) {
      header.remove();
    }
    if (content.parentNode) {
      content.remove();
    }
    if (footer.parentNode) {
      footer.remove();
    }
 
    // Remove tab captures
    Array.prototype.filter.call(this.children, (child) => child.hasAttribute('coral-tabcapture')).forEach((tabCapture) => {
      this.removeChild(tabCapture);
    });
 
    // Support cloneNode
    const template = this.querySelectorAll('._coral-Dialog-header, ._coral-Dialog-closeButton, ._coral-Popover-tip');
    for (let i = 0 ; i < template.length ; i++) {
      template[i].remove();
    }
 
    // Move everything in the content
    if (!contentZoneProvided) {
      while (this.firstChild) {
        content.appendChild(this.firstChild);
      }
    }
 
    // Insert template
    const frag = document.createDocumentFragment();
    frag.appendChild(this._elements.headerWrapper);
    frag.appendChild(this._elements.closeButton);
    frag.appendChild(this._elements.tip);
    this.appendChild(frag);
 
    // Assign content zones
    this.header = header;
    this.content = content;
    this.footer = footer;
  }
});
 
export default Popover;