|
| 1 | +import { HXElement } from './HXElement'; |
| 2 | + |
| 3 | +const MIN = 0; |
| 4 | +const MAX = 100; |
| 5 | + |
| 6 | +const tagName = 'hx-progress'; |
| 7 | +const template = document.createElement('template'); |
| 8 | +template.innerHTML = ` |
| 9 | + <style> |
| 10 | + #fill { |
| 11 | + background-color: currentColor; |
| 12 | + box-sizing: border-box; |
| 13 | + height: 100%; |
| 14 | + width: 0%; |
| 15 | + } |
| 16 | + </style> |
| 17 | + <div id="fill"></div> |
| 18 | +`; |
| 19 | + |
| 20 | +/** |
| 21 | + * @private |
| 22 | + * @param {*} val - Value to coerce into an Integer |
| 23 | + * @returns {Integer} Integer value between hard-coded MIN and MAX |
| 24 | + */ |
| 25 | +function _parseValue (val) { |
| 26 | + // coerce into an Integer |
| 27 | + let safeVal = Math.round(Number(val) || MIN); |
| 28 | + // guard upper bound |
| 29 | + safeVal = safeVal > MAX ? MAX : safeVal; |
| 30 | + // guard lower bound |
| 31 | + safeVal = safeVal < MIN ? MIN : safeVal; |
| 32 | + |
| 33 | + return safeVal; |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * Defines behavior for the `<hx-progress>` custom element. |
| 38 | + * @class |
| 39 | + * @extends HXElement |
| 40 | + */ |
| 41 | +export class HXProgressElement extends HXElement { |
| 42 | + static get is () { |
| 43 | + return tagName; |
| 44 | + } |
| 45 | + |
| 46 | + constructor () { |
| 47 | + super(tagName, template); |
| 48 | + } |
| 49 | + |
| 50 | + connectedCallback () { |
| 51 | + this.$upgradeProperty('value'); |
| 52 | + this.$defaultAttribute('role', 'progressbar'); |
| 53 | + this.$defaultAttribute('aria-valuemin', MIN); |
| 54 | + this.$defaultAttribute('aria-valuemax', MAX); |
| 55 | + this.value = this.value; |
| 56 | + } |
| 57 | + |
| 58 | + static get observedAttributes () { |
| 59 | + return [ 'value' ]; |
| 60 | + } |
| 61 | + |
| 62 | + attributeChangedCallback (attr, oldVal, newVal) { |
| 63 | + if (newVal !== oldVal) { |
| 64 | + if (attr === 'value') { |
| 65 | + let safeVal = _parseValue(newVal); |
| 66 | + this._elFill.style.width = `${safeVal}%`; |
| 67 | + this.setAttribute('aria-valuenow', safeVal); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * Completion percentage |
| 74 | + * @type {Integer} |
| 75 | + */ |
| 76 | + get value () { |
| 77 | + return _parseValue(this.getAttribute('value')); |
| 78 | + } |
| 79 | + set value (newVal) { |
| 80 | + let safeVal = _parseValue(newVal); |
| 81 | + this.setAttribute('value', safeVal); |
| 82 | + } |
| 83 | + |
| 84 | + /** |
| 85 | + * @private |
| 86 | + * @type {HTMLElement} |
| 87 | + */ |
| 88 | + get _elFill () { |
| 89 | + return this.shadowRoot.getElementById('fill'); |
| 90 | + } |
| 91 | +}//HXBusyElement |
0 commit comments