Skip to content

Commit

Permalink
Remove card-tools dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasloven committed Apr 3, 2023
1 parent f6f2641 commit b8c48b9
Show file tree
Hide file tree
Showing 16 changed files with 133 additions and 32 deletions.
4 changes: 2 additions & 2 deletions card-mod.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion hacs.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "card-mod",
"render_readme": true,
"homeassistant": "2023.4.0b0"
"homeassistant": "2023.4.0b5"
}
6 changes: 1 addition & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 2 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
{
"name": "card-mod",
"private": true,
"version": "3.2.1",
"version": "3.2.2",
"description": "",
"scripts": {
"build": "rollup -c",
"watch": "rollup -c --watch",
"update-card-tools": "npm uninstall card-tools && npm install thomasloven/lovelace-card-tools"
"watch": "rollup -c --watch"
},
"keywords": [],
"author": "Thomas Lovén",
Expand All @@ -19,7 +18,6 @@
"@rollup/plugin-babel": "^6.0.2",
"@rollup/plugin-json": "^5.0.1",
"@rollup/plugin-node-resolve": "^15.0.1",
"card-tools": "github:thomasloven/lovelace-card-tools",
"lit": "^2.4.1",
"rollup": "^3.4.0",
"rollup-plugin-typescript2": "^0.34.1",
Expand Down
9 changes: 6 additions & 3 deletions src/card-mod.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { LitElement, html } from "lit";
import { property } from "lit/decorators.js";
import { bind_template, unbind_template } from "./templates";
import { hasTemplate } from "card-tools/src/templates";
import {
hasTemplate,
bind_template,
unbind_template,
} from "./helpers/templates";
import pjson from "../package.json";
import { selectTree } from "card-tools/src/helpers";
import {
applyToElement,
compare_deep,
Expand All @@ -12,6 +14,7 @@ import {
parentElement,
Styles,
} from "./helpers";
import { selectTree } from "./helpers/selecttree";

export class CardMod extends LitElement {
type: string;
Expand Down
9 changes: 5 additions & 4 deletions src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { hass } from "card-tools/src/hass";
import { yaml2json } from "card-tools/src/yaml";
import { hass } from "./helpers/hass";
import { yaml2json } from "./helpers/yaml2json";
import { CardMod } from "./card-mod";

interface ModdedElement extends HTMLElement {
Expand Down Expand Up @@ -67,8 +67,9 @@ export async function get_theme(root: CardMod): Promise<Styles> {
.getComputedStyle(el)
.getPropertyValue("--card-mod-theme");

if (!hass()) return {};
const themes = hass()?.themes.themes ?? {};
const hs = await hass();
if (!hs) return {};
const themes = hs?.themes.themes ?? {};
if (!themes[theme]) return {};

if (themes[theme][`card-mod-${root.type}-yaml`]) {
Expand Down
6 changes: 6 additions & 0 deletions src/helpers/browser_id.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const ID_STORAGE_KEY = "browser_mod-browser-id";
export function BrowserID() {
if (document.querySelector("hc-main")) return "CAST";
if (localStorage[ID_STORAGE_KEY]) return localStorage[ID_STORAGE_KEY];
return "";
}
20 changes: 20 additions & 0 deletions src/helpers/hass.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export 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;
}
45 changes: 45 additions & 0 deletions src/helpers/selecttree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const TIMEOUT_ERROR = "SELECTTREE-TIMEOUT";

export async function await_element(el, hard = false) {
if (el.localName?.includes("-"))
await customElements.whenDefined(el.localName);
if (el.updateComplete) await el.updateComplete;
if (hard) {
if (el.pageRendered) await el.pageRendered;
if (el._panelState) {
let rounds = 0;
while (el._panelState !== "loaded" && rounds++ < 5)
await new Promise((r) => setTimeout(r, 100));
}
}
}

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_element(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;
});
}
15 changes: 10 additions & 5 deletions src/templates.ts → src/helpers/templates.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { hass } from "card-tools/src/hass";
import { deviceID } from "card-tools/src/deviceID";
import { hass } from "./hass";
import { BrowserID } from "./browser_id";

interface CachedTemplate {
template: string;
Expand Down Expand Up @@ -32,12 +32,17 @@ function template_updated(
cache.callbacks.forEach((f) => f(result.result));
}

export function hasTemplate(str) {
return String(str).includes("{%") || String(str).includes("{{");
}

export async function bind_template(
callback: (string) => void,
template: string,
variables: object
): Promise<void> {
const connection = hass().connection;
const hs = await hass();
const connection = hs.connection;

const cacheKey = JSON.stringify([template, variables]);
let cache = cachedTemplates[cacheKey];
Expand All @@ -46,8 +51,8 @@ export async function bind_template(
callback("");

variables = {
user: hass().user.name,
browser: deviceID,
user: hs.user.name,
browser: BrowserID(),
hash: location.hash.substr(1) || "",
...variables,
};
Expand Down
28 changes: 28 additions & 0 deletions src/helpers/yaml2json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const _load_yaml2json = async () => {
if (customElements.get("developer-tools-event")) return;

await customElements.whenDefined("partial-panel-resolver");
const ppr: any = document.createElement("partial-panel-resolver");

ppr.hass = {
panels: [
{
url_path: "tmp",
component_name: "developer-tools",
},
],
};
ppr._updateRoutes();

await ppr.routerOptions.routes.tmp.load();

await customElements.whenDefined("developer-tools-router");
const dtr: any = document.createElement("developer-tools-router");
await dtr.routerOptions.routes.event.load();
};

export const yaml2json = async (yaml) => {
await _load_yaml2json();
const el: any = document.createElement("developer-tools-event");
return el._computeParsedEventData(yaml);
};
2 changes: 0 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { fireEvent } from "card-tools/src/event.js";
import "./card-mod";
import "./patch/ha-card";
import "./patch/hui-entities-card";
Expand All @@ -20,7 +19,6 @@ const resources = getResources();
if (resources.some((r) => r.endsWith("card-mod.js"))) {
// console.info("Card-mod is loaded as a module");
} else {
fireEvent("ll-rebuild", {});
console.info(
"You may not be getting optimal performance out of card-mod.\nSee https://github.com/thomasloven/lovelace-card-mod#performance-improvements"
);
Expand Down
2 changes: 1 addition & 1 deletion src/patch/ha-more-info-dialog.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { selectTree } from "card-tools/src/helpers";
import { selectTree } from "../helpers/selecttree";
import { applyToElement } from "../helpers";

customElements.whenDefined("ha-more-info-dialog").then(() => {
Expand Down
2 changes: 1 addition & 1 deletion src/patch/ha-sidebar.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { selectTree } from "card-tools/src/helpers";
import { selectTree } from "../helpers/selecttree";
import { applyToElement } from "../helpers";

customElements.whenDefined("ha-sidebar").then(() => {
Expand Down
2 changes: 1 addition & 1 deletion src/patch/hui-root.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { selectTree } from "card-tools/src/helpers";
import { selectTree } from "../helpers/selecttree";
import { applyToElement } from "../helpers";

customElements.whenDefined("hui-root").then(() => {
Expand Down
7 changes: 4 additions & 3 deletions src/theme-watcher.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { hass } from "card-tools/src/hass";
import { hass } from "./helpers/hass";

function refresh_theme() {
document.dispatchEvent(new Event("cm_update"));
Expand All @@ -10,10 +10,11 @@ const bases = [
];
Promise.race(bases).then(() => {
window.setTimeout(async () => {
while (!hass()) {
const hs = await hass();
while (!hs) {
await new Promise((resolve) => window.setTimeout(resolve, 500));
}
hass().connection.subscribeEvents(() => {
hs.connection.subscribeEvents(() => {
window.setTimeout(refresh_theme, 500);
}, "themes_updated");
document
Expand Down

0 comments on commit b8c48b9

Please sign in to comment.