All files / coral-component-alert/src/scripts Alert.js

100% Statements 79/79
94.59% Branches 35/37
100% Functions 23/23
100% Lines 79/79

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                                                                              2x                                   2x       2x   2x   2x 10x       2x 166x                         2x 2x   2x           96x   96x   96x             96x       96x                     2x               8x 8x   8x 6x 6x     8x         166x 78x     166x   166x 4x       166x 166x 166x             78x   78x   78x   78x 28x     78x 26x     78x 234x   234x 164x       78x 420x   420x   302x     118x       78x     78x 234x     234x           168x         88x 88x   88x   88x     88x         88x                         2x     78x 78x   78x                     84x     80x       80x 80x                         88x     80x       80x   80x                         2x     80x       80x   80x             4788x            
/**
 * 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 {Icon} from '../../../coral-component-icon';
import {transform, validate} from '../../../coral-utils';
import {Decorator} from '../../../coral-decorator';
 
/**
 Enumeration for {@link Alert} variants.
 
 @typedef {Object} AlertVariantEnum
 
 @property {String} ERROR
 An alert with a warning icon to indicate that an error has occurred.
 @property {String} WARNING
 An alert with a warning icon to warn the user of something important.
 @property {String} SUCCESS
 An alert with a question mark icon to notify the user of a successful operation.
 @property {String} HELP
 A neutral alert with a question icon to help the user with non-critical information.
 @property {String} INFO
 An alert with an info icon to inform the user of non-critical information.
 */
const variant = {
  ERROR: 'error',
  WARNING: 'warning',
  SUCCESS: 'success',
  HELP: 'help',
  INFO: 'info'
};
 
/**
 Enumeration for {@link Alert} sizes.
 
 @typedef {Object} AlertSizeEnum
 
 @property {String} SMALL
 A small alert, usually employed for single line alerts without headers.
 @property {String} LARGE
 Not supported. Falls back to SMALL.
 */
const size = {
  SMALL: 'S',
  LARGE: 'L'
};
 
const CLASSNAME = '_coral-Alert';
 
// An array of all possible variant classnames
const ALL_VARIANT_CLASSES = [];
for (const variantValue in variant) {
  ALL_VARIANT_CLASSES.push(`${CLASSNAME}--${variant[variantValue]}`);
}
 
// Used to map icon with variant
const capitalize = s => s.charAt(0).toUpperCase() + s.slice(1);
 
/**
 @class Coral.Alert
 @classdesc An Alert component used as static indicators of an operation's result, or as messages to highlight
 information to the user. It does not include a close button by default, but you can add it manually by adding the
 <code>coral-close</code> attribute on an element contained by the Alert.
 @htmltag coral-alert
 @extends {HTMLElement}
 @extends {BaseComponent}
 */
