cyp/app/js/elements/app.js

66 lines
1.6 KiB
JavaScript
Raw Normal View History

2020-03-10 05:24:31 +08:00
import * as mpd from "../mpd.js";
import * as mpdMock from "../mpd-mock.js";
import * as html from "../html.js";
2020-03-09 05:11:46 +08:00
2019-03-29 05:52:57 +08:00
function initIcons() {
2020-03-09 16:26:10 +08:00
Array.from(document.querySelectorAll("[data-icon]")).forEach(/** @param {HTMLElement} node */ node => {
2019-03-29 05:52:57 +08:00
let icon = html.icon(node.dataset.icon);
node.insertBefore(icon, node.firstChild);
});
}
2020-03-09 21:26:39 +08:00
async function initMpd() {
try {
await mpd.init();
return mpd;
} catch (e) {
return mpdMock;
}
}
2020-03-09 05:11:46 +08:00
class App extends HTMLElement {
2020-03-09 16:26:10 +08:00
static get observedAttributes() { return ["component"]; }
2020-03-09 05:11:46 +08:00
constructor() {
super();
2019-03-26 19:35:47 +08:00
2020-03-09 16:26:10 +08:00
initIcons();
}
2019-03-20 03:45:23 +08:00
2020-03-09 21:26:39 +08:00
async connectedCallback() {
2020-03-10 05:24:31 +08:00
this.mpd = await initMpd();
2020-03-12 05:46:28 +08:00
const children = Array.from(this.querySelectorAll("*"));
const names = children.map(node => node.nodeName.toLowerCase())
.filter(name => name.startsWith("cyp-"));
const unique = new Set(names);
2020-03-09 21:26:39 +08:00
2020-03-12 05:46:28 +08:00
const promises = [...unique].map(name => customElements.whenDefined(name));
2020-03-09 05:11:46 +08:00
await Promise.all(promises);
2019-03-22 22:35:04 +08:00
2020-03-09 16:26:10 +08:00
this.dispatchEvent(new CustomEvent("load"));
2020-03-09 05:11:46 +08:00
const onHashChange = () => {
2020-03-13 23:52:24 +08:00
const component = location.hash.substring(1) || "queue";
if (component != this.component) { this.component = component; }
2020-03-09 05:11:46 +08:00
}
window.addEventListener("hashchange", onHashChange);
onHashChange();
}
2020-03-09 21:26:39 +08:00
attributeChangedCallback(name, oldValue, newValue) {
switch (name) {
case "component":
location.hash = newValue;
const e = new CustomEvent("component-change");
this.dispatchEvent(e);
break;
}
2020-03-09 05:11:46 +08:00
}
2020-03-13 23:52:24 +08:00
get component() { return this.getAttribute("component"); }
set component(component) { return this.setAttribute("component", component); }
2020-03-09 01:06:54 +08:00
}
customElements.define("cyp-app", App);