64 lines
1.6 KiB
TypeScript
64 lines
1.6 KiB
TypeScript
const TIMEOUT_ERROR = "SLECTTREE-TIMEOUT";
|
|
|
|
async function _await_el(el) {
|
|
if (el.localName?.includes("-"))
|
|
await customElements.whenDefined(el.localName);
|
|
if (el.updateComplete) await el.updateComplete;
|
|
}
|
|
|
|
async function _selectTree(root, path, all = false) {
|
|
let el = [root];
|
|
if (typeof path === "string") {
|
|
path = path.split(/(\$| )/);
|
|
}
|
|
while (path[path.length - 1] === "") path.pop();
|
|
for (const [i, p] of path.entries()) {
|
|
const e = el[0];
|
|
if (!e) return null;
|
|
|
|
if (!p.trim().length) continue;
|
|
|
|
_await_el(e);
|
|
el = p === "$" ? [e.shadowRoot] : e.querySelectorAll(p);
|
|
}
|
|
return all ? el : el[0];
|
|
}
|
|
|
|
export async function selectTree(root, path, all = false, timeout = 10000) {
|
|
return Promise.race([
|
|
_selectTree(root, path, all),
|
|
new Promise((_, reject) =>
|
|
setTimeout(() => reject(new Error(TIMEOUT_ERROR)), timeout)
|
|
),
|
|
]).catch((err) => {
|
|
if (!err.message || err.message !== TIMEOUT_ERROR) throw err;
|
|
return null;
|
|
});
|
|
}
|
|
|
|
async function _hass_base_el() {
|
|
await Promise.race([
|
|
customElements.whenDefined("home-assistant"),
|
|
customElements.whenDefined("hc-main"),
|
|
]);
|
|
|
|
const element = customElements.get("home-assistant")
|
|
? "home-assistant"
|
|
: "hc-main";
|
|
|
|
while (!document.querySelector(element))
|
|
await new Promise((r) => window.setTimeout(r, 100));
|
|
return document.querySelector(element);
|
|
}
|
|
|
|
export async function hass() {
|
|
const base: any = await _hass_base_el();
|
|
while (!base.hass) await new Promise((r) => window.setTimeout(r, 100));
|
|
return base.hass;
|
|
}
|
|
|
|
export async function provideHass(el) {
|
|
const base: any = await _hass_base_el();
|
|
base.provideHass(el);
|
|
}
|