diff --git a/package.json b/package.json index 0354c2e..f936065 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "boxicons", - "version": "1.0.6", + "version": "1.1.1", "private": true, "description": "High Quality web friendly icons", "scripts": { diff --git a/src/box-icon-element.js b/src/box-icon-element.js index 7df16bb..3d49633 100644 --- a/src/box-icon-element.js +++ b/src/box-icon-element.js @@ -44,7 +44,24 @@ export class BoxIconElement extends HTMLElement { * @return {Promise} */ static getIconSvg(iconUrl) { - + if (iconUrl && CACHE[iconUrl]) { + return CACHE[iconUrl]; + } + CACHE[iconUrl] = new Promise((resolve, reject) => { + const request = new XMLHttpRequest(); + request.addEventListener('load', function () { + if (this.status < 200 || this.status >= 300) { + reject(new Error(`${this.status} ${this.responseText}`)); + return; + } + resolve(this.responseText); + }); + request.onerror = reject; + request.onabort = reject; + request.open('GET', iconUrl); + request.send(); + }); + return CACHE[iconUrl]; } /** @@ -63,8 +80,8 @@ export class BoxIconElement extends HTMLElement {
`; - this.$iconHolder = this.$ui.getElementById('icon'); + this._state = { + $iconHolder: this.$ui.getElementById('icon'), + }; } attributeChangedCallback(attr, oldVal, newVal) { - // handle live changes + switch (attr) { + case 'name': + handleNameChange(this, oldVal, newVal); + break; + + } } } + +function handleNameChange(inst, oldVal, newVal) { + inst._state.currentName = newVal; + inst._state.$iconHolder.textContent = ''; + + if (newVal) { + const iconUrl = `${inst.constructor.cdnUrl}/${newVal}.svg`; + inst.constructor.getIconSvg(iconUrl) + .then((iconData) => { + if (inst._state.currentName === newVal) { + inst._state.$iconHolder.innerHTML = iconData; + } + }) + .catch((error) => { + console.error(`Failed to load icon: ${iconUrl + "\n"}${error}`); //eslint-disable-line + }); + } +} +