All files / coral-component-progress/src/scripts Progress.js

99.23% Statements 129/130
89.04% Branches 65/73
100% Functions 25/25
99.23% Lines 129/130

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                                                                        2x                                       2x             2x                 2x 2x   2x           82x   82x   82x       82x   82x   82x           82x                       2x         168x 168x 168x   168x 4x 4x   4x 2x     164x 164x   164x 12x         168x 50x 50x   50x 4x     50x   50x     118x 118x   118x 10x       118x               4x   4x             252x   6x     252x             68x   68x   68x 68x     68x 48x     68x 48x       68x 68x   68x 68x 68x   68x 20x       68x 52x   52x   12x     40x         68x   68x   68x     68x 68x 68x 68x                   192x     112x   112x 2x 110x 2x     112x   112x   112x 106x   106x   106x         6x     112x                           310x     12x   12x   12x 6x   6x 6x 6x 6x   6x   6x 6x 6x                             2x     72x 72x   72x   72x                         330x     4x   4x   4x 4x   4x     4x                       8x     68x       68x 68x                             250x     80x   80x 80x   80x   80x 80x   80x 240x     80x         506x                       14x                   14x  
/**
 * 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 base from '../templates/base';
import {commons, transform, validate} from '../../../coral-utils';
import {Decorator} from '../../../coral-decorator';
 
/**
 Enumeration for {@link Progress} sizes.
 
 @typedef {Object} ProgressSizeEnum
 
 @property {String} SMALL
 A small progress bar.
 @property {String} MEDIUM
 A default medium progress bar.
 @property {String} LARGE
 Not supported. Falls back to MEDIUM.
 */
const size = {
  SMALL: 'S',
  MEDIUM: 'M',
  LARGE: 'L'
};
 
/**
 Enumeration for {@link Progress} label positions.
 
 @typedef {Object} ProgressLabelPositionEnum
 
 @property {String} LEFT
 Show the label to the left of the bar.
 @property {String} SIDE
 Show the label to the side of the bar.
 @property {String} RIGHT
 Not supported. Falls back to LEFT.
 @property {String} BOTTOM
 Not supported. Falls back to LEFT.
 */
const labelPosition = {
  LEFT: 'left',
  RIGHT: 'right',
  SIDE: 'side',
  BOTTOM: 'bottom'
};
 
// Base classname
const CLASSNAME = '_coral-BarLoader';
 
/**
 @class Coral.Progress
 @classdesc A Progress component to indicate progress of processes.
 @htmltag coral-progress
 @extends {HTMLElement}
 @extends {BaseComponent}
 */
