Linting and remove duplicate code

This commit is contained in:
Thomas Lovén 2021-05-10 09:41:47 +00:00
parent f342c20b91
commit f4ca95d436
14 changed files with 1356 additions and 3754 deletions

File diff suppressed because one or more lines are too long

View File

@ -1,30 +1,28 @@
import { registerCard } from "card-tools/src/editor";
const bases = [customElements.whenDefined('home-assistant-main'), customElements.whenDefined('hui-view')];
const bases = [
customElements.whenDefined("home-assistant-main"),
customElements.whenDefined("hui-view"),
];
Promise.race(bases).then(() => {
const LitElement = customElements.get('home-assistant-main')
? Object.getPrototypeOf(customElements.get('home-assistant-main'))
: Object.getPrototypeOf(customElements.get('hui-view'));
const LitElement = customElements.get("home-assistant-main")
? Object.getPrototypeOf(customElements.get("home-assistant-main"))
: Object.getPrototypeOf(customElements.get("hui-view"));
const html = LitElement.prototype.html;
const css = LitElement.prototype.css;
class BrowserPlayerEditor extends LitElement {
setConfig(config) {
}
render() {
return html`
<div>
Nothing to configure.
</div>
`;
}
setConfig(config) {}
render() {
return html` <div>Nothing to configure.</div> `;
}
}
if(!customElements.get("browser-player-editor")) {
if (!customElements.get("browser-player-editor")) {
customElements.define("browser-player-editor", BrowserPlayerEditor);
window.customCards = window.customCards || [];
window.customCards.push({type:"browser-player", name: "Browser Player", preview: true});
window.customCards.push({
type: "browser-player",
name: "Browser Player",
preview: true,
});
}
});

View File

@ -1,138 +1,136 @@
import { deviceID, setDeviceID } from "card-tools/src/deviceId"
import { moreInfo } from "card-tools/src/more-info"
import "./browser-player-editor.js"
import { deviceID, setDeviceID } from "card-tools/src/deviceID";
import { moreInfo } from "card-tools/src/more-info";
import "./browser-player-editor.js";
const bases = [customElements.whenDefined('home-assistant-main'), customElements.whenDefined('hui-view')];
const bases = [
customElements.whenDefined("home-assistant-main"),
customElements.whenDefined("hui-view"),
];
Promise.race(bases).then(() => {
const LitElement = customElements.get("home-assistant-main")
? Object.getPrototypeOf(customElements.get("home-assistant-main"))
: Object.getPrototypeOf(customElements.get("hui-view"));
const html = LitElement.prototype.html;
const css = LitElement.prototype.css;
const LitElement = customElements.get('home-assistant-main')
? Object.getPrototypeOf(customElements.get('home-assistant-main'))
: Object.getPrototypeOf(customElements.get('hui-view'));
const html = LitElement.prototype.html;
const css = LitElement.prototype.css;
class BrowserPlayer extends LitElement {
static get properties() {
return {
hass: {},
};
}
static getConfigElement() {
return document.createElement("browser-player-editor");
}
static getStubConfig() {
return {};
}
setConfig(config) {
this._config = config;
for (const event of ["play", "pause", "ended", "volumechange", "canplay", "loadeddata"])
window.browser_mod.player.addEventListener(event, () => this.requestUpdate());
}
handleMute(ev) {
window.browser_mod.player_mute();
}
handleVolumeChange(ev) {
const vol = parseFloat(ev.target.value);
window.browser_mod.player_set_volume(vol);
}
handleMoreInfo(ev) {
moreInfo("media_player."+window.browser_mod.entity_id);
}
handlePlayPause(ev) {
if (window.browser_mod.player.paused)
window.browser_mod.player_play();
else
window.browser_mod.player_pause();
}
setDeviceID() {
const newID = prompt("Set deviceID", deviceID);
if (newID !== deviceID) {
setDeviceID(newID);
this.requestUpdate();
class BrowserPlayer extends LitElement {
static get properties() {
return {
hass: {},
};
}
}
render() {
if(!window.browser_mod) {
window.setTimeout(() => this.requestUpdate(), 100);
return html``;
static getConfigElement() {
return document.createElement("browser-player-editor");
}
const player = window.browser_mod.player;
return html`
<ha-card>
<div class="card-content">
<ha-icon-button
.icon=${player.muted
? "mdi:volume-off"
: "mdi:volume-high"
static getStubConfig() {
return {};
}
setConfig(config) {
this._config = config;
for (const event of [
"play",
"pause",
"ended",
"volumechange",
"canplay",
"loadeddata",
])
window.browser_mod.player.addEventListener(event, () =>
this.requestUpdate()
);
}
handleMute(ev) {
window.browser_mod.player_mute();
}
handleVolumeChange(ev) {
const vol = parseFloat(ev.target.value);
window.browser_mod.player_set_volume(vol);
}
handleMoreInfo(ev) {
moreInfo("media_player." + window.browser_mod.entity_id);
}
handlePlayPause(ev) {
if (window.browser_mod.player.paused) window.browser_mod.player_play();
else window.browser_mod.player_pause();
}
setDeviceID() {
const newID = prompt("Set deviceID", deviceID);
if (newID !== deviceID) {
setDeviceID(newID);
this.requestUpdate();
}
}
render() {
if (!window.browser_mod) {
window.setTimeout(() => this.requestUpdate(), 100);
return html``;
}
const player = window.browser_mod.player;
return html`
<ha-card>
<div class="card-content">
<ha-icon-button
.icon=${player.muted ? "mdi:volume-off" : "mdi:volume-high"}
@click=${this.handleMute}
></ha-icon-button>
<ha-slider
min="0"
max="1"
step="0.01"
?disabled=${player.muted}
value=${player.volume}
@change=${this.handleVolumeChange}
></ha-slider>
${window.browser_mod.player_state === "stopped"
? html`<div class="placeholder"></div>`
: html`
<ha-icon-button
.icon=${player.paused ? "mdi:play" : "mdi:pause"}
@click=${this.handlePlayPause}
highlight
></ha-icon-button>
`}
<ha-icon-button
.icon=${"mdi:cog"}
@click=${this.handleMoreInfo}
></ha-icon-button>
</div>
<div class="device-id" @click=${this.setDeviceID}>${deviceID}</div>
</ha-card>
`;
}
static get styles() {
return css`
paper-icon-button[highlight] {
color: var(--accent-color);
}
@click=${this.handleMute}
></ha-icon-button>
<ha-slider
min=0
max=1
step=0.01
?disabled=${player.muted}
value=${player.volume}
@change=${this.handleVolumeChange}
></ha-slider>
${window.browser_mod.player_state === "stopped"
? html`<div class="placeholder"></div>`
: html`
<ha-icon-button
.icon=${player.paused
? "mdi:play"
: "mdi:pause"
}
@click=${this.handlePlayPause}
highlight
></ha-icon-button>
`}
<ha-icon-button
.icon=${"mdi:cog"}
@click=${this.handleMoreInfo}
></ha-icon-button>
</div>
<div class="device-id" @click=${this.setDeviceID}>
${deviceID}
</div>
</ha-card>
`;
.card-content {
display: flex;
justify-content: center;
}
.placeholder {
width: 24px;
padding: 8px;
}
.device-id {
opacity: 0.7;
font-size: xx-small;
margin-top: -10px;
user-select: all;
-webkit-user-select: all;
-moz-user-select: all;
-ms-user-select: all;
}
`;
}
}
static get styles() {
return css`
paper-icon-button[highlight] {
color: var(--accent-color);
}
.card-content {
display: flex;
justify-content: center;
}
.placeholder {
width: 24px;
padding: 8px;
}
.device-id {
opacity: 0.7;
font-size: xx-small;
margin-top: -10px;
user-select: all;
-webkit-user-select: all;
-moz-user-select: all;
-ms-user-select: all;
}
`
}
}
if(!customElements.get("browser-player"))
customElements.define("browser-player", BrowserPlayer);
if (!customElements.get("browser-player"))
customElements.define("browser-player", BrowserPlayer);
});

View File

@ -1,36 +1,52 @@
import { fireEvent } from "card-tools/src/event";
export const BrowserModBrowserMixin = (C) => class extends C {
export const BrowserModBrowserMixin = (C) =>
class extends C {
constructor() {
super();
document.addEventListener("visibilitychange", () => this.sensor_update());
window.addEventListener("location-changed", () => this.sensor_update());
super();
document.addEventListener("visibilitychange", () => this.sensor_update());
window.addEventListener("location-changed", () => this.sensor_update());
window.setInterval(() => this.sensor_update(), 10000);
window.setInterval(() => this.sensor_update(), 10000);
}
sensor_update() {
const update = async () => {
const battery = navigator.getBattery ? await navigator.getBattery() : undefined;
this.sendUpdate({browser: {
path: window.location.pathname,
visibility: document.visibilityState,
userAgent: navigator.userAgent,
currentUser: this._hass &&this._hass.user && this._hass.user.name,
fullyKiosk: this.isFully,
width: window.innerWidth,
height: window.innerHeight,
battery_level: this.isFully ? window.fully.getBatteryLevel() : battery ? battery.level*100 : undefined,
charging: this.isFully ? window.fully.isPlugged() : battery ? battery.charging : undefined,
}});
};
update();
const update = async () => {
const battery = navigator.getBattery
? await navigator.getBattery()
: undefined;
this.sendUpdate({
browser: {
path: window.location.pathname,
visibility: document.visibilityState,
userAgent: navigator.userAgent,
currentUser: this._hass && this._hass.user && this._hass.user.name,
fullyKiosk: this.isFully,
width: window.innerWidth,
height: window.innerHeight,
battery_level: this.isFully
? window.fully.getBatteryLevel()
: battery
? battery.level * 100
: undefined,
charging: this.isFully
? window.fully.isPlugged()
: battery
? battery.charging
: undefined,
},
});
};
update();
}
do_navigate(path) {
if (!path) return;
history.pushState(null, "", path);
fireEvent("location-changed", {}, document.querySelector("home-assistant"));
if (!path) return;
history.pushState(null, "", path);
fireEvent(
"location-changed",
{},
document.querySelector("home-assistant")
);
}
}
};

View File

@ -1,46 +1,57 @@
export const BrowserModCameraMixin = (C) => class extends C {
export const BrowserModCameraMixin = (C) =>
class extends C {
setup_camera() {
console.log("Starting camera");
console.log("Starting camera")
if (this._video) return;
this._video = document.createElement("video");
this._video.autoplay = true;
this._video.playsInline = true;
this._video.style.display = "none";
if(this._video) return;
this._video = document.createElement("video");
this._video.autoplay = true;
this._video.playsInline = true;
this._video.style.display = "none";
this._canvas = document.createElement("canvas");
this._canvas.style.display = "none";
this._canvas = document.createElement("canvas");
this._canvas.style.display = "none";
document.body.appendChild(this._video);
document.body.appendChild(this._canvas);
document.body.appendChild(this._video);
document.body.appendChild(this._canvas);
if (!navigator.mediaDevices) return;
if(!navigator.mediaDevices) return;
console.log("Starting devices");
navigator.mediaDevices
.getUserMedia({ video: true, audio: false })
.then((stream) => {
this._video.srcObject = stream;
this._video.play();
this.update_camera();
});
console.log("Starting devices")
navigator.mediaDevices.getUserMedia({video: true, audio: false}).then((stream) => {
this._video.srcObject = stream;
this._video.play();
this.update_camera();
})
this._camera_framerate = 2;
this._camera_framerate = 2;
window.addEventListener("click", () => this._video.play(), {once: true});
window.addEventListener("click", () => this._video.play(), {
once: true,
});
}
update_camera() {
this._canvas.width = this._video.videoWidth;
this._canvas.height = this._video.videoHeight;
this._canvas.width = this._video.videoWidth;
this._canvas.height = this._video.videoHeight;
const context = this._canvas.getContext('2d');
context.drawImage(this._video, 0, 0, this._video.videoWidth, this._video.videoHeight);
const context = this._canvas.getContext("2d");
context.drawImage(
this._video,
0,
0,
this._video.videoWidth,
this._video.videoHeight
);
this.sendUpdate({
camera: this._canvas.toDataURL('image/jpeg'),
});
setTimeout(() => this.update_camera(), Math.round(1000 / this._camera_framerate));
this.sendUpdate({
camera: this._canvas.toDataURL("image/jpeg"),
});
setTimeout(
() => this.update_camera(),
Math.round(1000 / this._camera_framerate)
);
}
}
};

View File

@ -1,51 +1,47 @@
import { deviceID } from "card-tools/src/deviceId";
import { deviceID } from "card-tools/src/deviceID";
import { hass, provideHass } from "card-tools/src/hass";
export class BrowserModConnection{
async connect() {
const isCast = document.querySelector("hc-main") !== null;
if(!isCast) {
if(!window.hassConnection) {
window.setTimeout(() => this.connect(), 100);
return;
} else {
this._connection = (await window.hassConnection).conn;
}
} else {
this._connection = hass().connection;
}
this._connection.subscribeMessage((msg) => this.msg_callback(msg), {
type: 'browser_mod/connect',
deviceID: deviceID,
});
this._hass_patched = false;
provideHass(this);
export class BrowserModConnection {
async connect() {
const isCast = document.querySelector("hc-main") !== null;
if (!isCast) {
if (!window.hassConnection) {
window.setTimeout(() => this.connect(), 100);
return;
} else {
this._connection = (await window.hassConnection).conn;
}
} else {
this._connection = hass().connection;
}
set hass(hass) {
this._hass = hass;
}
this._connection.subscribeMessage((msg) => this.msg_callback(msg), {
type: "browser_mod/connect",
deviceID: deviceID,
});
get connected() {
return this._connection !== undefined;
}
this._hass_patched = false;
provideHass(this);
}
msg_callback(message) {
console.log(message);
}
set hass(hass) {
this._hass = hass;
}
sendUpdate(data) {
if(!this.connected) return;
this._connection.sendMessage({
type: 'browser_mod/update',
deviceID,
data,
}
)
}
get connected() {
return this._connection !== undefined;
}
msg_callback(message) {
console.log(message);
}
sendUpdate(data) {
if (!this.connected) return;
this._connection.sendMessage({
type: "browser_mod/update",
deviceID,
data,
});
}
}

View File

@ -1,59 +1,70 @@
export const FullyKioskMixin = (C) => class extends C {
export const FullyKioskMixin = (C) =>
class extends C {
get isFully() {
return window.fully !== undefined;
return window.fully !== undefined;
}
constructor() {
super();
super();
if (!this.isFully) return;
if (!this.isFully) return;
this._fullyMotion = false;
this._motionTimeout = undefined;
this._fullyMotion = false;
this._motionTimeout = undefined;
for (const ev of ["screenOn", "screenOff", "pluggedAC", "pluggedUSB", "onBatteryLevelChanged", "unplugged", "networkReconnect", "onMotion"]) {
window.fully.bind(ev, `window.browser_mod.fully_update("${ev}");`);
}
for (const ev of [
"screenOn",
"screenOff",
"pluggedAC",
"pluggedUSB",
"onBatteryLevelChanged",
"unplugged",
"networkReconnect",
"onMotion",
]) {
window.fully.bind(ev, `window.browser_mod.fully_update("${ev}");`);
}
this._keepingAlive = false;
this._keepingAlive = false;
}
fully_update(event) {
if(!this.isFully) return
if(event === "screenOn") {
window.clearTimeout(this._keepAliveTimer);
if(!this._keepingAlive)
this.screen_update();
} else if (event === "screenOff") {
this.screen_update();
this._keepingAlive = false;
if(this.config.force_stay_awake) {
this._keepAliveTimer = window.setTimeout(() => {
this._keepingAlive = true;
window.fully.turnScreenOn();
window.fully.turnScreenOff();
}, 270000);
}
} else if (event === "onMotion") {
this.fullyMotionTriggered();
if (!this.isFully) return;
if (event === "screenOn") {
window.clearTimeout(this._keepAliveTimer);
if (!this._keepingAlive) this.screen_update();
} else if (event === "screenOff") {
this.screen_update();
this._keepingAlive = false;
if (this.config.force_stay_awake) {
this._keepAliveTimer = window.setTimeout(() => {
this._keepingAlive = true;
window.fully.turnScreenOn();
window.fully.turnScreenOff();
}, 270000);
}
} else if (event === "onMotion") {
this.fullyMotionTriggered();
}
this.sendUpdate({fully: {
battery: window.fully.getBatteryLevel(),
charging: window.fully.isPlugged(),
motion: this._fullyMotion,
ip: window.fully.getIp4Address(),
}})
this.sendUpdate({
fully: {
battery: window.fully.getBatteryLevel(),
charging: window.fully.isPlugged(),
motion: this._fullyMotion,
ip: window.fully.getIp4Address(),
},
});
}
fullyMotionTriggered() {
if(this._keepingAlive) return;
this._fullyMotion = true;
clearTimeout(this._motionTimeout);
this._motionTimeout = setTimeout(() => {
this._fullyMotion = false;
this.fully_update();
}, 5000);
if (this._keepingAlive) return;
this._fullyMotion = true;
clearTimeout(this._motionTimeout);
this._motionTimeout = setTimeout(() => {
this._fullyMotion = false;
this.fully_update();
}, 5000);
this.fully_update();
}
}
};

View File

@ -1,4 +1,4 @@
import { deviceID } from "card-tools/src/deviceId";
import { deviceID } from "card-tools/src/deviceID";
import { lovelace_view } from "card-tools/src/hass";
import { popUp } from "card-tools/src/popup";
import { fireEvent } from "card-tools/src/event";
@ -12,7 +12,6 @@ import { BrowserModScreensaverMixin } from "./screensaver";
import { BrowserModPopupsMixin } from "./popups";
import { BrowserModBrowserMixin } from "./browser";
const ext = (baseClass, mixins) =>
mixins.reduceRight((base, mixin) => mixin(base), baseClass);
@ -23,9 +22,7 @@ class BrowserMod extends ext(BrowserModConnection, [
BrowserModCameraMixin,
FullyKioskMixin,
BrowserModMediaPlayerMixin,
]) {
]) {
constructor() {
super();
this.entity_id = deviceID.replace("-", "_");
@ -33,15 +30,18 @@ class BrowserMod extends ext(BrowserModConnection, [
this.connect();
document.body.addEventListener("ll-custom", (ev) => {
if(ev.detail.browser_mod) {
if (ev.detail.browser_mod) {
this.msg_callback(ev.detail.browser_mod);
}
})
});
const pjson = require('../package.json');
console.info(`%cBROWSER_MOD ${pjson.version} IS INSTALLED
const pjson = require("../package.json");
console.info(
`%cBROWSER_MOD ${pjson.version} IS INSTALLED
%cDeviceID: ${deviceID}`,
"color: green; font-weight: bold", "");
"color: green; font-weight: bold",
""
);
}
async msg_callback(msg) {
@ -65,83 +65,88 @@ class BrowserMod extends ext(BrowserModConnection, [
"lovelace-reload": (msg) => this.lovelace_reload(msg),
"window-reload": () => window.location.reload(),
blackout: (msg) => this.do_blackout(msg.time ? parseInt(msg.time) : undefined),
blackout: (msg) =>
this.do_blackout(msg.time ? parseInt(msg.time) : undefined),
"no-blackout": (msg) => {
if(msg.brightness && this.isFully) {
if (msg.brightness && this.isFully) {
window.fully.setScreenBrightness(msg.brightness);
}
this.no_blackout()
this.no_blackout();
},
"call-service": (msg) => this.call_service(msg),
"commands": async (msg) => {
for(const m of msg.commands) {
commands: async (msg) => {
for (const m of msg.commands) {
await this.msg_callback(m);
}
},
"delay": async (msg) => await new Promise((resolve) => {window.setTimeout(resolve, msg.seconds*1000)}),
delay: async (msg) =>
await new Promise((resolve) => {
window.setTimeout(resolve, msg.seconds * 1000);
}),
};
await handlers[msg.command.replace("_","-")](msg);
await handlers[msg.command.replace("_", "-")](msg);
}
debug(msg) {
popUp(`deviceID`, {type: "markdown", content: `# ${deviceID}`})
popUp(`deviceID`, { type: "markdown", content: `# ${deviceID}` });
alert(deviceID);
}
set_theme(msg){
if(!msg.theme) msg.theme = "default";
fireEvent("settheme", {theme: msg.theme}, document.querySelector("home-assistant"));
set_theme(msg) {
if (!msg.theme) msg.theme = "default";
fireEvent(
"settheme",
{ theme: msg.theme },
document.querySelector("home-assistant")
);
}
lovelace_reload(msg) {
const ll = lovelace_view();
if (ll)
fireEvent("config-refresh", {}, ll);
if (ll) fireEvent("config-refresh", {}, ll);
}
call_service(msg) {
const _replaceThis = (data) => {
if (typeof(data) === "string" && data === "this")
return deviceID;
if (Array.isArray(data))
return data.map(_replaceThis);
if (typeof data === "string" && data === "this") return deviceID;
if (Array.isArray(data)) return data.map(_replaceThis);
if (data.constructor == Object) {
for (const key in data)
data[key] = _replaceThis(data[key]);
for (const key in data) data[key] = _replaceThis(data[key]);
}
return data;
}
const [domain, service] = msg.service.split(".", 2);
let service_data = _replaceThis(JSON.parse(JSON.stringify(msg.service_data)));
};
const [domain, service] = msg.service.split(".", 2);
let service_data = _replaceThis(
JSON.parse(JSON.stringify(msg.service_data))
);
this._hass.callService(domain, service, service_data);
}
update(msg=null) {
if(msg) {
if(msg.name) {
update(msg = null) {
if (msg) {
if (msg.name) {
this.entity_id = msg.name.toLowerCase();
}
if(msg.camera) {
if (msg.camera) {
this.setup_camera();
}
this.config = {...this.config, ...msg};
this.config = { ...this.config, ...msg };
}
this.player_update();
this.fully_update();
this.screen_update();
this.sensor_update();
}
}
const bases = [customElements.whenDefined('home-assistant'), customElements.whenDefined('hc-main')];
const bases = [
customElements.whenDefined("home-assistant"),
customElements.whenDefined("hc-main"),
];
Promise.race(bases).then(() => {
window.setTimeout(() => {
window.browser_mod = window.browser_mod || new BrowserMod();
},
1000
);
}, 1000);
});

View File

@ -1,51 +1,53 @@
export const BrowserModMediaPlayerMixin = (C) => class extends C {
export const BrowserModMediaPlayerMixin = (C) =>
class extends C {
constructor() {
super();
this.player = new Audio();
super();
this.player = new Audio();
for (const event of ["play", "pause", "ended", "volumechange"]) {
this.player.addEventListener(event, () => this.player_update());
}
for (const event of ["play", "pause", "ended", "volumechange"]) {
this.player.addEventListener(event, () => this.player_update());
}
window.addEventListener("click", () => this.player.play(), {once: true});
window.addEventListener("click", () => this.player.play(), {
once: true,
});
}
player_update(ev) {
this.sendUpdate({player: {
volume: this.player.volume,
muted: this.player.muted,
src: this.player.src,
state: this.player_state,
}})
this.sendUpdate({
player: {
volume: this.player.volume,
muted: this.player.muted,
src: this.player.src,
state: this.player_state,
},
});
}
get player_state() {
if (!this.player.src) return "stopped";
if (this.player.ended) return "stopped";
if (this.player.paused) return "paused";
return "playing";
if (!this.player.src) return "stopped";
if (this.player.ended) return "stopped";
if (this.player.paused) return "paused";
return "playing";
}
player_play(src) {
if(src)
this.player.src = src;
this.player.play();
if (src) this.player.src = src;
this.player.play();
}
player_pause() {
this.player.pause();
this.player.pause();
}
player_stop() {
this.player.pause();
this.player.src = null;
this.player.pause();
this.player.src = null;
}
player_set_volume(level) {
if(level === undefined) return;
this.player.volume = level;
if (level === undefined) return;
this.player.volume = level;
}
player_mute(mute) {
if(mute === undefined)
mute = !this.player.muted;
this.player.muted = Boolean(mute);
if (mute === undefined) mute = !this.player.muted;
this.player.muted = Boolean(mute);
}
}
};

View File

@ -3,77 +3,87 @@ import { load_lovelace, lovelace } from "card-tools/src/hass";
import { moreInfo } from "card-tools/src/more-info";
import { closePopUp, popUp } from "card-tools/src/popup";
export const BrowserModPopupsMixin = (C) => class extends C {
export const BrowserModPopupsMixin = (C) =>
class extends C {
constructor() {
super();
if (document.querySelector("home-assistant"))
document.querySelector("home-assistant").addEventListener("hass-more-info", (ev) => this._popup_card(ev));
super();
if (document.querySelector("home-assistant"))
document
.querySelector("home-assistant")
.addEventListener("hass-more-info", (ev) => this._popup_card(ev));
const isCast = document.querySelector("hc-main") !== null;
if(!isCast)
load_lovelace();
const isCast = document.querySelector("hc-main") !== null;
if (!isCast) load_lovelace();
}
_popup_card(ev) {
if(!lovelace()) return;
if(!ev.detail || !ev.detail.entityId) return;
const data = {
...lovelace().config.popup_cards,
...lovelace().config.views[lovelace().current_view].popup_cards,
};
const d = data[ev.detail.entityId];
if(!d) return;
if (!lovelace()) return;
if (!ev.detail || !ev.detail.entityId) return;
const data = {
...lovelace().config.popup_cards,
...lovelace().config.views[lovelace().current_view].popup_cards,
};
const d = data[ev.detail.entityId];
if (!d) return;
popUp(
d.title,
d.card,
d.large || false,
d.style
this.do_popup(d);
window.setTimeout(() => {
fireEvent(
"hass-more-info",
{ entityID: "." },
document.querySelector("home-assistant")
);
window.setTimeout(() => {
fireEvent("hass-more-info", {entityID: "."}, document.querySelector("home-assistant"));
}, 50);
}, 50);
}
do_popup(cfg) {
if (!(cfg.title || cfg.auto_close || cfg.hide_header)) return;
if (!cfg.card) return;
if (!(cfg.title || cfg.auto_close || cfg.hide_header)) {
console.error(
"browser_mod: popup: Must specify title, auto_close or hide_header."
);
return;
}
if (!cfg.card) {
console.error("browser_mod: popup: No card specified");
return;
}
const open = () => {
popUp(
cfg.title,
cfg.card,
cfg.large,
cfg.style,
cfg.auto_close || cfg.hide_header,
);
};
const open = () => {
popUp(
cfg.title,
cfg.card,
cfg.large,
cfg.style,
cfg.auto_close || cfg.hide_header
);
};
if(cfg.auto_close) {
this.screensaver_set(open, closePopUp, cfg.time);
} else {
open();
}
if (cfg.auto_close) {
this.screensaver_set(open, closePopUp, cfg.time);
} else {
open();
}
}
do_close_popup() {
this.screensaver_stop();
closePopUp();
this.screensaver_stop();
closePopUp();
}
do_more_info(entity_id, large) {
if (!entity_id) return;
moreInfo(entity_id, large);
if (!entity_id) return;
moreInfo(entity_id, large);
}
do_toast(message, duration) {
if (!message) return;
fireEvent("hass-notification", {
message,
duration: parseInt(duration),
}, document.querySelector("home-assistant"));
if (!message) return;
fireEvent(
"hass-notification",
{
message,
duration: parseInt(duration),
},
document.querySelector("home-assistant")
);
}
}
};

View File

@ -1,22 +1,23 @@
export const BrowserModScreensaverMixin = (C) => class extends C {
export const BrowserModScreensaverMixin = (C) =>
class extends C {
constructor() {
super();
this._blackout_panel = document.createElement("div");
super();
this._blackout_panel = document.createElement("div");
this._screenSaver = undefined;
this._screenSaverTimer = undefined;
this._screenSaverTimeOut = 0;
this._screenSaver = undefined;
this._screenSaverTimer = undefined;
this._screenSaverTimeOut = 0;
this._screenSaver = {
fn: undefined,
clearfn: undefined,
timer: undefined,
timeout: undefined,
listeners : {},
active: false,
};
this._screenSaver = {
fn: undefined,
clearfn: undefined,
timer: undefined,
timeout: undefined,
listeners: {},
active: false,
};
this._blackout_panel.style.cssText = `
this._blackout_panel.style.cssText = `
position: fixed;
left: 0;
top: 0;
@ -27,95 +28,100 @@ export const BrowserModScreensaverMixin = (C) => class extends C {
background: black;
display: none;
`;
document.body.appendChild(this._blackout_panel);
document.body.appendChild(this._blackout_panel);
}
screensaver_set(fn, clearfn, time) {
this._ss_clear();
this._screenSaver = {
fn,
clearfn,
timer: undefined,
timeout: time,
listeners: {},
active: false,
}
const l = () => this.screensaver_update();
for(const event of ["mousemove", "mousedown", "keydown", "touchstart"]) {
window.addEventListener(event, l);
this._screenSaver.listeners[event] = l;
}
this._screenSaver.timer = window.setTimeout(() => this._ss_run(), time*1000);
this._ss_clear();
this._screenSaver = {
fn,
clearfn,
timer: undefined,
timeout: time,
listeners: {},
active: false,
};
const l = () => this.screensaver_update();
for (const event of ["mousemove", "mousedown", "keydown", "touchstart"]) {
window.addEventListener(event, l);
this._screenSaver.listeners[event] = l;
}
this._screenSaver.timer = window.setTimeout(
() => this._ss_run(),
time * 1000
);
}
screensaver_update() {
if (this._screenSaver.active) {
this.screensaver_stop();
} else {
window.clearTimeout(this._screenSaver.timer);
this._screenSaver.timer = window.setTimeout(() => this._ss_run(), this._screenSaver.timeout*1000);
}
if (this._screenSaver.active) {
this.screensaver_stop();
} else {
window.clearTimeout(this._screenSaver.timer);
this._screenSaver.timer = window.setTimeout(
() => this._ss_run(),
this._screenSaver.timeout * 1000
);
}
}
screensaver_stop() {
this._ss_clear();
this._screenSaver.active = false;
if(this._screenSaver.clearfn)
this._screenSaver.clearfn();
if(this._screenSaver.timeout) {
this.screensaver_set(
this._screenSaver.fn,
this._screenSaver.clearfn,
this._screenSaver.timeout,
);
}
this._ss_clear();
this._screenSaver.active = false;
if (this._screenSaver.clearfn) this._screenSaver.clearfn();
if (this._screenSaver.timeout) {
this.screensaver_set(
this._screenSaver.fn,
this._screenSaver.clearfn,
this._screenSaver.timeout
);
}
}
_ss_clear() {
window.clearTimeout(this._screenSaverTimer);
for(const [k, v] of Object.entries(this._screenSaver.listeners)) {
window.removeEventListener(k, v);
}
window.clearTimeout(this._screenSaverTimer);
for (const [k, v] of Object.entries(this._screenSaver.listeners)) {
window.removeEventListener(k, v);
}
}
_ss_run() {
this._screenSaver.active = true;
this._screenSaver.fn();
this._screenSaver.active = true;
this._screenSaver.fn();
}
do_blackout(timeout) {
this.screensaver_set(
() => {
if(this.isFully)
window.fully.turnScreenOff(true);
else
this._blackout_panel.style.display = "block";
this.screen_update();
},
() => {
if(this._blackout_panel.style.display = "block")
this._blackout_panel.style.display = "none"
if(this.isFully && !window.fully.getScreenOn())
window.fully.turnScreenOn();
this.screen_update();
},
timeout || 0
);
this.screensaver_set(
() => {
if (this.isFully) window.fully.turnScreenOff(true);
else this._blackout_panel.style.display = "block";
this.screen_update();
},
() => {
if ((this._blackout_panel.style.display = "block"))
this._blackout_panel.style.display = "none";
if (this.isFully && !window.fully.getScreenOn())
window.fully.turnScreenOn();
this.screen_update();
},
timeout || 0
);
}
no_blackout() {
if(this.isFully)
window.fully.turnScreenOn();
this.screensaver_stop();
if (this.isFully) window.fully.turnScreenOn();
this.screensaver_stop();
}
screen_update() {
this.sendUpdate({screen: {
blackout: this.isFully
? !window.fully.getScreenOn()
: Boolean(this._blackout_panel.style.display === "block"),
brightness: this.isFully ? window.fully.getScreenBrightness() : undefined,
}})
this.sendUpdate({
screen: {
blackout: this.isFully
? !window.fully.getScreenOn()
: Boolean(this._blackout_panel.style.display === "block"),
brightness: this.isFully
? window.fully.getScreenBrightness()
: undefined,
},
});
}
}
};

3645
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -12,8 +12,8 @@
"author": "Thomas Lovén",
"license": "MIT",
"devDependencies": {
"webpack": "^4.46.0",
"webpack-cli": "^3.3.12"
"webpack": "^5.36.2",
"webpack-cli": "^4.7.0"
},
"dependencies": {
"card-tools": "github:thomasloven/lovelace-card-tools"

View File

@ -45,6 +45,8 @@ views:
card:
type: markdown
content: Local popup for climate.hvac
light.kitchen_lights:
type: No card
cards:
- type: button
@ -57,3 +59,8 @@ views:
name: Override global popup-card
tap_action:
action: more-info
- type: button
entity: light.kitchen_lights
name: No card config
tap_action:
action: more-info