const Alert = Decorator(class extends BaseComponent(HTMLElement) {
  /** @ignore */
  constructor() {
    super();
 
    // Prepare templates
    this._elements = {
      // Fetch or create the content zone elements
      header: this.querySelector('coral-alert-header') || document.createElement('coral-alert-header'),
      content: this.querySelector('coral-alert-content') || document.createElement('coral-alert-content'),
      footer: this.querySelector('coral-alert-footer') || document.createElement('coral-alert-footer')
    };
 
    // Events
    this._delegateEvents({
      'click [coral-close]': '_onCloseClick'
    });
  }
 
  /**
   The alert variant style to use. See {@link AlertVariantEnum}.
 
   @type {String}
   @default AlertVariantEnum.INFO
   @htmlattribute variant
   @htmlattributereflected
   */
  get variant() {
    return this._variant || variant.INFO;
  }
 
  set variant(value) {
    value = transform.string(value).toLowerCase();
    this._variant = validate.enumeration(variant)(value) && value || variant.INFO;
    this._reflectAttribute('variant', this._variant);
 
    this._insertTemplate();
 
    // Remove all variant classes
    this.classList.remove(...ALL_VARIANT_CLASSES);
 
    // Set new variant class
    // Don't use this._className; use the constant
    // This lets popover get our styles for free
    this.classList.add(`${CLASSNAME}--${this._variant}`);
  }
 
  /**
   The size of the alert. It accepts both lower and upper case sizes. See {@link AlertVariantEnum}.
 
   @type {String}
   @default AlertSizeEnum.SMALL
   @htmlattribute size
   @htmlattributereflected
   */
  get size() {
    return this._size || size.SMALL;
  }
 
  set size(value) {
    value = transform.string(value).toUpperCase();
    this._size = validate.enumeration(size)(value) && value || size.SMALL;
    this._reflectAttribute('size', this._size);
  }
 
  /**
   The alert header element.
 
   @type {AlertHeader}
   @contentzone
   */
  get header() {
    return this._getContentZone(this._elements.header);
  }
 
  set header(value) {
    this._setContentZone('header', value, {
      handle: 'header',
      tagName: 'coral-alert-header',
      insert: function (header) {
        header.classList.add(`${CLASSNAME}-header`);
        this.insertBefore(header, this.firstChild);
      }
    });
  }
 
  /**
   The alert content element.
 
   @type {AlertContent}
   @contentzone
   */
  get content() {
    return this._getContentZone(this._elements.content);
  }
 
  set content(value) {
    this._setContentZone('content', value, {
      handle: 'content',
      tagName: 'coral-alert-content',
      insert: function (content) {
        content.classList.add(`${CLASSNAME}-content`);
        // After the header
        this.insertBefore(content, this.header.nextElementSibling);
      }
    });
  }
 
  /**
   The alert footer element.
 
   @type {AlertFooter}
   @contentzone
   */
  get footer() {
    return this._getContentZone(this._elements.footer);
  }
 
  set footer(value) {
    this._setContentZone('footer', value, {
      handle: 'footer',
      tagName: 'coral-alert-footer',
      insert: function (footer) {
        footer.classList.add(`${CLASSNAME}-footer`);
        // After the content
        this.insertBefore(footer, this.content.nextElementSibling);
      }
    });
  }
 
  /**
   @ignore
   @todo maybe this should be base or something
   */
  _onCloseClick(event) {
    const dismissTarget = event.matchedTarget;
    const dismissValue = dismissTarget.getAttribute('coral-close');
    if (!dismissValue || this.matches(dismissValue)) {
      this.hidden = true;
      event.stopPropagation();
    }
 
    this._trackEvent('close', 'coral-alert', event);
  }
 
  _insertTemplate() {
    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
    const iconName = capitalize(variantValue);
    this.insertAdjacentHTML('afterbegin', Icon._renderSVG(`spectrum-css-icon-${iconName}Medium`, ['_coral-Alert-icon', `_coral-UIIcon-${iconName}Medium`]));
    this._elements.icon = this.querySelector('._coral-Alert-icon');
  }
 
  get _contentZones() {
    return {
      'coral-alert-header': 'header',
      'coral-alert-content': 'content',
      'coral-alert-footer': 'footer'
    };
  }
 
  /**
   Returns {@link Alert} variants.
 
   @return {AlertVariantEnum}
   */
  static get variant() {
    return variant;
  }
 
  /**
   Returns {@link Alert} sizes.
 
   @return {AlertSizeEnum}
   */
  static get size() {
    return size;
  }
 
  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat(['variant', 'size']);
  }
 
  /** @ignore */
  render() {
    super.render();
 
    this.classList.add(CLASSNAME);
 
    // a11y
    this.setAttribute('role', 'alert');
 
    // Default reflected attributes
    if (!this._variant) {
      this.variant = variant.INFO;
    }
    if (!this._size) {
      this.size = size.SMALL;
    }
 
    for (const contentZone in this._contentZones) {
      const element = this._elements[this._contentZones[contentZone]];
      // Remove it so we can process children
      if (element.parentNode) {
        element.parentNode.removeChild(element);
      }
    }
 
    while (this.firstChild) {
      const child = this.firstChild;
      if (child.nodeType === Node.TEXT_NODE ||
        child.nodeType === Node.ELEMENT_NODE && !child.classList.contains('_coral-Alert-icon')) {
        // Add non-template elements to the content
        this._elements.content.appendChild(child);
      } else {
        // Remove anything else element
        this.removeChild(child);
      }
    }
 
    this._insertTemplate();
 
    // Assign the content zones so the insert functions will be called
    for (const contentZone in this._contentZones) {
      const contentZoneName = this._contentZones[contentZone];
 
      /** @ignore */
      this[contentZoneName] = this._elements[contentZoneName];
    }
  }
});
 
export default Alert;