cyp/app/js/elements/app.js
2020-03-16 22:57:13 +01:00

66 lines
1.6 KiB
JavaScript

import * as mpd from "../mpd.js";
import * as mpdMock from "../mpd-mock.js";
import * as html from "../html.js";
function initIcons() {
Array.from(document.querySelectorAll("[data-icon]")).forEach(/** @param {HTMLElement} node */ node => {
let icon = html.icon(node.dataset.icon);
node.insertBefore(icon, node.firstChild);
});
}
async function initMpd() {
try {
await mpd.init();
return mpd;
} catch (e) {
return mpdMock;
}
}
class App extends HTMLElement {
static get observedAttributes() { return ["component"]; }
constructor() {
super();
initIcons();
}
async connectedCallback() {
this.mpd = await initMpd();
const children = Array.from(this.querySelectorAll("*"));
const names = children.map(node => node.nodeName.toLowerCase())
.filter(name => name.startsWith("cyp-"));
const unique = new Set(names);
console.log(unique);
const promises = [...unique].map(name => customElements.whenDefined(name));
await Promise.all(promises);
this.dispatchEvent(new CustomEvent("load"));
const onHashChange = () => {
const component = location.hash.substring(1) || "queue";
if (component != this.component) { this.component = component; }
}
window.addEventListener("hashchange", onHashChange);
onHashChange();
}
attributeChangedCallback(name, oldValue, newValue) {
switch (name) {
case "component":
location.hash = newValue;
const e = new CustomEvent("component-change");
this.dispatchEvent(e);
break;
}
}
get component() { return this.getAttribute("component"); }
set component(component) { return this.setAttribute("component", component); }
}
customElements.define("cyp-app", App);