From 1fdae261d4ea872a3db4654e8df149b590118c9f Mon Sep 17 00:00:00 2001 From: Paul T Date: Fri, 29 Jun 2018 20:12:50 -0400 Subject: [PATCH] Support for `name` attribute - support the `name` attribute on the html element - Loads svg image and caches - Changed version in package.json to take advantage of images included in v1.1.1 --- package.json | 2 +- src/box-icon-element.js | 53 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 49 insertions(+), 6 deletions(-) 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 + }); + } +} +