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
This commit is contained in:
Paul T 2018-06-29 20:12:50 -04:00
parent ecf8e4c8f8
commit 1fdae261d4
2 changed files with 49 additions and 6 deletions

View file

@ -1,6 +1,6 @@
{ {
"name": "boxicons", "name": "boxicons",
"version": "1.0.6", "version": "1.1.1",
"private": true, "private": true,
"description": "High Quality web friendly icons", "description": "High Quality web friendly icons",
"scripts": { "scripts": {

View file

@ -44,7 +44,24 @@ export class BoxIconElement extends HTMLElement {
* @return {Promise<String, Error>} * @return {Promise<String, Error>}
*/ */
static getIconSvg(iconUrl) { 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 {
<style> <style>
:host { :host {
display: inline-block; display: inline-block;
width: 1rem; width: 1em;
height: 1rem; height: 1em;
} }
#icon, #icon,
svg { svg {
@ -76,10 +93,36 @@ ${transformationsCss}
</style> </style>
<div id="icon"></div>`; <div id="icon"></div>`;
this.$iconHolder = this.$ui.getElementById('icon'); this._state = {
$iconHolder: this.$ui.getElementById('icon'),
};
} }
attributeChangedCallback(attr, oldVal, newVal) { 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
});
}
}