const Progress = Decorator(class extends BaseComponent(HTMLElement) {
  /** @ignore */
  constructor() {
    super();
 
    // Prepare templates
    this._elements = {
      // Fetch or create the content content zone element
      label: this.querySelector('coral-progress-label') || document.createElement('coral-progress-label')
    };
    base.call(this._elements);
 
    // Watch for label changes
    this._observer = new MutationObserver(this._toggleLabelVisibility.bind(this));
    this._observer.observe(this._elements.label, {
      characterData: true,
      childList: true,
      subtree: true
    });
  }
 
  /**
   The current progress in percent.
 
   @type {Number}
   @default 0
   @emits {coral-progress:change}
   @htmlattribute value
   @htmlattributereflected
   */
  get value() {
    return this.indeterminate ? 0 : this._value || 0;
  }
 
  set value(value) {
    value = transform.number(value) || 0;
 
    // Stay within bounds
    if (value > 100) {
      value = 100;
    } else if (value < 0) {
      value = 0;
    }
 
    this._value = value;
    this._reflectAttribute('value', this._value);
 
    if (!this.indeterminate) {
      this._elements.status.style.width = `${this.value}%`;
 
      // ARIA: Reflect value for screenreaders
      this.setAttribute('aria-valuenow', this._value);
 
      if (this.showPercent) {
        // Only update label text in percent mode
        this._setPercentage(`${this._value}%`);
      }
    } else {
      this._elements.status.style.width = '';
    }
 
    this.trigger('coral-progress:change');
  }
 
  /**
   Whether to hide the current value and show an animation. Set to true for operations whose progress cannot be
   determined.
 
   @type {Boolean}
   @default false
   @htmlattribute indeterminate
   @htmlattributereflected
   */
  get indeterminate() {
    return this._indeterminate || false;
  }
 
  set indeterminate(value) {
    this._indeterminate = transform.booleanAttr(value);
    thisE._reflectAttribute('indeterminate', this._indeterminate);
 
    if (this._indeterminate) {
      this.classList.add(`${CLASSNAME}--indeterminate`);
 
      // ARIA: Remove attributes
      this.removeAttribute('aria-valuenow');
      this.removeAttribute('aria-valuemin');
      this.removeAttribute('aria-valuemax');
 
      this.value = 0;
    } else {
      this.classList.remove(`${CLASSNAME}--indeterminate`);
 
      // ARIA: Add attributes
      this.setAttribute('aria-valuemin', '0');
      this.setAttribute('aria-valuemax', '100');
 
      this.value = this._oldValue;
    }
  }
 
  /**
   The vertical and text size of this progress bar. To adjust the width, simply set the CSS width property.
   See {@link ProgressSizeEnum}.
 
   @type {String}
   @default ProgressSizeEnum.MEDIUM
   @htmlattribute size
   @htmlattributereflected size
   */
  get size() {
    return this._size || size.MEDIUM;
  }
 
  set size(value) {
    value = transform.string(value).toUpperCase();
    this._size = validate.enumeration(size)(value) && value || size.MEDIUM;
    this._reflectAttribute('size', this._size);
 
    this.classList.toggle(`${CLASSNAME}--small`, this._size === size.SMALL);
  }
 
  /**
   Boolean attribute to toggle showing progress percent as the label content.
   Default is true.
E
   @type {Boolean}
   @default false
   @htmlattribute showpercent
   */
  get showPercent() {
    return this._showPercent || false;
  }
 
  set showPercent(value) {
    this._showPercent = transform.booleanAttr(value);
    this._reflectAttribute('showpercent', this._showPercent);
 
    if (this._showPercent) {
      const content = this.indeterminate ? '' : `${this.value}%`;
      this._setPercentage(content);
    }
 
    this._toggleLabelVisibility();
  }
 
  /**
   Used to access to the {@link Coral.Progress.Label} element. Keep in mind that the width of a custom label is
   limited for {@link Coral.Progress.labelPosition.LEFT} and {@link Coral.Progress.labelPosition.RIGHT}.
 
   @type {ProgressLabel}
   @contentzone
   */
  get label() {
    return this._getContentZone(this._elements.label);
  }
 
  set label(value) {
    this._setContentZone('label', value, {
      handle: 'label',
      tagName: 'coral-progress-label',
      insert: function (label) {
        label.classList.add(`${CLASSNAME}-label`);
        this.appendChild(label);
      }
    });
  }
 
  /**
   Label position. See {@link ProgressLabelPositionEnum}.
 
   @type {String}
   @default ProgressLabelPositionEnum.LEFT
   @htmlattribute labelposition
   @htmlattributereflected
   */
  get labelPosition() {
    return this._labelPosition || labelPosition.LEFT;
  }
 
  set labelPosition(value) {
    value = transform.string(value).toLowerCase();
    this._labelPosition = validate.enumeration(labelPosition)(value) && value || labelPosition.LEFT;
    this._reflectAttribute('labelposition', this._labelPosition);
 
    this.classList.toggle('_coral-BarLoader--sideLabel', this._labelPosition === labelPosition.SIDE);
 
    const elements = this.labelPosition === labelPosition.SIDE ? ['label', 'bar', 'percentage'] : ['label', 'percentage', 'bar'];
    // @spectrum should be supported with classes
    elements.forEach((el, i) => {
      this._elements[el].style.order = i;
    });
 
    this._toggleLabelVisibility();
  }
 
  /** @ignore */
  _toggleLabelVisibility() {
    const percentage = this._elements.percentage;
    const label = this._elements.label;
    const isSidePositioned = this.labelPosition === labelPosition.SIDE;
 
    // Handle percentage
    if (Ithis.showPercent) {
      percentage.style.visibility = 'visible';
      percentage.setAttribute('aria-hidden', 'false');
 
      if (isSidePositioned) {
        percentage.hidden = false;
      }
    } else {
      percentage.style.visibility = 'hidden';
      percentage.setAttribute('aria-hidden', 'true');
 
      if (isSidePositioned) {
        percentage.hidden = true;
      }
    }
 
    // Handle label
    if (label.textContent.length > 0) {
      label.style.visibility = 'visible';
      label.setAttribute('aria-hidden', 'false');
 
      if (isSidePositioned) {
        label.hidden = false;
      }
 
      if (!this.showPercent) {
        // Update the value for accessibility as it was cleared when the label was hidden
        this.setAttribute('aria-valuetext', label.textContent);
      }
    } else {
      label.style.visibility = 'hidden';
      label.setAttribute('aria-hidden', 'true');
 
      if (isSidePositioned) {
        label.hidden = true;
      }
 
      // Remove the value for accessibility so the screenreader knows we're unlabelled
      this.removeAttribute('aria-valuetext');
    }
  }
 
  /** @ignore */
  _setPercentage(content) {
    this._elements.percentage.textContent = content;
 
    // ARIA
    this[this.showPercent ? 'removeAttribute' : 'setAttribute']('aria-valuetext', content);
  }
 
  get _contentZones() {
    return {'coral-progress-label': 'label'};
  }
 
  /**
   Returns {@link Progress} label position options.
 
   @return {ProgressLabelPositionEnum}
   */
  static get labelPosition() {
    return labelPosition;
  }
 
  /**
   Returns {@link Progress} sizes.
 
   @return {ProgressSizeEnum}
   */
  static get size() {
    return size;
  }
 
  static get _attributePropertyMap() {
    return commons.extend(super._attributePropertyMap, {
      showpercent: 'showPercent',
      labelposition: 'labelPosition'
    });
  }
 
  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat([
      'value',
      'indeterminate',
      E'size',
      'showpercent',
      'labelposition'
    ]);
  }
 
  /** @ignore */
  attributeChangedCallback(name, oldValue, value) {
    if (name === 'indeterminate' && transform.booleanAttr(value)) {
      // Remember current value in case indeterminate is toggled
      this._oldValue = this._value || 0;
    }
 
    super.attributeChangedCallback(name, oldValue, value);
  }
 
  /** @ignore */
  render() {
    super.render();
 
    this.classList.add(CLASSNAME);
 
    // Default reflected attributes
    if (!this._value) {
      this.value = this.value;
    }
    if (!this._size) {
      this.size = size.MEDIUM;
    }
    if (!this._labelPosition) {
      this.labelPosition = labelPosition.LEFT;
    }
 
    // Create a fragment
    const fragment = document.createDocumentFragment();
 
    const templateHandleNames = ['bar', 'percentage'];
 
    // Render the template
    fragment.appendChild(this._elements.percentage);
    fragment.appendChild(this._elements.bar);
 
    const label = this._elements.label;
 
    // Remove it so we can process children
    if (label.parentNode) {
      label.parentNode.removeChild(label);
    }
 
    // Move any remaining elements into the content sub-component
    while (this.firstChild) {
      const child = this.firstChild;
      if (child.nodeType === Node.TEXT_NODE ||
        child.nodeType === Node.ELEMENT_NODE && templateHandleNames.indexOf(child.getAttribute('handle')) === -1) {
        // Add non-template elements to the label
        label.appendChild(child);
      } else {
        // Remove anything else
        this.removeChild(child);
      }
    }
 
    // Add the frag to the component
    this.appendChild(fragment);
 
    // Assign the content zone
    this.label = label;
 
    // Toggle label based on content
    this._toggleLabelVisibility();
 
    // ARIA
    this.setAttribute('role', 'progressbar');
    this.setAttribute('aria-valuenow', '0');
    this.setAttribute('aria-valuemin', '0');
    this.setAttribute('aria-valuemax', '100');
  }
 
  /**
   Triggered when the {@link Progress} value is changed.
 
   @typedef {CustomEvent} coral-progress:change
   */
});
 
export default Progress;