Compare commits

..

1 Commits

Author SHA1 Message Date
Joakim Sørensen
0bfeb22209 Move snapshot toggle to persistent checkbox 2021-06-15 16:40:24 +00:00
130 changed files with 2496 additions and 8454 deletions

View File

@@ -5,6 +5,8 @@ const paths = require("./paths.js");
// Files from NPM Packages that should not be imported
module.exports.ignorePackages = ({ latestBuild }) => [
// Bloats bundle and it's not used.
path.resolve(require.resolve("moment"), "../locale"),
// Part of yaml.js and only used for !!js functions that we don't use
require.resolve("esprima"),
];

View File

@@ -302,23 +302,15 @@ gulp.task("gen-index-hassio-prod", async () => {
function writeHassioEntrypoint(latestEntrypoint, es5Entrypoint) {
fs.mkdirSync(paths.hassio_output_root, { recursive: true });
// Safari 12 and below does not have a compliant ES2015 implementation of template literals, so we ship ES5
fs.writeFileSync(
path.resolve(paths.hassio_output_root, "entrypoint.js"),
`
function loadES5() {
try {
new Function("import('${latestEntrypoint}')")();
} catch (err) {
var el = document.createElement('script');
el.src = '${es5Entrypoint}';
document.body.appendChild(el);
}
if (/.*Version\\/(?:11|12)(?:\\.\\d+)*.*Safari\\//.test(navigator.userAgent)) {
loadES5();
} else {
try {
new Function("import('${latestEntrypoint}')")();
} catch (err) {
loadES5();
}
}
`,
{ encoding: "utf-8" }

View File

@@ -19,12 +19,10 @@ const bothBuilds = (createConfigFunc, params) => [
createConfigFunc({ ...params, latestBuild: false }),
];
const isWsl =
fs.existsSync("/proc/version") &&
fs
.readFileSync("/proc/version", "utf-8")
.toLocaleLowerCase()
.includes("microsoft");
const isWsl = fs
.readFileSync("/proc/version", "utf-8")
.toLocaleLowerCase()
.includes("microsoft");
/**
* @param {{
@@ -86,11 +84,10 @@ const prodBuild = (conf) =>
gulp.task("webpack-watch-app", () => {
// This command will run forever because we don't close compiler
webpack(
process.env.ES5
? bothBuilds(createAppConfig, { isProdBuild: false })
: createAppConfig({ isProdBuild: false, latestBuild: true })
).watch({ ignored: /build-translations/, poll: isWsl }, doneHandler());
webpack(createAppConfig({ isProdBuild: false, latestBuild: true })).watch(
{ ignored: /build-translations/, poll: isWsl },
doneHandler()
);
gulp.watch(
path.join(paths.translations_src, "en.json"),
gulp.series("build-translations", "copy-translations-app")

View File

@@ -134,7 +134,7 @@ class HassioAddonConfig extends LitElement {
></ha-form>`
: html` <ha-yaml-editor
@value-changed=${this._configChanged}
.yamlSchema=${ADDON_YAML_SCHEMA}
.schema=${ADDON_YAML_SCHEMA}
></ha-yaml-editor>`}
${this._error ? html` <div class="errors">${this._error}</div> ` : ""}
${!this._yamlMode ||
@@ -269,9 +269,6 @@ class HassioAddonConfig extends LitElement {
private async _saveTapped(ev: CustomEvent): Promise<void> {
const button = ev.currentTarget as any;
const options: Record<string, unknown> = this._yamlMode
? this._editor?.value
: this._options;
const eventdata = {
success: true,
response: undefined,
@@ -285,13 +282,13 @@ class HassioAddonConfig extends LitElement {
const validation = await validateHassioAddonOption(
this.hass,
this.addon.slug,
options
this._editor?.value
);
if (!validation.valid) {
throw Error(validation.message);
}
await setHassioAddonOption(this.hass, this.addon.slug, {
options,
options: this._yamlMode ? this._editor?.value : this._options,
});
this._configHasChanged = false;

View File

@@ -892,19 +892,10 @@ class HassioAddonInfo extends LitElement {
private async _openChangelog(): Promise<void> {
try {
let content = await fetchHassioAddonChangelog(this.hass, this.addon.slug);
if (
content.includes(`# ${this.addon.version}`) &&
content.includes(`# ${this.addon.version_latest}`)
) {
const newcontent = content.split(`# ${this.addon.version}`)[0];
if (newcontent.includes(`# ${this.addon.version_latest}`)) {
// Only change the content if the new version still exist
// if the changelog does not have the newests version on top
// this will not be true, and we don't modify the content
content = newcontent;
}
}
const content = await fetchHassioAddonChangelog(
this.hass,
this.addon.slug
);
showHassioMarkdownDialog(this, {
title: this.supervisor.localize("addon.dashboard.changelog"),
content,
@@ -986,6 +977,7 @@ class HassioAddonInfo extends LitElement {
showDialogSupervisorUpdate(this, {
supervisor: this.supervisor,
name: this.addon.name,
slug: this.addon.slug,
version: this.addon.version_latest,
snapshotParams: {
name: `addon_${this.addon.slug}_${this.addon.version}`,

View File

@@ -86,7 +86,7 @@ export class HassioUpdate extends LitElement {
"hassio/supervisor/update",
`https://github.com//home-assistant/hassio/releases/tag/${this.supervisor.supervisor.version_latest}`
)}
${this.supervisor.host.features.includes("haos")
${this.supervisor.host.features.includes("hassos")
? this._renderUpdateCard(
"Operating System",
"os",
@@ -161,6 +161,7 @@ export class HassioUpdate extends LitElement {
showDialogSupervisorUpdate(this, {
supervisor: this.supervisor,
name: "Home Assistant Core",
slug: "core",
version: this.supervisor.core.version_latest,
snapshotParams: {
name: `core_${this.supervisor.core.version}`,

View File

@@ -2,19 +2,32 @@ import "@material/mwc-button/mwc-button";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, state } from "lit/decorators";
import { fireEvent } from "../../../../src/common/dom/fire_event";
import "../../../../src/components/ha-checkbox";
import "../../../../src/components/ha-circular-progress";
import "../../../../src/components/ha-dialog";
import "../../../../src/components/ha-settings-row";
import "../../../../src/components/ha-svg-icon";
import "../../../../src/components/ha-switch";
import {
extractApiErrorMessage,
ignoreSupervisorError,
} from "../../../../src/data/hassio/common";
import {
SupervisorFrontendPrefrences,
fetchSupervisorFrontendPreferences,
saveSupervisorFrontendPreferences,
} from "../../../../src/data/supervisor/supervisor";
import { createHassioPartialSnapshot } from "../../../../src/data/hassio/snapshot";
import { haStyle, haStyleDialog } from "../../../../src/resources/styles";
import type { HomeAssistant } from "../../../../src/types";
import { SupervisorDialogSupervisorUpdateParams } from "./show-dialog-update";
import memoizeOne from "memoize-one";
const snapshot_before_update = memoizeOne(
(slug: string, frontendPrefrences: SupervisorFrontendPrefrences) =>
slug in frontendPrefrences.snapshot_before_update
? frontendPrefrences.snapshot_before_update[slug]
: true
);
@customElement("dialog-supervisor-update")
class DialogSupervisorUpdate extends LitElement {
@@ -22,12 +35,12 @@ class DialogSupervisorUpdate extends LitElement {
@state() private _opened = false;
@state() private _createSnapshot = true;
@state() private _action: "snapshot" | "update" | null = null;
@state() private _error?: string;
@state() private _frontendPrefrences?: SupervisorFrontendPrefrences;
@state()
private _dialogParams?: SupervisorDialogSupervisorUpdateParams;
@@ -36,14 +49,17 @@ class DialogSupervisorUpdate extends LitElement {
): Promise<void> {
this._opened = true;
this._dialogParams = params;
this._frontendPrefrences = await fetchSupervisorFrontendPreferences(
this.hass
);
await this.updateComplete;
}
public closeDialog(): void {
this._action = null;
this._createSnapshot = true;
this._error = undefined;
this._dialogParams = undefined;
this._frontendPrefrences = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
}
@@ -56,7 +72,7 @@ class DialogSupervisorUpdate extends LitElement {
}
protected render(): TemplateResult {
if (!this._dialogParams) {
if (!this._dialogParams || !this._frontendPrefrences) {
return html``;
}
return html`
@@ -82,6 +98,16 @@ class DialogSupervisorUpdate extends LitElement {
</div>
<ha-settings-row>
<ha-checkbox
.checked=${snapshot_before_update(
this._dialogParams.slug,
this._frontendPrefrences
)}
haptic
@click=${this._toggleSnapshot}
slot="prefix"
>
</ha-checkbox>
<span slot="heading">
${this._dialogParams.supervisor.localize(
"dialog.update.snapshot"
@@ -94,12 +120,6 @@ class DialogSupervisorUpdate extends LitElement {
this._dialogParams.name
)}
</span>
<ha-switch
.checked=${this._createSnapshot}
haptic
@click=${this._toggleSnapshot}
>
</ha-switch>
</ha-settings-row>
<mwc-button @click=${this.closeDialog} slot="secondaryAction">
${this._dialogParams.supervisor.localize("common.cancel")}
@@ -133,12 +153,27 @@ class DialogSupervisorUpdate extends LitElement {
`;
}
private _toggleSnapshot() {
this._createSnapshot = !this._createSnapshot;
private async _toggleSnapshot(): Promise<void> {
this._frontendPrefrences!.snapshot_before_update[
this._dialogParams!.slug
] = !snapshot_before_update(
this._dialogParams!.slug,
this._frontendPrefrences!
);
await saveSupervisorFrontendPreferences(
this.hass,
this._frontendPrefrences!
);
}
private async _update() {
if (this._createSnapshot) {
if (
snapshot_before_update(
this._dialogParams!.slug,
this._frontendPrefrences!
)
) {
this._action = "snapshot";
try {
await createHassioPartialSnapshot(
@@ -158,8 +193,8 @@ class DialogSupervisorUpdate extends LitElement {
} catch (err) {
if (this.hass.connection.connected && !ignoreSupervisorError(err)) {
this._error = extractApiErrorMessage(err);
this._action = null;
}
this._action = null;
return;
}

View File

@@ -5,6 +5,7 @@ export interface SupervisorDialogSupervisorUpdateParams {
supervisor: Supervisor;
name: string;
version: string;
slug: string;
snapshotParams: any;
updateHandler: () => Promise<void>;
}

View File

@@ -164,6 +164,7 @@ class HassioCoreInfo extends LitElement {
showDialogSupervisorUpdate(this, {
supervisor: this.supervisor,
name: "Home Assistant Core",
slug: "core",
version: this.supervisor.core.version_latest,
snapshotParams: {
name: `core_${this.supervisor.core.version}`,

View File

@@ -113,7 +113,7 @@ class HassioHostInfo extends LitElement {
`
: ""}
</ha-settings-row>
${!this.supervisor.host.features.includes("haos")
${!this.supervisor.host.features.includes("hassos")
? html`<ha-settings-row>
<span slot="heading">
${this.supervisor.localize("system.host.docker_version")}
@@ -190,7 +190,7 @@ class HassioHostInfo extends LitElement {
<mwc-list-item>
${this.supervisor.localize("system.host.hardware")}
</mwc-list-item>
${this.supervisor.host.features.includes("haos")
${this.supervisor.host.features.includes("hassos")
? html`<mwc-list-item>
${this.supervisor.localize("system.host.import_from_usb")}
</mwc-list-item>`

View File

@@ -44,21 +44,20 @@
"@fullcalendar/list": "5.1.0",
"@lit-labs/virtualizer": "^0.6.0",
"@material/chips": "=12.0.0-canary.1a8d06483.0",
"@material/mwc-button": "0.22.0-canary.cc04657a.0",
"@material/mwc-checkbox": "0.22.0-canary.cc04657a.0",
"@material/mwc-circular-progress": "0.22.0-canary.cc04657a.0",
"@material/mwc-dialog": "0.22.0-canary.cc04657a.0",
"@material/mwc-fab": "0.22.0-canary.cc04657a.0",
"@material/mwc-formfield": "0.22.0-canary.cc04657a.0",
"@material/mwc-icon-button": "0.22.0-canary.cc04657a.0",
"@material/mwc-linear-progress": "0.22.0-canary.cc04657a.0",
"@material/mwc-list": "0.22.0-canary.cc04657a.0",
"@material/mwc-menu": "0.22.0-canary.cc04657a.0",
"@material/mwc-radio": "0.22.0-canary.cc04657a.0",
"@material/mwc-ripple": "0.22.0-canary.cc04657a.0",
"@material/mwc-switch": "0.22.0-canary.cc04657a.0",
"@material/mwc-tab": "0.22.0-canary.cc04657a.0",
"@material/mwc-tab-bar": "0.22.0-canary.cc04657a.0",
"@material/mwc-button": "canary",
"@material/mwc-checkbox": "canary",
"@material/mwc-circular-progress": "canary",
"@material/mwc-dialog": "canary",
"@material/mwc-fab": "canary",
"@material/mwc-formfield": "canary",
"@material/mwc-icon-button": "canary",
"@material/mwc-list": "canary",
"@material/mwc-menu": "canary",
"@material/mwc-radio": "canary",
"@material/mwc-ripple": "canary",
"@material/mwc-switch": "canary",
"@material/mwc-tab": "canary",
"@material/mwc-tab-bar": "canary",
"@material/top-app-bar": "=12.0.0-canary.1a8d06483.0",
"@mdi/js": "5.9.55",
"@mdi/svg": "5.9.55",
@@ -97,11 +96,11 @@
"@vibrant/quantizer-mmcq": "^3.2.1-alpha.1",
"@vue/web-component-wrapper": "^1.2.0",
"@webcomponents/webcomponentsjs": "^2.2.7",
"chart.js": "^3.3.2",
"chart.js": "^2.9.4",
"chartjs-chart-timeline": "^0.4.0",
"comlink": "^4.3.1",
"core-js": "^3.6.5",
"cropperjs": "^1.5.11",
"date-fns": "^2.22.1",
"deep-clone-simple": "^1.1.1",
"deep-freeze": "^0.0.1",
"fecha": "^4.2.0",

View File

@@ -9,6 +9,12 @@ if [ -z "${DEVCONTAINER}" ]; then
exit 1
fi
if [ ! -z "${CODESPACES}" ]; then
WORKSPACE="/root/workspace/frontend"
else
WORKSPACE="/workspaces/frontend"
fi
if [ -z $(which hass) ]; then
echo "Installing Home Asstant core from dev."
python3 -m pip install --upgrade \
@@ -16,9 +22,9 @@ if [ -z $(which hass) ]; then
git+git://github.com/home-assistant/home-assistant.git@dev
fi
if [ ! -d "/workspaces/frontend/config" ]; then
if [ ! -d "${WORKSPACE}/config" ]; then
echo "Creating default configuration."
mkdir -p "/workspaces/frontend/config";
mkdir -p "${WORKSPACE}/config";
hass --script ensure_config -c config
echo "demo:
@@ -26,24 +32,24 @@ logger:
default: info
logs:
homeassistant.components.frontend: debug
" >> /workspaces/frontend/config/configuration.yaml
" >> "${WORKSPACE}/config/configuration.yaml"
if [ ! -z "${HASSIO}" ]; then
echo "
# frontend:
# development_repo: /workspaces/frontend
# development_repo: ${WORKSPACE}
hassio:
development_repo: /workspaces/frontend" >> /workspaces/frontend/config/configuration.yaml
development_repo: ${WORKSPACE}" >> "${WORKSPACE}/config/configuration.yaml"
else
echo "
frontend:
development_repo: /workspaces/frontend
development_repo: ${WORKSPACE}
# hassio:
# development_repo: /workspaces/frontend" >> /workspaces/frontend/config/configuration.yaml
# development_repo: ${WORKSPACE}" >> "${WORKSPACE}/config/configuration.yaml"
fi
fi
hass -c /workspaces/frontend/config
hass -c "${WORKSPACE}/config"

View File

@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
setup(
name="home-assistant-frontend",
version="20210706.0",
version="20210603.0",
description="The Home Assistant frontend",
url="https://github.com/home-assistant/home-assistant-polymer",
author="The Home Assistant Authors",

View File

@@ -7,7 +7,6 @@ import {
PropertyValues,
TemplateResult,
} from "lit";
import "./ha-password-manager-polyfill";
import { property, state } from "lit/decorators";
import "../components/ha-form/ha-form";
import "../components/ha-markdown";
@@ -21,7 +20,7 @@ import { litLocalizeLiteMixin } from "../mixins/lit-localize-lite-mixin";
type State = "loading" | "error" | "step";
class HaAuthFlow extends litLocalizeLiteMixin(LitElement) {
@property({ attribute: false }) public authProvider?: AuthProvider;
@property() public authProvider?: AuthProvider;
@property() public clientId?: string;
@@ -38,15 +37,7 @@ class HaAuthFlow extends litLocalizeLiteMixin(LitElement) {
@state() private _errorMessage?: string;
protected render() {
return html`
<form>${this._renderForm()}</form>
<ha-password-manager-polyfill
.step=${this._step}
.stepData=${this._stepData}
@form-submitted=${this._handleSubmit}
@value-changed=${this._stepDataChanged}
></ha-password-manager-polyfill>
`;
return html` <form>${this._renderForm()}</form> `;
}
protected firstUpdated(changedProps: PropertyValues) {
@@ -240,17 +231,11 @@ class HaAuthFlow extends litLocalizeLiteMixin(LitElement) {
await this.updateComplete;
// 100ms to give all the form elements time to initialize.
setTimeout(() => {
const form = this.renderRoot.querySelector("ha-form");
const form = this.shadowRoot!.querySelector("ha-form");
if (form) {
(form as any).focus();
}
}, 100);
setTimeout(() => {
this.renderRoot.querySelector(
"ha-password-manager-polyfill"
)!.boundingRect = this.getBoundingClientRect();
}, 500);
}
private _stepDataChanged(ev: CustomEvent) {
@@ -344,9 +329,3 @@ class HaAuthFlow extends litLocalizeLiteMixin(LitElement) {
}
}
customElements.define("ha-auth-flow", HaAuthFlow);
declare global {
interface HTMLElementTagNameMap {
"ha-auth-flow": HaAuthFlow;
}
}

View File

@@ -1,110 +0,0 @@
import { html, LitElement, TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
import { fireEvent } from "../common/dom/fire_event";
import { HaFormSchema } from "../components/ha-form/ha-form";
import { DataEntryFlowStep } from "../data/data_entry_flow";
declare global {
interface HTMLElementTagNameMap {
"ha-password-manager-polyfill": HaPasswordManagerPolyfill;
}
interface HASSDomEvents {
"form-submitted": undefined;
}
}
const ENABLED_HANDLERS = [
"homeassistant",
"legacy_api_password",
"command_line",
];
@customElement("ha-password-manager-polyfill")
export class HaPasswordManagerPolyfill extends LitElement {
@property({ attribute: false }) public step?: DataEntryFlowStep;
@property({ attribute: false }) public stepData: any;
@property({ attribute: false }) public boundingRect?: DOMRect;
protected createRenderRoot() {
// Add under document body so the element isn't placed inside any shadow roots
return document.body;
}
private get styles() {
return `
.password-manager-polyfill {
position: absolute;
top: ${this.boundingRect?.y || 148}px;
left: calc(50% - ${(this.boundingRect?.width || 360) / 2}px);
width: ${this.boundingRect?.width || 360}px;
opacity: 0;
z-index: -1;
}
.password-manager-polyfill input {
width: 100%;
height: 62px;
padding: 0;
border: 0;
}
.password-manager-polyfill input[type="submit"] {
width: 0;
height: 0;
}
`;
}
protected render(): TemplateResult {
if (
this.step &&
this.step.type === "form" &&
this.step.step_id === "init" &&
ENABLED_HANDLERS.includes(this.step.handler[0])
) {
return html`
<form
class="password-manager-polyfill"
aria-hidden="true"
@submit=${this._handleSubmit}
>
${this.step.data_schema.map((input) => this.render_input(input))}
<input type="submit" />
<style>
${this.styles}
</style>
</form>
`;
}
return html``;
}
private render_input(schema: HaFormSchema): TemplateResult | string {
const inputType = schema.name.includes("password") ? "password" : "text";
if (schema.type !== "string") {
return "";
}
return html`
<input
tabindex="-1"
.id=${schema.name}
.type=${inputType}
.value=${this.stepData[schema.name] || ""}
@input=${this._valueChanged}
/>
`;
}
private _handleSubmit(ev: Event) {
ev.preventDefault();
fireEvent(this, "form-submitted");
}
private _valueChanged(ev: Event) {
const target = ev.target! as HTMLInputElement;
this.stepData = { ...this.stepData, [target.id]: target.value };
fireEvent(this, "value-changed", {
value: this.stepData,
});
}
}

View File

@@ -1,63 +0,0 @@
export const COLORS = [
"#377eb8",
"#984ea3",
"#00d2d5",
"#ff7f00",
"#af8d00",
"#7f80cd",
"#b3e900",
"#c42e60",
"#a65628",
"#f781bf",
"#8dd3c7",
"#bebada",
"#fb8072",
"#80b1d3",
"#fdb462",
"#fccde5",
"#bc80bd",
"#ffed6f",
"#c4eaff",
"#cf8c00",
"#1b9e77",
"#d95f02",
"#e7298a",
"#e6ab02",
"#a6761d",
"#0097ff",
"#00d067",
"#f43600",
"#4ba93b",
"#5779bb",
"#927acc",
"#97ee3f",
"#bf3947",
"#9f5b00",
"#f48758",
"#8caed6",
"#f2b94f",
"#eff26e",
"#e43872",
"#d9b100",
"#9d7a00",
"#698cff",
"#d9d9d9",
"#00d27e",
"#d06800",
"#009f82",
"#c49200",
"#cbe8ff",
"#fecddf",
"#c27eb6",
"#8cd2ce",
"#c4b8d9",
"#f883b0",
"#a49100",
"#f48800",
"#27d0df",
"#a04a9b",
];
export function getColorByIndex(index: number) {
return COLORS[index % COLORS.length];
}

View File

@@ -1,4 +1,4 @@
export const luminosity = (rgb: [number, number, number]): number => {
const luminosity = (rgb: [number, number, number]): number => {
// http://www.w3.org/TR/WCAG20/#relativeluminancedef
const lum: [number, number, number] = [0, 0, 0];
for (let i = 0; i < rgb.length; i++) {

View File

@@ -42,7 +42,6 @@ export const FIXED_DOMAIN_ICONS = {
remote: "hass:remote",
scene: "hass:palette",
script: "hass:script-text",
select: "hass:format-list-bulleted",
sensor: "hass:eye",
simple_alarm: "hass:bell",
sun: "hass:white-balance-sunny",
@@ -84,7 +83,6 @@ export const DOMAINS_WITH_CARD = [
"number",
"scene",
"script",
"select",
"timer",
"vacuum",
"water_heater",
@@ -123,7 +121,6 @@ export const DOMAINS_HIDE_MORE_INFO = [
"input_text",
"number",
"scene",
"select",
];
/** Domains that should have the history hidden in the more info dialog. */

View File

@@ -17,19 +17,6 @@ export const formatDate = toLocaleDateStringSupportsOptions
formatDateMem(locale).format(dateObj)
: (dateObj: Date) => format(dateObj, "longDate");
const formatDateShortMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
day: "numeric",
month: "short",
})
);
export const formatDateShort = toLocaleDateStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatDateShortMem(locale).format(dateObj)
: (dateObj: Date) => format(dateObj, "shortDate");
const formatDateWeekdayMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {

View File

@@ -29,61 +29,37 @@ export const computeStateDisplay = (
const domain = computeStateDomain(stateObj);
if (domain === "input_datetime") {
if (state) {
// If trying to display an explicit state, need to parse the explict state to `Date` then format.
// Attributes aren't available, we have to use `state`.
try {
const components = state.split(" ");
if (components.length === 2) {
// Date and time.
return formatDateTime(new Date(components.join("T")), locale);
}
if (components.length === 1) {
if (state.includes("-")) {
// Date only.
return formatDate(new Date(`${state}T00:00`), locale);
}
if (state.includes(":")) {
// Time only.
const now = new Date();
return formatTime(
new Date(`${now.toISOString().split("T")[0]}T${state}`),
locale
);
}
}
return state;
} catch {
// Formatting methods may throw error if date parsing doesn't go well,
// just return the state string in that case.
return state;
}
} else {
// If not trying to display an explicit state, create `Date` object from `stateObj`'s attributes then format.
let date: Date;
if (!stateObj.attributes.has_time) {
date = new Date(
stateObj.attributes.year,
stateObj.attributes.month - 1,
stateObj.attributes.day
);
return formatDate(date, locale);
}
if (!stateObj.attributes.has_date) {
date = new Date();
date.setHours(stateObj.attributes.hour, stateObj.attributes.minute);
return formatTime(date, locale);
}
let date: Date;
if (!stateObj.attributes.has_time) {
date = new Date(
stateObj.attributes.year,
stateObj.attributes.month - 1,
stateObj.attributes.day,
stateObj.attributes.day
);
return formatDate(date, locale);
}
if (!stateObj.attributes.has_date) {
const now = new Date();
date = new Date(
// Due to bugs.chromium.org/p/chromium/issues/detail?id=797548
// don't use artificial 1970 year.
now.getFullYear(),
now.getMonth(),
now.getDay(),
stateObj.attributes.hour,
stateObj.attributes.minute
);
return formatDateTime(date, locale);
return formatTime(date, locale);
}
date = new Date(
stateObj.attributes.year,
stateObj.attributes.month - 1,
stateObj.attributes.day,
stateObj.attributes.hour,
stateObj.attributes.minute
);
return formatDateTime(date, locale);
}
if (domain === "humidifier") {

View File

@@ -1,2 +0,0 @@
export const clamp = (value: number, min: number, max: number) =>
Math.min(Math.max(value, min), max);

View File

@@ -29,28 +29,31 @@ export const iconColorCSS = css`
}
ha-icon[data-domain="climate"][data-state="cooling"] {
color: var(--cool-color, var(--state-climate-cool-color));
color: var(--cool-color, #2b9af9);
}
ha-icon[data-domain="climate"][data-state="heating"] {
color: var(--heat-color, var(--state-climate-heat-color));
color: var(--heat-color, #ff8100);
}
ha-icon[data-domain="climate"][data-state="drying"] {
color: var(--dry-color, var(--state-climate-dry-color));
color: var(--dry-color, #efbd07);
}
ha-icon[data-domain="alarm_control_panel"] {
color: var(--alarm-color-armed, var(--label-badge-red));
}
ha-icon[data-domain="alarm_control_panel"][data-state="disarmed"] {
color: var(--alarm-color-disarmed, var(--label-badge-green));
}
ha-icon[data-domain="alarm_control_panel"][data-state="pending"],
ha-icon[data-domain="alarm_control_panel"][data-state="arming"] {
color: var(--alarm-color-pending, var(--label-badge-yellow));
animation: pulse 1s infinite;
}
ha-icon[data-domain="alarm_control_panel"][data-state="triggered"] {
color: var(--alarm-color-triggered, var(--label-badge-red));
animation: pulse 1s infinite;
@@ -70,11 +73,11 @@ export const iconColorCSS = css`
ha-icon[data-domain="plant"][data-state="problem"],
ha-icon[data-domain="zwave"][data-state="dead"] {
color: var(--state-icon-error-color);
color: var(--error-state-color, #db4437);
}
/* Color the icon if unavailable */
ha-icon[data-state="unavailable"] {
color: var(--state-unavailable-color);
color: var(--state-icon-unavailable-color);
}
`;

View File

@@ -5,20 +5,32 @@
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `false for leading`. To disable execution on the trailing edge, ditto.
export const throttle = <T extends any[]>(
func: (...args: T) => void,
export const throttle = <T extends (...args) => unknown>(
func: T,
wait: number,
leading = true,
trailing = true
) => {
): T => {
let timeout: number | undefined;
let previous = 0;
return (...args: T): void => {
const later = () => {
previous = leading === false ? 0 : Date.now();
timeout = undefined;
func(...args);
};
let context: any;
let args: any;
const later = () => {
previous = leading === false ? 0 : Date.now();
timeout = undefined;
func.apply(context, args);
if (!timeout) {
context = null;
args = null;
}
};
// @ts-ignore
return function (...argmnts) {
// @ts-ignore
// @typescript-eslint/no-this-alias
context = this;
args = argmnts;
const now = Date.now();
if (!previous && leading === false) {
previous = now;
@@ -30,7 +42,7 @@ export const throttle = <T extends any[]>(
timeout = undefined;
}
previous = now;
func(...args);
func.apply(context, args);
} else if (!timeout && trailing !== false) {
timeout = window.setTimeout(later, remaining);
}

View File

@@ -1,197 +0,0 @@
import { _adapters } from "chart.js";
import {
startOfSecond,
startOfMinute,
startOfHour,
startOfDay,
startOfWeek,
startOfMonth,
startOfQuarter,
startOfYear,
addMilliseconds,
addSeconds,
addMinutes,
addHours,
addDays,
addWeeks,
addMonths,
addQuarters,
addYears,
differenceInMilliseconds,
differenceInSeconds,
differenceInMinutes,
differenceInHours,
differenceInDays,
differenceInWeeks,
differenceInMonths,
differenceInQuarters,
differenceInYears,
endOfSecond,
endOfMinute,
endOfHour,
endOfDay,
endOfWeek,
endOfMonth,
endOfQuarter,
endOfYear,
} from "date-fns";
import { formatDate, formatDateShort } from "../../common/datetime/format_date";
import {
formatDateTime,
formatDateTimeWithSeconds,
} from "../../common/datetime/format_date_time";
import {
formatTime,
formatTimeWithSeconds,
} from "../../common/datetime/format_time";
const FORMATS = {
datetime: "datetime",
datetimeseconds: "datetimeseconds",
millisecond: "millisecond",
second: "second",
minute: "minute",
hour: "hour",
day: "day",
week: "week",
month: "month",
quarter: "quarter",
year: "year",
};
_adapters._date.override({
formats: () => FORMATS,
parse: (value: Date | number) => {
if (!(value instanceof Date)) {
return value;
}
return value.getTime();
},
format: function (time, fmt: keyof typeof FORMATS) {
switch (fmt) {
case "datetime":
return formatDateTime(new Date(time), this.options.locale);
case "datetimeseconds":
return formatDateTimeWithSeconds(new Date(time), this.options.locale);
case "millisecond":
return formatTimeWithSeconds(new Date(time), this.options.locale);
case "second":
return formatTimeWithSeconds(new Date(time), this.options.locale);
case "minute":
return formatTime(new Date(time), this.options.locale);
case "hour":
return formatTime(new Date(time), this.options.locale);
case "day":
return formatDateShort(new Date(time), this.options.locale);
case "week":
return formatDate(new Date(time), this.options.locale);
case "month":
return formatDate(new Date(time), this.options.locale);
case "quarter":
return formatDate(new Date(time), this.options.locale);
case "year":
return formatDate(new Date(time), this.options.locale);
default:
return "";
}
},
// @ts-ignore
add: (time, amount, unit) => {
switch (unit) {
case "millisecond":
return addMilliseconds(time, amount);
case "second":
return addSeconds(time, amount);
case "minute":
return addMinutes(time, amount);
case "hour":
return addHours(time, amount);
case "day":
return addDays(time, amount);
case "week":
return addWeeks(time, amount);
case "month":
return addMonths(time, amount);
case "quarter":
return addQuarters(time, amount);
case "year":
return addYears(time, amount);
default:
return time;
}
},
diff: (max, min, unit) => {
switch (unit) {
case "millisecond":
return differenceInMilliseconds(max, min);
case "second":
return differenceInSeconds(max, min);
case "minute":
return differenceInMinutes(max, min);
case "hour":
return differenceInHours(max, min);
case "day":
return differenceInDays(max, min);
case "week":
return differenceInWeeks(max, min);
case "month":
return differenceInMonths(max, min);
case "quarter":
return differenceInQuarters(max, min);
case "year":
return differenceInYears(max, min);
default:
return 0;
}
},
// @ts-ignore
startOf: (time, unit, weekday) => {
switch (unit) {
case "second":
return startOfSecond(time);
case "minute":
return startOfMinute(time);
case "hour":
return startOfHour(time);
case "day":
return startOfDay(time);
case "week":
return startOfWeek(time);
case "isoWeek":
return startOfWeek(time, {
weekStartsOn: +weekday! as 0 | 1 | 2 | 3 | 4 | 5 | 6,
});
case "month":
return startOfMonth(time);
case "quarter":
return startOfQuarter(time);
case "year":
return startOfYear(time);
default:
return time;
}
},
// @ts-ignore
endOf: (time, unit) => {
switch (unit) {
case "second":
return endOfSecond(time);
case "minute":
return endOfMinute(time);
case "hour":
return endOfHour(time);
case "day":
return endOfDay(time);
case "week":
return endOfWeek(time);
case "month":
return endOfMonth(time);
case "quarter":
return endOfQuarter(time);
case "year":
return endOfYear(time);
default:
return time;
}
},
});

View File

@@ -1,318 +0,0 @@
import type {
Chart,
ChartType,
ChartData,
ChartOptions,
TooltipModel,
} from "chart.js";
import { css, CSSResultGroup, html, LitElement, PropertyValues } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { styleMap } from "lit/directives/style-map";
import { clamp } from "../../common/number/clamp";
interface Tooltip extends TooltipModel<any> {
top: string;
left: string;
}
@customElement("ha-chart-base")
export default class HaChartBase extends LitElement {
public chart?: Chart;
@property({ attribute: "chart-type", reflect: true })
public chartType: ChartType = "line";
@property({ attribute: false })
public data: ChartData = { datasets: [] };
@property({ attribute: false })
public options?: ChartOptions;
@state() private _tooltip?: Tooltip;
@state() private _height?: string;
@state() private _hiddenDatasets: Set<number> = new Set();
protected firstUpdated() {
this._setupChart();
this.data.datasets.forEach((dataset, index) => {
if (dataset.hidden) {
this._hiddenDatasets.add(index);
}
});
}
public willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
if (!this.hasUpdated || !this.chart) {
return;
}
if (changedProps.has("type")) {
this.chart.config.type = this.chartType;
}
if (changedProps.has("data")) {
this.chart.data = this.data;
}
if (changedProps.has("options")) {
this.chart.options = this._createOptions();
}
this.chart.update("none");
}
protected render() {
return html`
${this.options?.plugins?.legend?.display === true
? html` <div class="chartLegend">
<ul>
${this.data.datasets.map(
(dataset, index) => html`<li
.datasetIndex=${index}
@click=${this._legendClick}
class=${classMap({
hidden: this._hiddenDatasets.has(index),
})}
>
<div
class="bullet"
style=${styleMap({
backgroundColor: dataset.backgroundColor as string,
borderColor: dataset.borderColor as string,
})}
></div>
${dataset.label}
</li>`
)}
</ul>
</div>`
: ""}
<div
class="chartContainer"
style=${styleMap({
height:
this.chartType === "timeline"
? `${this.data.datasets.length * 30 + 30}px`
: this._height,
overflow: this._height ? "initial" : "hidden",
})}
>
<canvas></canvas>
${this._tooltip
? html`<div
class="chartTooltip ${classMap({ [this._tooltip.yAlign]: true })}"
style=${styleMap({
top: this._tooltip.top,
left: this._tooltip.left,
})}
>
<div class="title">${this._tooltip.title}</div>
${this._tooltip.beforeBody
? html`<div class="beforeBody">
${this._tooltip.beforeBody}
</div>`
: ""}
<div>
<ul>
${this._tooltip.body.map(
(item, i) => html`<li>
<div
class="bullet"
style=${styleMap({
backgroundColor: this._tooltip!.labelColors[i]
.backgroundColor as string,
borderColor: this._tooltip!.labelColors[i]
.borderColor as string,
})}
></div>
${item.lines.join("\n")}
</li>`
)}
</ul>
</div>
</div>`
: ""}
</div>
`;
}
private async _setupChart() {
const ctx: CanvasRenderingContext2D = this.renderRoot
.querySelector("canvas")!
.getContext("2d")!;
this.chart = new (await import("../../resources/chartjs")).Chart(ctx, {
type: this.chartType,
data: this.data,
options: this._createOptions(),
plugins: [
{
id: "afterRenderHook",
afterRender: (chart) => {
this._height = `${chart.height}px`;
},
},
],
});
}
private _createOptions() {
return {
...this.options,
plugins: {
...this.options?.plugins,
tooltip: {
...this.options?.plugins?.tooltip,
enabled: false,
external: (context) => this._handleTooltip(context),
},
legend: {
...this.options?.plugins?.legend,
display: false,
},
},
};
}
private _legendClick(ev) {
if (!this.chart) {
return;
}
const index = ev.currentTarget.datasetIndex;
if (this.chart.isDatasetVisible(index)) {
this.chart.setDatasetVisibility(index, false);
this._hiddenDatasets.add(index);
} else {
this.chart.setDatasetVisibility(index, true);
this._hiddenDatasets.delete(index);
}
this.chart.update("none");
this.requestUpdate("_hiddenDatasets");
}
private _handleTooltip(context: {
chart: Chart;
tooltip: TooltipModel<any>;
}) {
if (context.tooltip.opacity === 0) {
this._tooltip = undefined;
return;
}
this._tooltip = {
...context.tooltip,
top: this.chart!.canvas.offsetTop + context.tooltip.caretY + 12 + "px",
left:
this.chart!.canvas.offsetLeft +
clamp(context.tooltip.caretX, 100, this.clientWidth - 100) -
100 +
"px",
};
}
public updateChart = (): void => {
if (this.chart) {
this.chart.update();
}
};
static get styles(): CSSResultGroup {
return css`
:host {
display: block;
}
.chartContainer {
overflow: hidden;
height: 0;
transition: height 300ms cubic-bezier(0.4, 0, 0.2, 1);
}
:host(:not([chart-type="timeline"])) canvas {
max-height: 400px;
}
.chartLegend {
text-align: center;
}
.chartLegend li {
cursor: pointer;
display: inline-flex;
padding: 0 8px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
box-sizing: border-box;
align-items: center;
color: var(--secondary-text-color);
}
.chartLegend .hidden {
text-decoration: line-through;
}
.chartLegend .bullet,
.chartTooltip .bullet {
border-width: 1px;
border-style: solid;
border-radius: 50%;
display: inline-block;
height: 16px;
margin-right: 4px;
width: 16px;
flex-shrink: 0;
box-sizing: border-box;
}
.chartTooltip .bullet {
align-self: baseline;
}
:host([rtl]) .chartTooltip .bullet {
margin-right: inherit;
margin-left: 4px;
}
.chartTooltip {
padding: 8px;
font-size: 90%;
position: absolute;
background: rgba(80, 80, 80, 0.9);
color: white;
border-radius: 4px;
pointer-events: none;
z-index: 1000;
width: 200px;
box-sizing: border-box;
}
:host([rtl]) .chartTooltip {
direction: rtl;
}
.chartLegend ul,
.chartTooltip ul {
display: inline-block;
padding: 0 0px;
margin: 8px 0 0 0;
width: 100%;
}
.chartTooltip ul {
margin: 0 4px;
}
.chartTooltip li {
display: flex;
white-space: pre-line;
align-items: center;
line-height: 16px;
}
.chartTooltip .title {
text-align: center;
font-weight: 500;
}
.chartTooltip .beforeBody {
text-align: center;
font-weight: 300;
word-break: break-all;
}
`;
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-chart-base": HaChartBase;
}
}

View File

@@ -1,392 +0,0 @@
import type { ChartData, ChartDataset, ChartOptions } from "chart.js";
import { html, LitElement, PropertyValues } from "lit";
import { property, state } from "lit/decorators";
import { getColorByIndex } from "../../common/color/colors";
import { LineChartEntity, LineChartState } from "../../data/history";
import { HomeAssistant } from "../../types";
import "./ha-chart-base";
class StateHistoryChartLine extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public data: LineChartEntity[] = [];
@property({ type: Boolean }) public names = false;
@property() public unit?: string;
@property() public identifier?: string;
@property({ type: Boolean }) public isSingleDevice = false;
@property({ attribute: false }) public endTime?: Date;
@state() private _chartData?: ChartData<"line">;
@state() private _chartOptions?: ChartOptions<"line">;
protected render() {
return html`
<ha-chart-base
.data=${this._chartData}
.options=${this._chartOptions}
chart-type="line"
></ha-chart-base>
`;
}
public willUpdate(changedProps: PropertyValues) {
if (!this.hasUpdated) {
this._chartOptions = {
parsing: false,
animation: false,
scales: {
x: {
type: "time",
adapters: {
date: {
locale: this.hass.locale,
},
},
ticks: {
maxRotation: 0,
sampleSize: 5,
autoSkipPadding: 20,
major: {
enabled: true,
},
font: (context) =>
context.tick && context.tick.major
? ({ weight: "bold" } as any)
: {},
},
time: {
tooltipFormat: "datetimeseconds",
},
},
y: {
ticks: {
maxTicksLimit: 7,
},
title: {
display: true,
text: this.unit,
},
},
},
plugins: {
tooltip: {
mode: "nearest",
callbacks: {
label: (context) =>
`${context.dataset.label}: ${context.parsed.y} ${this.unit}`,
},
},
filler: {
propagate: true,
},
legend: {
display: !this.isSingleDevice,
labels: {
usePointStyle: true,
},
},
},
hover: {
mode: "nearest",
},
elements: {
line: {
tension: 0.1,
borderWidth: 1.5,
},
point: {
hitRadius: 5,
},
},
};
}
if (changedProps.has("data")) {
this._generateData();
}
}
private _generateData() {
let colorIndex = 0;
const computedStyles = getComputedStyle(this);
const deviceStates = this.data;
const datasets: ChartDataset<"line">[] = [];
let endTime: Date;
if (deviceStates.length === 0) {
return;
}
function safeParseFloat(value) {
const parsed = parseFloat(value);
return isFinite(parsed) ? parsed : null;
}
endTime =
this.endTime ||
// Get the highest date from the last date of each device
new Date(
Math.max.apply(
null,
deviceStates.map((devSts) =>
new Date(
devSts.states[devSts.states.length - 1].last_changed
).getMilliseconds()
)
)
);
if (endTime > new Date()) {
endTime = new Date();
}
const names = this.names || {};
deviceStates.forEach((states) => {
const domain = states.domain;
const name = names[states.entity_id] || states.name;
// array containing [value1, value2, etc]
let prevValues: any[] | null = null;
const data: ChartDataset<"line">[] = [];
const pushData = (timestamp: Date, datavalues: any[] | null) => {
if (!datavalues) return;
if (timestamp > endTime) {
// Drop datapoints that are after the requested endTime. This could happen if
// endTime is "now" and client time is not in sync with server time.
return;
}
data.forEach((d, i) => {
if (datavalues[i] === null && prevValues && prevValues[i] !== null) {
// null data values show up as gaps in the chart.
// If the current value for the dataset is null and the previous
// value of the data set is not null, then add an 'end' point
// to the chart for the previous value. Otherwise the gap will
// be too big. It will go from the start of the previous data
// value until the start of the next data value.
d.data.push({ x: timestamp.getTime(), y: prevValues[i] });
}
d.data.push({ x: timestamp.getTime(), y: datavalues[i] });
});
prevValues = datavalues;
};
const addDataSet = (
nameY: string,
step = false,
fill = false,
color?: string
) => {
if (!color) {
color = getColorByIndex(colorIndex);
colorIndex++;
}
data.push({
label: nameY,
fill: fill ? "origin" : false,
borderColor: color,
backgroundColor: color + "7F",
stepped: step ? "before" : false,
pointRadius: 0,
data: [],
});
};
if (
domain === "thermostat" ||
domain === "climate" ||
domain === "water_heater"
) {
const hasHvacAction = states.states.some(
(entityState) => entityState.attributes?.hvac_action
);
const isHeating =
domain === "climate" && hasHvacAction
? (entityState: LineChartState) =>
entityState.attributes?.hvac_action === "heating"
: (entityState: LineChartState) => entityState.state === "heat";
const isCooling =
domain === "climate" && hasHvacAction
? (entityState: LineChartState) =>
entityState.attributes?.hvac_action === "cooling"
: (entityState: LineChartState) => entityState.state === "cool";
const hasHeat = states.states.some(isHeating);
const hasCool = states.states.some(isCooling);
// We differentiate between thermostats that have a target temperature
// range versus ones that have just a target temperature
// Using step chart by step-before so manually interpolation not needed.
const hasTargetRange = states.states.some(
(entityState) =>
entityState.attributes &&
entityState.attributes.target_temp_high !==
entityState.attributes.target_temp_low
);
addDataSet(
`${this.hass.localize("ui.card.climate.current_temperature", {
name: name,
})}`,
true
);
if (hasHeat) {
addDataSet(
`${this.hass.localize("ui.card.climate.heating", { name: name })}`,
true,
true,
computedStyles.getPropertyValue("--state-climate-heat-color")
);
// The "heating" series uses steppedArea to shade the area below the current
// temperature when the thermostat is calling for heat.
}
if (hasCool) {
addDataSet(
`${this.hass.localize("ui.card.climate.cooling", { name: name })}`,
true,
true,
computedStyles.getPropertyValue("--state-climate-cool-color")
);
// The "cooling" series uses steppedArea to shade the area below the current
// temperature when the thermostat is calling for heat.
}
if (hasTargetRange) {
addDataSet(
`${this.hass.localize("ui.card.climate.target_temperature_mode", {
name: name,
mode: this.hass.localize("ui.card.climate.high"),
})}`,
true
);
addDataSet(
`${this.hass.localize("ui.card.climate.target_temperature_mode", {
name: name,
mode: this.hass.localize("ui.card.climate.low"),
})}`,
true
);
} else {
addDataSet(
`${this.hass.localize("ui.card.climate.target_temperature_entity", {
name: name,
})}`,
true
);
}
states.states.forEach((entityState) => {
if (!entityState.attributes) return;
const curTemp = safeParseFloat(
entityState.attributes.current_temperature
);
const series = [curTemp];
if (hasHeat) {
series.push(isHeating(entityState) ? curTemp : null);
}
if (hasCool) {
series.push(isCooling(entityState) ? curTemp : null);
}
if (hasTargetRange) {
const targetHigh = safeParseFloat(
entityState.attributes.target_temp_high
);
const targetLow = safeParseFloat(
entityState.attributes.target_temp_low
);
series.push(targetHigh, targetLow);
pushData(new Date(entityState.last_changed), series);
} else {
const target = safeParseFloat(entityState.attributes.temperature);
series.push(target);
pushData(new Date(entityState.last_changed), series);
}
});
} else if (domain === "humidifier") {
addDataSet(
`${this.hass.localize("ui.card.humidifier.target_humidity_entity", {
name: name,
})}`,
true
);
addDataSet(
`${this.hass.localize("ui.card.humidifier.on_entity", {
name: name,
})}`,
true,
true
);
states.states.forEach((entityState) => {
if (!entityState.attributes) return;
const target = safeParseFloat(entityState.attributes.humidity);
const series = [target];
series.push(entityState.state === "on" ? target : null);
pushData(new Date(entityState.last_changed), series);
});
} else {
// Only disable interpolation for sensors
const isStep = domain === "sensor";
addDataSet(name, isStep);
let lastValue: number;
let lastDate: Date;
let lastNullDate: Date | null = null;
// Process chart data.
// When state is `unknown`, calculate the value and break the line.
states.states.forEach((entityState) => {
const value = safeParseFloat(entityState.state);
const date = new Date(entityState.last_changed);
if (value !== null && lastNullDate) {
const dateTime = date.getTime();
const lastNullDateTime = lastNullDate.getTime();
const lastDateTime = lastDate?.getTime();
const tmpValue =
(value - lastValue) *
((lastNullDateTime - lastDateTime) /
(dateTime - lastDateTime)) +
lastValue;
pushData(lastNullDate, [tmpValue]);
pushData(new Date(lastNullDateTime + 1), [null]);
pushData(date, [value]);
lastDate = date;
lastValue = value;
lastNullDate = null;
} else if (value !== null && lastNullDate === null) {
pushData(date, [value]);
lastDate = date;
lastValue = value;
} else if (
value === null &&
lastNullDate === null &&
lastValue !== undefined
) {
lastNullDate = date;
}
});
}
// Add an entry for final values
pushData(endTime, prevValues);
// Concat two arrays
Array.prototype.push.apply(datasets, data);
});
this._chartData = {
datasets,
};
}
}
customElements.define("state-history-chart-line", StateHistoryChartLine);
declare global {
interface HTMLElementTagNameMap {
"state-history-chart-line": StateHistoryChartLine;
}
}

View File

@@ -1,310 +0,0 @@
import type { ChartData, ChartDataset, ChartOptions } from "chart.js";
import { HassEntity } from "home-assistant-js-websocket";
import { html, LitElement, PropertyValues } from "lit";
import { customElement, property, state } from "lit/decorators";
import { getColorByIndex } from "../../common/color/colors";
import { formatDateTimeWithSeconds } from "../../common/datetime/format_date_time";
import { computeDomain } from "../../common/entity/compute_domain";
import { computeRTL } from "../../common/util/compute_rtl";
import { TimelineEntity } from "../../data/history";
import { HomeAssistant } from "../../types";
import "./ha-chart-base";
import type { TimeLineData } from "./timeline-chart/const";
/** Binary sensor device classes for which the static colors for on/off need to be inverted.
* List the ones were "off" = good or normal state = should be rendered "green".
*/
const BINARY_SENSOR_DEVICE_CLASS_COLOR_INVERTED = new Set([
"battery",
"door",
"garage_door",
"gas",
"lock",
"opening",
"problem",
"safety",
"smoke",
"window",
]);
const STATIC_STATE_COLORS = new Set([
"on",
"off",
"home",
"not_home",
"unavailable",
"unknown",
"idle",
]);
const stateColorMap: Map<string, string> = new Map();
let colorIndex = 0;
const invertOnOff = (entityState?: HassEntity) =>
entityState &&
computeDomain(entityState.entity_id) === "binary_sensor" &&
"device_class" in entityState.attributes &&
BINARY_SENSOR_DEVICE_CLASS_COLOR_INVERTED.has(
entityState.attributes.device_class!
);
const getColor = (
stateString: string,
entityState: HassEntity,
computedStyles: CSSStyleDeclaration
) => {
if (invertOnOff(entityState)) {
stateString = stateString === "on" ? "off" : "on";
}
if (stateColorMap.has(stateString)) {
return stateColorMap.get(stateString);
}
if (STATIC_STATE_COLORS.has(stateString)) {
const color = computedStyles.getPropertyValue(
`--state-${stateString}-color`
);
stateColorMap.set(stateString, color);
return color;
}
const color = getColorByIndex(colorIndex);
colorIndex++;
stateColorMap.set(stateString, color);
return color;
};
@customElement("state-history-chart-timeline")
export class StateHistoryChartTimeline extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public data: TimelineEntity[] = [];
@property({ type: Boolean }) public names = false;
@property() public unit?: string;
@property() public identifier?: string;
@property({ type: Boolean }) public isSingleDevice = false;
@property({ attribute: false }) public endTime?: Date;
@state() private _chartData?: ChartData<"timeline">;
@state() private _chartOptions?: ChartOptions<"timeline">;
protected render() {
return html`
<ha-chart-base
.data=${this._chartData}
.options=${this._chartOptions}
chart-type="timeline"
></ha-chart-base>
`;
}
public willUpdate(changedProps: PropertyValues) {
if (!this.hasUpdated) {
this._chartOptions = {
maintainAspectRatio: false,
parsing: false,
animation: false,
scales: {
x: {
type: "timeline",
position: "bottom",
adapters: {
date: {
locale: this.hass.locale,
},
},
ticks: {
autoSkip: true,
maxRotation: 0,
sampleSize: 5,
autoSkipPadding: 20,
major: {
enabled: true,
},
font: (context) =>
context.tick && context.tick.major
? ({ weight: "bold" } as any)
: {},
},
grid: {
offset: false,
},
time: {
tooltipFormat: "datetimeseconds",
},
},
y: {
type: "category",
barThickness: 20,
offset: true,
grid: {
display: false,
drawBorder: false,
drawTicks: false,
},
ticks: {
display: this.data.length !== 1,
},
afterSetDimensions: (y) => {
y.maxWidth = y.chart.width * 0.18;
},
position: computeRTL(this.hass) ? "right" : "left",
},
},
plugins: {
tooltip: {
mode: "nearest",
callbacks: {
title: (context) =>
context![0].chart!.data!.labels![
context[0].datasetIndex
] as string,
beforeBody: (context) => context[0].dataset.label || "",
label: (item) => {
const d = item.dataset.data[item.dataIndex] as TimeLineData;
return [
d.label || "",
formatDateTimeWithSeconds(d.start, this.hass.locale),
formatDateTimeWithSeconds(d.end, this.hass.locale),
];
},
labelColor: (item) => ({
borderColor: (item.dataset.data[item.dataIndex] as TimeLineData)
.color!,
backgroundColor: (item.dataset.data[
item.dataIndex
] as TimeLineData).color!,
}),
},
},
filler: {
propagate: true,
},
},
};
}
if (changedProps.has("data")) {
this._generateData();
}
}
private _generateData() {
const computedStyles = getComputedStyle(this);
let stateHistory = this.data;
if (!stateHistory) {
stateHistory = [];
}
const startTime = new Date(
stateHistory.reduce(
(minTime, stateInfo) =>
Math.min(minTime, new Date(stateInfo.data[0].last_changed).getTime()),
new Date().getTime()
)
);
// end time is Math.max(startTime, last_event)
let endTime =
this.endTime ||
new Date(
stateHistory.reduce(
(maxTime, stateInfo) =>
Math.max(
maxTime,
new Date(
stateInfo.data[stateInfo.data.length - 1].last_changed
).getTime()
),
startTime.getTime()
)
);
if (endTime > new Date()) {
endTime = new Date();
}
const labels: string[] = [];
const datasets: ChartDataset<"timeline">[] = [];
const names = this.names || {};
// stateHistory is a list of lists of sorted state objects
stateHistory.forEach((stateInfo) => {
let newLastChanged: Date;
let prevState: string | null = null;
let locState: string | null = null;
let prevLastChanged = startTime;
const entityDisplay: string =
names[stateInfo.entity_id] || stateInfo.name;
const dataRow: TimeLineData[] = [];
stateInfo.data.forEach((entityState) => {
let newState: string | null = entityState.state;
const timeStamp = new Date(entityState.last_changed);
if (!newState) {
newState = null;
}
if (timeStamp > endTime) {
// Drop datapoints that are after the requested endTime. This could happen if
// endTime is 'now' and client time is not in sync with server time.
return;
}
if (prevState === null) {
prevState = newState;
locState = entityState.state_localize;
prevLastChanged = new Date(entityState.last_changed);
} else if (newState !== prevState) {
newLastChanged = new Date(entityState.last_changed);
dataRow.push({
start: prevLastChanged,
end: newLastChanged,
label: locState,
color: getColor(
prevState,
this.hass.states[stateInfo.entity_id],
computedStyles
),
});
prevState = newState;
locState = entityState.state_localize;
prevLastChanged = newLastChanged;
}
});
if (prevState !== null) {
dataRow.push({
start: prevLastChanged,
end: endTime,
label: locState,
color: getColor(
prevState,
this.hass.states[stateInfo.entity_id],
computedStyles
),
});
}
datasets.push({
data: dataRow,
label: stateInfo.entity_id,
});
labels.push(entityDisplay);
});
this._chartData = {
labels: labels,
datasets: datasets,
};
}
}
declare global {
interface HTMLElementTagNameMap {
"state-history-chart-timeline": StateHistoryChartTimeline;
}
}

View File

@@ -1,18 +0,0 @@
export interface TimeLineData {
start: Date;
end: Date;
label?: string | null;
color?: string;
}
declare module "chart.js" {
interface ChartTypeRegistry {
timeline: {
chartOptions: BarControllerChartOptions;
datasetOptions: BarControllerDatasetOptions;
defaultDataPoint: TimeLineData;
parsedDataType: any;
scales: "timeline";
};
}
}

View File

@@ -1,60 +0,0 @@
import { BarElement, BarOptions, BarProps } from "chart.js";
import { hex2rgb } from "../../../common/color/convert-color";
import { luminosity } from "../../../common/color/rgb";
export interface TextBarProps extends BarProps {
text?: string | null;
options?: Partial<TextBaroptions>;
}
export interface TextBaroptions extends BarOptions {
textPad?: number;
textColor?: string;
backgroundColor: string;
}
export class TextBarElement extends BarElement {
static id = "textbar";
draw(ctx) {
super.draw(ctx);
const options = this.options as TextBaroptions;
const { x, y, base, width, text } = (this as BarElement<
TextBarProps,
TextBaroptions
>).getProps(["x", "y", "base", "width", "text"]);
if (!text) {
return;
}
ctx.beginPath();
const textRect = ctx.measureText(text);
if (
textRect.width === 0 ||
textRect.width + (options.textPad || 4) + 2 > width
) {
return;
}
const textColor =
options.textColor ||
(options.backgroundColor &&
(luminosity(hex2rgb(options.backgroundColor)) > 0.5 ? "#000" : "#fff"));
// ctx.font = "12px arial";
ctx.fillStyle = textColor;
ctx.lineWidth = 0;
ctx.strokeStyle = textColor;
ctx.textBaseline = "middle";
ctx.fillText(
text,
x - width / 2 + (options.textPad || 4),
y + (base - y) / 2
);
}
tooltipPosition(useFinalPosition: boolean) {
const { x, y, base } = this.getProps(["x", "y", "base"], useFinalPosition);
return { x, y: y + (base - y) / 2 };
}
}

View File

@@ -1,160 +0,0 @@
import { BarController, BarElement } from "chart.js";
import { TimeLineData } from "./const";
import { TextBarProps } from "./textbar-element";
function parseValue(entry, item, vScale, i) {
const startValue = vScale.parse(entry.start, i);
const endValue = vScale.parse(entry.end, i);
const min = Math.min(startValue, endValue);
const max = Math.max(startValue, endValue);
let barStart = min;
let barEnd = max;
if (Math.abs(min) > Math.abs(max)) {
barStart = max;
barEnd = min;
}
// Store `barEnd` (furthest away from origin) as parsed value,
// to make stacking straight forward
item[vScale.axis] = barEnd;
item._custom = {
barStart,
barEnd,
start: startValue,
end: endValue,
min,
max,
};
return item;
}
export class TimelineController extends BarController {
static id = "timeline";
static defaults = {
dataElementType: "textbar",
dataElementOptions: ["text", "textColor", "textPadding"],
elements: {
showText: true,
textPadding: 4,
minBarWidth: 1,
},
layout: {
padding: {
left: 0,
right: 0,
top: 0,
bottom: 0,
},
},
};
static overrides = {
maintainAspectRatio: false,
plugins: {
legend: {
display: false,
},
},
};
parseObjectData(meta, data, start, count) {
const iScale = meta.iScale;
const vScale = meta.vScale;
const labels = iScale.getLabels();
const singleScale = iScale === vScale;
const parsed: any[] = [];
let i;
let ilen;
let item;
let entry;
for (i = start, ilen = start + count; i < ilen; ++i) {
entry = data[i];
item = {};
item[iScale.axis] = singleScale || iScale.parse(labels[i], i);
parsed.push(parseValue(entry, item, vScale, i));
}
return parsed;
}
getLabelAndValue(index) {
const meta = this._cachedMeta;
const { vScale } = meta;
const data = this.getDataset().data[index] as TimeLineData;
return {
label: vScale!.getLabelForValue(this.index) || "",
value: data.label || "",
};
}
updateElements(
bars: BarElement[],
start: number,
count: number,
mode: "reset" | "resize" | "none" | "hide" | "show" | "normal" | "active"
) {
const vScale = this._cachedMeta.vScale!;
const iScale = this._cachedMeta.iScale!;
const dataset = this.getDataset();
const firstOpts = this.resolveDataElementOptions(start, mode);
const sharedOptions = this.getSharedOptions(firstOpts);
const includeOptions = this.includeOptions(mode, sharedOptions!);
const horizontal = vScale.isHorizontal();
this.updateSharedOptions(sharedOptions!, mode, firstOpts);
for (let index = start; index < start + count; index++) {
const data = dataset.data[index] as TimeLineData;
// @ts-ignore
const y = vScale.getPixelForValue(this.index);
// @ts-ignore
const xStart = iScale.getPixelForValue(data.start.getTime());
// @ts-ignore
const xEnd = iScale.getPixelForValue(data.end.getTime());
const width = xEnd - xStart;
const height = 10;
const properties: TextBarProps = {
horizontal,
x: xStart + width / 2, // Center of the bar
y: y - height, // Top of bar
width,
height: 0,
base: y + height, // Bottom of bar,
// Text
text: data.label,
};
if (includeOptions) {
properties.options =
sharedOptions || this.resolveDataElementOptions(index, mode);
properties.options = {
...properties.options,
backgroundColor: data.color,
};
}
this.updateElement(bars[index], index, properties as any, mode);
}
}
removeHoverStyle(_element, _datasetIndex, _index) {
// this._setStyle(element, index, 'active', false);
}
setHoverStyle(_element, _datasetIndex, _index) {
// this._setStyle(element, index, 'active', true);
}
}

View File

@@ -1,55 +0,0 @@
import { TimeScale } from "chart.js";
import { TimeLineData } from "./const";
export class TimeLineScale extends TimeScale {
static id = "timeline";
static defaults = {
position: "bottom",
tooltips: {
mode: "nearest",
},
ticks: {
autoSkip: true,
},
};
determineDataLimits() {
const options = this.options;
// @ts-ignore
const adapter = this._adapter;
const unit = options.time.unit || "day";
let { min, max } = this.getUserBounds();
const chart = this.chart;
// Convert data to timestamps
chart.data.datasets.forEach((dataset, index) => {
if (!chart.isDatasetVisible(index)) {
return;
}
for (const data of dataset.data as TimeLineData[]) {
let timestamp0 = adapter.parse(data.start, this);
let timestamp1 = adapter.parse(data.end, this);
if (timestamp0 > timestamp1) {
[timestamp0, timestamp1] = [timestamp1, timestamp0];
}
if (min > timestamp0 && timestamp0) {
min = timestamp0;
}
if (max < timestamp1 && timestamp1) {
max = timestamp1;
}
}
});
// In case there is no valid min/max, var's use today limits
min =
isFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);
max = isFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit);
// Make sure that max is strictly higher than min (required by the lookup table)
this.min = Math.min(min, max - 1);
this.max = Math.max(min + 1, max);
}
}

View File

@@ -0,0 +1,661 @@
/* eslint-plugin-disable lit */
import { IronResizableBehavior } from "@polymer/iron-resizable-behavior/iron-resizable-behavior";
import { mixinBehaviors } from "@polymer/polymer/lib/legacy/class";
import { timeOut } from "@polymer/polymer/lib/utils/async";
import { Debouncer } from "@polymer/polymer/lib/utils/debounce";
import { html } from "@polymer/polymer/lib/utils/html-tag";
import { PolymerElement } from "@polymer/polymer/polymer-element";
import { formatTime } from "../../common/datetime/format_time";
import "../ha-icon-button";
// eslint-disable-next-line no-unused-vars
/* global Chart moment Color */
let scriptsLoaded = null;
class HaChartBase extends mixinBehaviors(
[IronResizableBehavior],
PolymerElement
) {
static get template() {
return html`
<style>
:host {
display: block;
}
.chartHeader {
padding: 6px 0 0 0;
width: 100%;
display: flex;
flex-direction: row;
}
.chartHeader > div {
vertical-align: top;
padding: 0 8px;
}
.chartHeader > div.chartTitle {
padding-top: 8px;
flex: 0 0 0;
max-width: 30%;
}
.chartHeader > div.chartLegend {
flex: 1 1;
min-width: 70%;
}
:root {
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
.chartTooltip {
font-size: 90%;
opacity: 1;
position: absolute;
background: rgba(80, 80, 80, 0.9);
color: white;
border-radius: 3px;
pointer-events: none;
transform: translate(-50%, 12px);
z-index: 1000;
width: 200px;
transition: opacity 0.15s ease-in-out;
}
:host([rtl]) .chartTooltip {
direction: rtl;
}
.chartLegend ul,
.chartTooltip ul {
display: inline-block;
padding: 0 0px;
margin: 5px 0 0 0;
width: 100%;
}
.chartTooltip ul {
margin: 0 3px;
}
.chartTooltip li {
display: block;
white-space: pre-line;
}
.chartTooltip li::first-line {
line-height: 0;
}
.chartTooltip .title {
text-align: center;
font-weight: 500;
}
.chartTooltip .beforeBody {
text-align: center;
font-weight: 300;
word-break: break-all;
}
.chartLegend li {
display: inline-block;
padding: 0 6px;
max-width: 49%;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
box-sizing: border-box;
}
.chartLegend li:nth-child(odd):last-of-type {
/* Make last item take full width if it is odd-numbered. */
max-width: 100%;
}
.chartLegend li[data-hidden] {
text-decoration: line-through;
}
.chartLegend em,
.chartTooltip em {
border-radius: 5px;
display: inline-block;
height: 10px;
margin-right: 4px;
width: 10px;
}
:host([rtl]) .chartTooltip em {
margin-right: inherit;
margin-left: 4px;
}
ha-icon-button {
color: var(--secondary-text-color);
}
</style>
<template is="dom-if" if="[[unit]]">
<div class="chartHeader">
<div class="chartTitle">[[unit]]</div>
<div class="chartLegend">
<ul>
<template is="dom-repeat" items="[[metas]]">
<li on-click="_legendClick" data-hidden$="[[item.hidden]]">
<em style$="background-color:[[item.bgColor]]"></em>
[[item.label]]
</li>
</template>
</ul>
</div>
</div>
</template>
<div id="chartTarget" style="height:40px; width:100%">
<canvas id="chartCanvas"></canvas>
<div
class$="chartTooltip [[tooltip.yAlign]]"
style$="opacity:[[tooltip.opacity]]; top:[[tooltip.top]]; left:[[tooltip.left]]; padding:[[tooltip.yPadding]]px [[tooltip.xPadding]]px"
>
<div class="title">[[tooltip.title]]</div>
<template is="dom-if" if="[[tooltip.beforeBody]]">
<div class="beforeBody">[[tooltip.beforeBody]]</div>
</template>
<div>
<ul>
<template is="dom-repeat" items="[[tooltip.lines]]">
<li>
<em style$="background-color:[[item.bgColor]]"></em
>[[item.text]]
</li>
</template>
</ul>
</div>
</div>
</div>
`;
}
get chart() {
return this._chart;
}
static get properties() {
return {
data: Object,
identifier: String,
rendered: {
type: Boolean,
notify: true,
value: false,
readOnly: true,
},
metas: {
type: Array,
value: () => [],
},
tooltip: {
type: Object,
value: () => ({
opacity: "0",
left: "0",
top: "0",
xPadding: "5",
yPadding: "3",
}),
},
unit: Object,
rtl: {
type: Boolean,
reflectToAttribute: true,
},
};
}
static get observers() {
return ["onPropsChange(data)"];
}
connectedCallback() {
super.connectedCallback();
this._isAttached = true;
this.onPropsChange();
this._resizeListener = () => {
this._debouncer = Debouncer.debounce(
this._debouncer,
timeOut.after(10),
() => {
if (this._isAttached) {
this.resizeChart();
}
}
);
};
if (typeof ResizeObserver === "function") {
this.resizeObserver = new ResizeObserver((entries) => {
entries.forEach(() => {
this._resizeListener();
});
});
this.resizeObserver.observe(this.$.chartTarget);
} else {
this.addEventListener("iron-resize", this._resizeListener);
}
if (scriptsLoaded === null) {
scriptsLoaded = import("../../resources/ha-chart-scripts.js");
}
scriptsLoaded.then((ChartModule) => {
this.ChartClass = ChartModule.default;
this.onPropsChange();
});
}
disconnectedCallback() {
super.disconnectedCallback();
this._isAttached = false;
if (this.resizeObserver) {
this.resizeObserver.unobserve(this.$.chartTarget);
}
this.removeEventListener("iron-resize", this._resizeListener);
if (this._resizeTimer !== undefined) {
clearInterval(this._resizeTimer);
this._resizeTimer = undefined;
}
}
onPropsChange() {
if (!this._isAttached || !this.ChartClass || !this.data) {
return;
}
this.drawChart();
}
_customTooltips(tooltip) {
// Hide if no tooltip
if (tooltip.opacity === 0) {
this.set(["tooltip", "opacity"], 0);
return;
}
// Set caret Position
if (tooltip.yAlign) {
this.set(["tooltip", "yAlign"], tooltip.yAlign);
} else {
this.set(["tooltip", "yAlign"], "no-transform");
}
const title = tooltip.title ? tooltip.title[0] || "" : "";
this.set(["tooltip", "title"], title);
if (tooltip.beforeBody) {
this.set(["tooltip", "beforeBody"], tooltip.beforeBody.join("\n"));
}
const bodyLines = tooltip.body.map((n) => n.lines);
// Set Text
if (tooltip.body) {
this.set(
["tooltip", "lines"],
bodyLines.map((body, i) => {
const colors = tooltip.labelColors[i];
return {
color: colors.borderColor,
bgColor: colors.backgroundColor,
text: body.join("\n"),
};
})
);
}
const parentWidth = this.$.chartTarget.clientWidth;
let positionX = tooltip.caretX;
const positionY = this._chart.canvas.offsetTop + tooltip.caretY;
if (tooltip.caretX + 100 > parentWidth) {
positionX = parentWidth - 100;
} else if (tooltip.caretX < 100) {
positionX = 100;
}
positionX += this._chart.canvas.offsetLeft;
// Display, position, and set styles for font
this.tooltip = {
...this.tooltip,
opacity: 1,
left: `${positionX}px`,
top: `${positionY}px`,
};
}
_legendClick(event) {
event = event || window.event;
event.stopPropagation();
let target = event.target || event.srcElement;
while (target.nodeName !== "LI") {
// user clicked child, find parent LI
target = target.parentElement;
}
const index = event.model.itemsIndex;
const meta = this._chart.getDatasetMeta(index);
meta.hidden =
meta.hidden === null ? !this._chart.data.datasets[index].hidden : null;
this.set(
["metas", index, "hidden"],
this._chart.isDatasetVisible(index) ? null : "hidden"
);
this._chart.update();
}
_drawLegend() {
const chart = this._chart;
// New data for old graph. Keep metadata.
const preserveVisibility =
this._oldIdentifier && this.identifier === this._oldIdentifier;
this._oldIdentifier = this.identifier;
this.set(
"metas",
this._chart.data.datasets.map((x, i) => ({
label: x.label,
color: x.color,
bgColor: x.backgroundColor,
hidden:
preserveVisibility && i < this.metas.length
? this.metas[i].hidden
: !chart.isDatasetVisible(i),
}))
);
let updateNeeded = false;
if (preserveVisibility) {
for (let i = 0; i < this.metas.length; i++) {
const meta = chart.getDatasetMeta(i);
if (!!meta.hidden !== !!this.metas[i].hidden) updateNeeded = true;
meta.hidden = this.metas[i].hidden ? true : null;
}
}
if (updateNeeded) {
chart.update();
}
this.unit = this.data.unit;
}
_formatTickValue(value, index, values) {
if (values.length === 0) {
return value;
}
const date = new Date(values[index].value);
return formatTime(date, this.hass.locale);
}
drawChart() {
const data = this.data.data;
const ctx = this.$.chartCanvas;
if ((!data.datasets || !data.datasets.length) && !this._chart) {
return;
}
if (this.data.type !== "timeline" && data.datasets.length > 0) {
const cnt = data.datasets.length;
const colors = this.constructor.getColorList(cnt);
for (let loopI = 0; loopI < cnt; loopI++) {
data.datasets[loopI].borderColor = colors[loopI].rgbString();
data.datasets[loopI].backgroundColor = colors[loopI]
.alpha(0.6)
.rgbaString();
}
}
if (this._chart) {
this._customTooltips({ opacity: 0 });
this._chart.data = data;
this._chart.update({ duration: 0 });
if (this.isTimeline) {
this._chart.options.scales.yAxes[0].gridLines.display = data.length > 1;
} else if (this.data.legend === true) {
this._drawLegend();
}
this.resizeChart();
} else {
if (!data.datasets) {
return;
}
this._customTooltips({ opacity: 0 });
const plugins = [{ afterRender: () => this._setRendered(true) }];
let options = {
responsive: true,
maintainAspectRatio: false,
animation: {
duration: 0,
},
hover: {
animationDuration: 0,
},
responsiveAnimationDuration: 0,
tooltips: {
enabled: false,
custom: this._customTooltips.bind(this),
},
legend: {
display: false,
},
line: {
spanGaps: true,
},
elements: {
font: "12px 'Roboto', 'sans-serif'",
},
ticks: {
fontFamily: "'Roboto', 'sans-serif'",
},
};
options = Chart.helpers.merge(options, this.data.options);
options.scales.xAxes[0].ticks.callback = this._formatTickValue.bind(this);
if (this.data.type === "timeline") {
this.set("isTimeline", true);
if (this.data.colors !== undefined) {
this._colorFunc = this.constructor.getColorGenerator(
this.data.colors.staticColors,
this.data.colors.staticColorIndex
);
}
if (this._colorFunc !== undefined) {
options.elements.colorFunction = this._colorFunc;
}
if (data.datasets.length === 1) {
if (options.scales.yAxes[0].ticks) {
options.scales.yAxes[0].ticks.display = false;
} else {
options.scales.yAxes[0].ticks = { display: false };
}
if (options.scales.yAxes[0].gridLines) {
options.scales.yAxes[0].gridLines.display = false;
} else {
options.scales.yAxes[0].gridLines = { display: false };
}
}
this.$.chartTarget.style.height = "50px";
} else {
this.$.chartTarget.style.height = "160px";
}
const chartData = {
type: this.data.type,
data: this.data.data,
options: options,
plugins: plugins,
};
// Async resize after dom update
this._chart = new this.ChartClass(ctx, chartData);
if (this.isTimeline !== true && this.data.legend === true) {
this._drawLegend();
}
this.resizeChart();
}
}
resizeChart() {
if (!this._chart) return;
// Chart not ready
if (this._resizeTimer === undefined) {
this._resizeTimer = setInterval(this.resizeChart.bind(this), 10);
return;
}
clearInterval(this._resizeTimer);
this._resizeTimer = undefined;
this._resizeChart();
}
_resizeChart() {
const chartTarget = this.$.chartTarget;
const options = this.data;
const data = options.data;
if (data.datasets.length === 0) {
return;
}
if (!this.isTimeline) {
this._chart.resize();
return;
}
// Recalculate chart height for Timeline chart
const areaTop = this._chart.chartArea.top;
const areaBot = this._chart.chartArea.bottom;
const height1 = this._chart.canvas.clientHeight;
if (areaBot > 0) {
this._axisHeight = height1 - areaBot + areaTop;
}
if (!this._axisHeight) {
chartTarget.style.height = "50px";
this._chart.resize();
this.resizeChart();
return;
}
if (this._axisHeight) {
const cnt = data.datasets.length;
const targetHeight = 30 * cnt + this._axisHeight + "px";
if (chartTarget.style.height !== targetHeight) {
chartTarget.style.height = targetHeight;
}
this._chart.resize();
}
}
// Get HSL distributed color list
static getColorList(count) {
let processL = false;
if (count > 10) {
processL = true;
count = Math.ceil(count / 2);
}
const h1 = 360 / count;
const result = [];
for (let loopI = 0; loopI < count; loopI++) {
result[loopI] = Color().hsl(h1 * loopI, 80, 38);
if (processL) {
result[loopI + count] = Color().hsl(h1 * loopI, 80, 62);
}
}
return result;
}
static getColorGenerator(staticColors, startIndex) {
// Known colors for static data,
// should add for very common state string manually.
// Palette modified from http://google.github.io/palette.js/ mpn65, Apache 2.0
const palette = [
"ff0029",
"66a61e",
"377eb8",
"984ea3",
"00d2d5",
"ff7f00",
"af8d00",
"7f80cd",
"b3e900",
"c42e60",
"a65628",
"f781bf",
"8dd3c7",
"bebada",
"fb8072",
"80b1d3",
"fdb462",
"fccde5",
"bc80bd",
"ffed6f",
"c4eaff",
"cf8c00",
"1b9e77",
"d95f02",
"e7298a",
"e6ab02",
"a6761d",
"0097ff",
"00d067",
"f43600",
"4ba93b",
"5779bb",
"927acc",
"97ee3f",
"bf3947",
"9f5b00",
"f48758",
"8caed6",
"f2b94f",
"eff26e",
"e43872",
"d9b100",
"9d7a00",
"698cff",
"d9d9d9",
"00d27e",
"d06800",
"009f82",
"c49200",
"cbe8ff",
"fecddf",
"c27eb6",
"8cd2ce",
"c4b8d9",
"f883b0",
"a49100",
"f48800",
"27d0df",
"a04a9b",
];
function getColorIndex(idx) {
// Reuse the color if index too large.
return Color("#" + palette[idx % palette.length]);
}
const colorDict = {};
let colorIndex = 0;
if (startIndex > 0) colorIndex = startIndex;
if (staticColors) {
Object.keys(staticColors).forEach((c) => {
const c1 = staticColors[c];
if (isFinite(c1)) {
colorDict[c.toLowerCase()] = getColorIndex(c1);
} else {
colorDict[c.toLowerCase()] = Color(staticColors[c]);
}
});
}
// Custom color assign
function getColor(__, data) {
let ret;
const name = data[3];
if (name === null) return Color().hsl(0, 40, 38);
if (name === undefined) return Color().hsl(120, 40, 38);
let name1 = name.toLowerCase();
if (ret === undefined) {
if (data[4]) {
// Invert on/off if data[4] is true. Required for some binary_sensor device classes
// (BINARY_SENSOR_DEVICE_CLASS_COLOR_INVERTED) where "off" is the good (= green color) value.
name1 = name1 === "on" ? "off" : name1 === "off" ? "on" : name1;
}
ret = colorDict[name1];
}
if (ret === undefined) {
ret = getColorIndex(colorIndex);
colorIndex++;
colorDict[name1] = ret;
}
return ret;
}
return getColor;
}
}
customElements.define("ha-chart-base", HaChartBase);

View File

@@ -1,19 +1,14 @@
import "@material/mwc-icon-button/mwc-icon-button";
import { mdiClose, mdiMenuDown } from "@mdi/js";
import "@polymer/paper-input/paper-input";
import "@polymer/paper-item/paper-item";
import "@polymer/paper-listbox/paper-listbox";
import "@polymer/paper-menu-button/paper-menu-button";
import "@polymer/paper-ripple/paper-ripple";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, query } from "lit/decorators";
import { fireEvent } from "../../common/dom/fire_event";
import "../ha-svg-icon";
import "../ha-paper-dropdown-menu";
import { HaFormElement, HaFormSelectData, HaFormSelectSchema } from "./ha-form";
@customElement("ha-form-select")
export class HaFormSelect extends LitElement implements HaFormElement {
@property({ attribute: false }) public schema!: HaFormSelectSchema;
@property() public schema!: HaFormSelectSchema;
@property() public data!: HaFormSelectData;
@@ -31,33 +26,7 @@ export class HaFormSelect extends LitElement implements HaFormElement {
protected render(): TemplateResult {
return html`
<paper-menu-button horizontal-align="right" vertical-offset="8">
<div class="dropdown-trigger" slot="dropdown-trigger">
<paper-ripple></paper-ripple>
<paper-input
id="input"
type="text"
readonly
value=${this.data}
label=${this.label}
input-role="button"
input-aria-haspopup="listbox"
autocomplete="off"
>
${this.data && this.schema.optional
? html`<mwc-icon-button
slot="suffix"
class="clear-button"
@click=${this._clearValue}
>
<ha-svg-icon .path=${mdiClose}></ha-svg-icon>
</mwc-icon-button>`
: ""}
<mwc-icon-button slot="suffix">
<ha-svg-icon .path=${mdiMenuDown}></ha-svg-icon>
</mwc-icon-button>
</paper-input>
</div>
<ha-paper-dropdown-menu .label=${this.label}>
<paper-listbox
slot="dropdown-content"
attr-for-selected="item-value"
@@ -76,7 +45,7 @@ export class HaFormSelect extends LitElement implements HaFormElement {
)
}
</paper-listbox>
</paper-menu-button>
</ha-paper-dropdown-menu>
`;
}
@@ -88,11 +57,6 @@ export class HaFormSelect extends LitElement implements HaFormElement {
return Array.isArray(item) ? item[1] || item[0] : item;
}
private _clearValue(ev: CustomEvent) {
ev.stopPropagation();
fireEvent(this, "value-changed", { value: undefined });
}
private _valueChanged(ev: CustomEvent) {
if (!ev.detail.value) {
return;
@@ -104,16 +68,8 @@ export class HaFormSelect extends LitElement implements HaFormElement {
static get styles(): CSSResultGroup {
return css`
paper-menu-button {
ha-paper-dropdown-menu {
display: block;
padding: 0;
}
paper-input > mwc-icon-button {
--mdc-icon-button-size: 24px;
padding: 2px;
}
.clear-button {
color: var(--secondary-text-color);
}
`;
}

View File

@@ -7,7 +7,7 @@ import {
PropertyValues,
TemplateResult,
} from "lit";
import { customElement, property, query } from "lit/decorators";
import { customElement, property, query, state } from "lit/decorators";
import { fireEvent } from "../common/dom/fire_event";
import { nextRender } from "../common/util/render-status";
import { getExternalConfig } from "../external_app/external_config";
@@ -42,23 +42,27 @@ class HaHLSPlayer extends LitElement {
// don't cache this, as we remove it on disconnects
@query("video") private _videoEl!: HTMLVideoElement;
@state() private _attached = false;
private _hlsPolyfillInstance?: HlsLite;
private _exoPlayer = false;
private _useExoPlayer = false;
public connectedCallback() {
super.connectedCallback();
if (this.hasUpdated) {
this._startHls();
}
this._attached = true;
}
public disconnectedCallback() {
super.disconnectedCallback();
this._cleanUp();
this._attached = false;
}
protected render(): TemplateResult {
if (!this._attached) {
return html``;
}
return html`
<video
?autoplay=${this.autoPlay}
@@ -73,13 +77,21 @@ class HaHLSPlayer extends LitElement {
protected updated(changedProps: PropertyValues) {
super.updated(changedProps);
const attachedChanged = changedProps.has("_attached");
const urlChanged = changedProps.has("url");
if (!urlChanged) {
if (!urlChanged && !attachedChanged) {
return;
}
this._cleanUp();
// If we are no longer attached, destroy polyfill
if (attachedChanged && !this._attached) {
// Tear down existing polyfill, if available
this._destroyPolyfill();
return;
}
this._destroyPolyfill();
this._startHls();
}
@@ -106,13 +118,13 @@ class HaHLSPlayer extends LitElement {
}
if (!hlsSupported) {
videoEl.innerHTML = this.hass.localize(
this._videoEl.innerHTML = this.hass.localize(
"ui.components.media-browser.video_not_supported"
);
return;
}
const useExoPlayer = await useExoPlayerPromise;
this._useExoPlayer = await useExoPlayerPromise;
const masterPlaylist = await (await masterPlaylistPromise).text();
// Parse playlist assuming it is a master playlist. Match group 1 is whether hevc, match group 2 is regular playlist url
@@ -132,7 +144,7 @@ class HaHLSPlayer extends LitElement {
}
// If codec is HEVC and ExoPlayer is supported, use ExoPlayer.
if (useExoPlayer && match !== null && match[1] !== undefined) {
if (this._useExoPlayer && match !== null && match[1] !== undefined) {
this._renderHLSExoPlayer(playlist_url);
} else if (Hls.isSupported()) {
this._renderHLSPolyfill(videoEl, Hls, playlist_url);
@@ -142,7 +154,6 @@ class HaHLSPlayer extends LitElement {
}
private async _renderHLSExoPlayer(url: string) {
this._exoPlayer = true;
window.addEventListener("resize", this._resizeExoPlayer);
this.updateComplete.then(() => nextRender()).then(this._resizeExoPlayer);
this._videoEl.style.visibility = "hidden";
@@ -191,28 +202,25 @@ class HaHLSPlayer extends LitElement {
private async _renderHLSNative(videoEl: HTMLVideoElement, url: string) {
videoEl.src = url;
videoEl.addEventListener("loadedmetadata", () => {
videoEl.play();
});
await new Promise((resolve) =>
videoEl.addEventListener("loadedmetadata", resolve)
);
videoEl.play();
}
private _elementResized() {
fireEvent(this, "iron-resize");
}
private _cleanUp() {
private _destroyPolyfill() {
if (this._hlsPolyfillInstance) {
this._hlsPolyfillInstance.destroy();
this._hlsPolyfillInstance = undefined;
}
if (this._exoPlayer) {
if (this._useExoPlayer) {
window.removeEventListener("resize", this._resizeExoPlayer);
this.hass!.auth.external!.fireMessage({ type: "exoplayer/stop" });
this._exoPlayer = false;
}
const videoEl = this._videoEl;
videoEl.removeAttribute("src");
videoEl.load();
}
static get styles(): CSSResultGroup {

View File

@@ -0,0 +1,433 @@
import "@polymer/polymer/lib/utils/debounce";
import { html } from "@polymer/polymer/lib/utils/html-tag";
/* eslint-plugin-disable lit */
import { PolymerElement } from "@polymer/polymer/polymer-element";
import { formatDateTimeWithSeconds } from "../common/datetime/format_date_time";
import LocalizeMixin from "../mixins/localize-mixin";
import "./entity/ha-chart-base";
class StateHistoryChartLine extends LocalizeMixin(PolymerElement) {
static get template() {
return html`
<style>
:host {
display: block;
overflow: hidden;
height: 0;
transition: height 0.3s ease-in-out;
}
</style>
<ha-chart-base
id="chart"
hass="[[hass]]"
data="[[chartData]]"
identifier="[[identifier]]"
rendered="{{rendered}}"
></ha-chart-base>
`;
}
static get properties() {
return {
hass: {
type: Object,
},
chartData: Object,
data: Object,
names: Object,
unit: String,
identifier: String,
isSingleDevice: {
type: Boolean,
value: false,
},
endTime: Object,
rendered: {
type: Boolean,
value: false,
observer: "_onRenderedChanged",
},
};
}
static get observers() {
return ["dataChanged(data, endTime, isSingleDevice)"];
}
connectedCallback() {
super.connectedCallback();
this._isAttached = true;
this.drawChart();
}
ready() {
super.ready();
// safari doesn't always render the canvas when we animate it, so we remove overflow hidden when the animation is complete
this.addEventListener("transitionend", () => {
this.style.overflow = "auto";
});
}
dataChanged() {
this.drawChart();
}
_onRenderedChanged(rendered) {
if (rendered) {
this.animateHeight();
}
}
animateHeight() {
requestAnimationFrame(() =>
requestAnimationFrame(() => {
this.style.height = this.$.chart.scrollHeight + "px";
})
);
}
drawChart() {
if (!this._isAttached) {
return;
}
const unit = this.unit;
const deviceStates = this.data;
const datasets = [];
let endTime;
if (deviceStates.length === 0) {
return;
}
function safeParseFloat(value) {
const parsed = parseFloat(value);
return isFinite(parsed) ? parsed : null;
}
endTime =
this.endTime ||
// Get the highest date from the last date of each device
new Date(
Math.max.apply(
null,
deviceStates.map(
(devSts) =>
new Date(devSts.states[devSts.states.length - 1].last_changed)
)
)
);
if (endTime > new Date()) {
endTime = new Date();
}
const names = this.names || {};
deviceStates.forEach((states) => {
const domain = states.domain;
const name = names[states.entity_id] || states.name;
// array containing [value1, value2, etc]
let prevValues;
const data = [];
function pushData(timestamp, datavalues) {
if (!datavalues) return;
if (timestamp > endTime) {
// Drop datapoints that are after the requested endTime. This could happen if
// endTime is "now" and client time is not in sync with server time.
return;
}
data.forEach((d, i) => {
if (datavalues[i] === null && prevValues && prevValues[i] !== null) {
// null data values show up as gaps in the chart.
// If the current value for the dataset is null and the previous
// value of the data set is not null, then add an 'end' point
// to the chart for the previous value. Otherwise the gap will
// be too big. It will go from the start of the previous data
// value until the start of the next data value.
d.data.push({ x: timestamp, y: prevValues[i] });
}
d.data.push({ x: timestamp, y: datavalues[i] });
});
prevValues = datavalues;
}
function addColumn(nameY, step, fill) {
let dataFill = false;
let dataStep = false;
if (fill) {
dataFill = "origin";
}
if (step) {
dataStep = "before";
}
data.push({
label: nameY,
fill: dataFill,
steppedLine: dataStep,
pointRadius: 0,
data: [],
unitText: unit,
});
}
if (
domain === "thermostat" ||
domain === "climate" ||
domain === "water_heater"
) {
const hasHvacAction = states.states.some(
(state) => state.attributes && state.attributes.hvac_action
);
const isHeating =
domain === "climate" && hasHvacAction
? (state) => state.attributes.hvac_action === "heating"
: (state) => state.state === "heat";
const isCooling =
domain === "climate" && hasHvacAction
? (state) => state.attributes.hvac_action === "cooling"
: (state) => state.state === "cool";
const hasHeat = states.states.some(isHeating);
const hasCool = states.states.some(isCooling);
// We differentiate between thermostats that have a target temperature
// range versus ones that have just a target temperature
// Using step chart by step-before so manually interpolation not needed.
const hasTargetRange = states.states.some(
(state) =>
state.attributes &&
state.attributes.target_temp_high !==
state.attributes.target_temp_low
);
addColumn(
`${this.hass.localize(
"ui.card.climate.current_temperature",
"name",
name
)}`,
true
);
if (hasHeat) {
addColumn(
`${this.hass.localize("ui.card.climate.heating", "name", name)}`,
true,
true
);
// The "heating" series uses steppedArea to shade the area below the current
// temperature when the thermostat is calling for heat.
}
if (hasCool) {
addColumn(
`${this.hass.localize("ui.card.climate.cooling", "name", name)}`,
true,
true
);
// The "cooling" series uses steppedArea to shade the area below the current
// temperature when the thermostat is calling for heat.
}
if (hasTargetRange) {
addColumn(
`${this.hass.localize(
"ui.card.climate.target_temperature_mode",
"name",
name,
"mode",
this.hass.localize("ui.card.climate.high")
)}`,
true
);
addColumn(
`${this.hass.localize(
"ui.card.climate.target_temperature_mode",
"name",
name,
"mode",
this.hass.localize("ui.card.climate.low")
)}`,
true
);
} else {
addColumn(
`${this.hass.localize(
"ui.card.climate.target_temperature_entity",
"name",
name
)}`,
true
);
}
states.states.forEach((state) => {
if (!state.attributes) return;
const curTemp = safeParseFloat(state.attributes.current_temperature);
const series = [curTemp];
if (hasHeat) {
series.push(isHeating(state) ? curTemp : null);
}
if (hasCool) {
series.push(isCooling(state) ? curTemp : null);
}
if (hasTargetRange) {
const targetHigh = safeParseFloat(
state.attributes.target_temp_high
);
const targetLow = safeParseFloat(state.attributes.target_temp_low);
series.push(targetHigh, targetLow);
pushData(new Date(state.last_changed), series);
} else {
const target = safeParseFloat(state.attributes.temperature);
series.push(target);
pushData(new Date(state.last_changed), series);
}
});
} else if (domain === "humidifier") {
addColumn(
`${this.hass.localize(
"ui.card.humidifier.target_humidity_entity",
"name",
name
)}`,
true
);
addColumn(
`${this.hass.localize("ui.card.humidifier.on_entity", "name", name)}`,
true,
true
);
states.states.forEach((state) => {
if (!state.attributes) return;
const target = safeParseFloat(state.attributes.humidity);
const series = [target];
series.push(state.state === "on" ? target : null);
pushData(new Date(state.last_changed), series);
});
} else {
// Only disable interpolation for sensors
const isStep = domain === "sensor";
addColumn(name, isStep);
let lastValue = null;
let lastDate = null;
let lastNullDate = null;
// Process chart data.
// When state is `unknown`, calculate the value and break the line.
states.states.forEach((state) => {
const value = safeParseFloat(state.state);
const date = new Date(state.last_changed);
if (value !== null && lastNullDate !== null) {
const dateTime = date.getTime();
const lastNullDateTime = lastNullDate.getTime();
const lastDateTime = lastDate.getTime();
const tmpValue =
(value - lastValue) *
((lastNullDateTime - lastDateTime) /
(dateTime - lastDateTime)) +
lastValue;
pushData(lastNullDate, [tmpValue]);
pushData(new Date(lastNullDateTime + 1), [null]);
pushData(date, [value]);
lastDate = date;
lastValue = value;
lastNullDate = null;
} else if (value !== null && lastNullDate === null) {
pushData(date, [value]);
lastDate = date;
lastValue = value;
} else if (
value === null &&
lastNullDate === null &&
lastValue !== null
) {
lastNullDate = date;
}
});
}
// Add an entry for final values
pushData(endTime, prevValues, false);
// Concat two arrays
Array.prototype.push.apply(datasets, data);
});
const formatTooltipTitle = (items, data) => {
const item = items[0];
const date = data.datasets[item.datasetIndex].data[item.index].x;
return formatDateTimeWithSeconds(date, this.hass.locale);
};
const chartOptions = {
type: "line",
unit: unit,
legend: !this.isSingleDevice,
options: {
scales: {
xAxes: [
{
type: "time",
ticks: {
major: {
fontStyle: "bold",
},
source: "auto",
sampleSize: 5,
autoSkipPadding: 20,
maxRotation: 0,
},
},
],
yAxes: [
{
ticks: {
maxTicksLimit: 7,
},
},
],
},
tooltips: {
mode: "neareach",
callbacks: {
title: formatTooltipTitle,
},
},
hover: {
mode: "neareach",
},
layout: {
padding: {
top: 5,
},
},
elements: {
line: {
tension: 0.1,
pointRadius: 0,
borderWidth: 1.5,
},
point: {
hitRadius: 5,
},
},
plugins: {
filler: {
propagate: true,
},
},
},
data: {
labels: [],
datasets: datasets,
},
};
this.chartData = chartOptions;
}
}
customElements.define("state-history-chart-line", StateHistoryChartLine);

View File

@@ -0,0 +1,286 @@
import "@polymer/polymer/lib/utils/debounce";
import { html } from "@polymer/polymer/lib/utils/html-tag";
/* eslint-plugin-disable lit */
import { PolymerElement } from "@polymer/polymer/polymer-element";
import { formatDateTimeWithSeconds } from "../common/datetime/format_date_time";
import { computeDomain } from "../common/entity/compute_domain";
import { computeRTL } from "../common/util/compute_rtl";
import LocalizeMixin from "../mixins/localize-mixin";
import "./entity/ha-chart-base";
/** Binary sensor device classes for which the static colors for on/off need to be inverted.
* List the ones were "off" = good or normal state = should be rendered "green".
*/
const BINARY_SENSOR_DEVICE_CLASS_COLOR_INVERTED = new Set([
"battery",
"door",
"garage_door",
"gas",
"lock",
"opening",
"problem",
"safety",
"smoke",
"window",
]);
class StateHistoryChartTimeline extends LocalizeMixin(PolymerElement) {
static get template() {
return html`
<style>
:host {
display: block;
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
:host([rendered]) {
opacity: 1;
}
ha-chart-base {
direction: ltr;
}
</style>
<ha-chart-base
hass="[[hass]]"
data="[[chartData]]"
rendered="{{rendered}}"
rtl="{{rtl}}"
></ha-chart-base>
`;
}
static get properties() {
return {
hass: {
type: Object,
},
chartData: Object,
data: {
type: Object,
observer: "dataChanged",
},
names: Object,
noSingle: Boolean,
endTime: Date,
rendered: {
type: Boolean,
value: false,
reflectToAttribute: true,
},
rtl: {
reflectToAttribute: true,
computed: "_computeRTL(hass)",
},
};
}
static get observers() {
return ["dataChanged(data, endTime, localize, language)"];
}
connectedCallback() {
super.connectedCallback();
this._isAttached = true;
this.drawChart();
}
dataChanged() {
this.drawChart();
}
drawChart() {
const staticColors = {
on: 1,
off: 0,
home: 1,
not_home: 0,
unavailable: "#a0a0a0",
unknown: "#606060",
idle: 2,
};
let stateHistory = this.data;
if (!this._isAttached) {
return;
}
if (!stateHistory) {
stateHistory = [];
}
const startTime = new Date(
stateHistory.reduce(
(minTime, stateInfo) =>
Math.min(minTime, new Date(stateInfo.data[0].last_changed)),
new Date()
)
);
// end time is Math.max(startTime, last_event)
let endTime =
this.endTime ||
new Date(
stateHistory.reduce(
(maxTime, stateInfo) =>
Math.max(
maxTime,
new Date(stateInfo.data[stateInfo.data.length - 1].last_changed)
),
startTime
)
);
if (endTime > new Date()) {
endTime = new Date();
}
const labels = [];
const datasets = [];
// stateHistory is a list of lists of sorted state objects
const names = this.names || {};
stateHistory.forEach((stateInfo) => {
let newLastChanged;
let prevState = null;
let locState = null;
let prevLastChanged = startTime;
const entityDisplay = names[stateInfo.entity_id] || stateInfo.name;
const invertOnOff =
computeDomain(stateInfo.entity_id) === "binary_sensor" &&
BINARY_SENSOR_DEVICE_CLASS_COLOR_INVERTED.has(
this.hass.states[stateInfo.entity_id].attributes.device_class
);
const dataRow = [];
stateInfo.data.forEach((state) => {
let newState = state.state;
const timeStamp = new Date(state.last_changed);
if (newState === undefined || newState === "") {
newState = null;
}
if (timeStamp > endTime) {
// Drop datapoints that are after the requested endTime. This could happen if
// endTime is 'now' and client time is not in sync with server time.
return;
}
if (prevState !== null && newState !== prevState) {
newLastChanged = new Date(state.last_changed);
dataRow.push([
prevLastChanged,
newLastChanged,
locState,
prevState,
invertOnOff,
]);
prevState = newState;
locState = state.state_localize;
prevLastChanged = newLastChanged;
} else if (prevState === null) {
prevState = newState;
locState = state.state_localize;
prevLastChanged = new Date(state.last_changed);
}
});
if (prevState !== null) {
dataRow.push([
prevLastChanged,
endTime,
locState,
prevState,
invertOnOff,
]);
}
datasets.push({
data: dataRow,
entity_id: stateInfo.entity_id,
});
labels.push(entityDisplay);
});
const formatTooltipLabel = (item, data) => {
const values = data.datasets[item.datasetIndex].data[item.index];
const start = formatDateTimeWithSeconds(values[0], this.hass.locale);
const end = formatDateTimeWithSeconds(values[1], this.hass.locale);
const state = values[2];
return [state, start, end];
};
const formatTooltipBeforeBody = (item, data) => {
if (!this.hass.userData || !this.hass.userData.showAdvanced || !item[0]) {
return "";
}
// Extract the entity ID from the dataset.
const values = data.datasets[item[0].datasetIndex];
return values.entity_id || "";
};
const chartOptions = {
type: "timeline",
options: {
tooltips: {
callbacks: {
label: formatTooltipLabel,
beforeBody: formatTooltipBeforeBody,
},
},
scales: {
xAxes: [
{
ticks: {
major: {
fontStyle: "bold",
},
sampleSize: 5,
autoSkipPadding: 50,
maxRotation: 0,
},
categoryPercentage: undefined,
barPercentage: undefined,
time: {
format: undefined,
},
},
],
yAxes: [
{
afterSetDimensions: (yaxe) => {
yaxe.maxWidth = yaxe.chart.width * 0.18;
},
position: this._computeRTL ? "right" : "left",
categoryPercentage: undefined,
barPercentage: undefined,
time: { format: undefined },
},
],
},
},
datasets: {
categoryPercentage: 0.8,
barPercentage: 0.9,
},
data: {
labels: labels,
datasets: datasets,
},
colors: {
staticColors: staticColors,
staticColorIndex: 3,
},
};
this.chartData = chartOptions;
}
_computeRTL(hass) {
return computeRTL(hass);
}
}
customElements.define(
"state-history-chart-timeline",
StateHistoryChartTimeline
);

View File

@@ -7,10 +7,10 @@ import {
TemplateResult,
} from "lit";
import { customElement, property } from "lit/decorators";
import { isComponentLoaded } from "../../common/config/is_component_loaded";
import { HistoryResult } from "../../data/history";
import type { HomeAssistant } from "../../types";
import "../ha-circular-progress";
import { isComponentLoaded } from "../common/config/is_component_loaded";
import { HistoryResult } from "../data/history";
import type { HomeAssistant } from "../types";
import "./ha-circular-progress";
import "./state-history-chart-line";
import "./state-history-chart-timeline";
@@ -24,7 +24,7 @@ class StateHistoryCharts extends LitElement {
@property({ attribute: false }) public endTime?: Date;
@property({ type: Boolean, attribute: "up-to-now" }) public upToNow = false;
@property({ type: Boolean }) public upToNow = false;
@property({ type: Boolean, attribute: "no-single" }) public noSingle = false;
@@ -101,12 +101,12 @@ class StateHistoryCharts extends LitElement {
return css`
:host {
display: block;
/* height of single timeline chart = 60px */
min-height: 60px;
/* height of single timeline chart = 58px */
min-height: 58px;
}
.info {
text-align: center;
line-height: 60px;
line-height: 58px;
color: var(--secondary-text-color);
}
`;

View File

@@ -8,7 +8,7 @@ export class HatGraphNode extends LitElement {
@property({ reflect: true, type: Boolean }) disabled?: boolean;
@property({ reflect: true, type: Boolean }) graphStart?: boolean;
@property({ reflect: true, type: Boolean }) graphstart?: boolean;
@property({ reflect: true, type: Boolean }) nofocus?: boolean;
@@ -21,20 +21,20 @@ export class HatGraphNode extends LitElement {
}
render() {
const height = NODE_SIZE + (this.graphStart ? 2 : SPACING + 1);
const height = NODE_SIZE + (this.graphstart ? 2 : SPACING + 1);
const width = SPACING + NODE_SIZE;
return svg`
<svg
width="${width}px"
height="${height}px"
viewBox="-${Math.ceil(width / 2)} -${
this.graphStart
this.graphstart
? Math.ceil(height / 2)
: Math.ceil((NODE_SIZE + SPACING * 2) / 2)
} ${width} ${height}"
>
${
this.graphStart
this.graphstart
? ``
: svg`
<path

View File

@@ -30,16 +30,16 @@ export class HatGraph extends LitElement {
@property({ reflect: true, type: Boolean }) branching?: boolean;
@property({ converter: track_converter })
@property({ reflect: true, converter: track_converter })
track_start?: number[];
@property({ converter: track_converter }) track_end?: number[];
@property({ reflect: true, converter: track_converter }) track_end?: number[];
@property({ reflect: true, type: Boolean }) disabled?: boolean;
@property({ type: Boolean }) selected?: boolean;
@property({ reflect: true, type: Boolean }) selected?: boolean;
@property({ type: Boolean }) short = false;
@property({ reflect: true, type: Boolean }) short = false;
async updateChildren() {
this._num_items = this.children.length;
@@ -68,7 +68,7 @@ export class HatGraph extends LitElement {
return html`
<slot name="head" @slotchange=${this.updateChildren}> </slot>
${this.branching && branches.some((branch) => !branch.start)
${this.branching
? svg`
<svg
id="top"

View File

@@ -1,13 +1,11 @@
import { css, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement } from "lit/decorators";
@customElement("hat-logbook-note")
class HatLogbookNote extends LitElement {
@property() public domain = "automation";
render() {
return html`
Not all shown logbook entries might be related to this ${this.domain}.
Not all shown logbook entries might be related to this automation.
`;
}

View File

@@ -36,9 +36,9 @@ import {
WaitForTriggerAction,
} from "../../data/script";
import {
AutomationTraceExtended,
ChooseActionTraceStep,
ConditionTraceStep,
TraceExtended,
} from "../../data/trace";
import "../ha-svg-icon";
import { NodeInfo, NODE_SIZE, SPACING } from "./hat-graph";
@@ -53,7 +53,7 @@ declare global {
@customElement("hat-script-graph")
class HatScriptGraph extends LitElement {
@property({ attribute: false }) public trace!: TraceExtended;
@property({ attribute: false }) public trace!: AutomationTraceExtended;
@property({ attribute: false }) public selected;
@@ -137,11 +137,7 @@ class HatScriptGraph extends LitElement {
`;
}
private render_choose_node(
config: ChooseAction,
path: string,
graphStart = false
) {
private render_choose_node(config: ChooseAction, path: string) {
const trace = this.trace.trace[path] as ChooseActionTraceStep[] | undefined;
const trace_path = trace?.[0].result
? trace[0].result.choice === "default"
@@ -161,7 +157,6 @@ class HatScriptGraph extends LitElement {
})}
>
<hat-graph-node
.graphStart=${graphStart}
.iconPath=${mdiCallSplit}
class=${classMap({
track: trace !== undefined,
@@ -215,11 +210,7 @@ class HatScriptGraph extends LitElement {
`;
}
private render_condition_node(
node: Condition,
path: string,
graphStart = false
) {
private render_condition_node(node: Condition, path: string) {
const trace = (this.trace.trace[path] as ConditionTraceStep[]) || undefined;
const track_path =
trace?.[0].result === undefined ? 0 : trace[0].result.result ? 1 : 2;
@@ -237,18 +228,23 @@ class HatScriptGraph extends LitElement {
short
>
<hat-graph-node
.graphStart=${graphStart}
slot="head"
class=${classMap({
track: Boolean(trace),
})}
.iconPath=${mdiAbTesting}
nofocus
graphEnd
></hat-graph-node>
<div style=${`width: ${NODE_SIZE + SPACING}px;`}></div>
<div
style=${`width: ${NODE_SIZE + SPACING}px;`}
graphStart
graphEnd
></div>
<div></div>
<hat-graph-node
.iconPath=${mdiClose}
graphEnd
nofocus
class=${classMap({
track: track_path === 2,
@@ -258,14 +254,9 @@ class HatScriptGraph extends LitElement {
`;
}
private render_delay_node(
node: DelayAction,
path: string,
graphStart = false
) {
private render_delay_node(node: DelayAction, path: string) {
return html`
<hat-graph-node
.graphStart=${graphStart}
.iconPath=${mdiTimerOutline}
@focus=${this.selectNode(node, path)}
class=${classMap({
@@ -277,14 +268,9 @@ class HatScriptGraph extends LitElement {
`;
}
private render_device_node(
node: DeviceAction,
path: string,
graphStart = false
) {
private render_device_node(node: DeviceAction, path: string) {
return html`
<hat-graph-node
.graphStart=${graphStart}
.iconPath=${mdiDevices}
@focus=${this.selectNode(node, path)}
class=${classMap({
@@ -296,14 +282,9 @@ class HatScriptGraph extends LitElement {
`;
}
private render_event_node(
node: EventAction,
path: string,
graphStart = false
) {
private render_event_node(node: EventAction, path: string) {
return html`
<hat-graph-node
.graphStart=${graphStart}
.iconPath=${mdiExclamation}
@focus=${this.selectNode(node, path)}
class=${classMap({
@@ -315,11 +296,7 @@ class HatScriptGraph extends LitElement {
`;
}
private render_repeat_node(
node: RepeatAction,
path: string,
graphStart = false
) {
private render_repeat_node(node: RepeatAction, path: string) {
const trace: any = this.trace.trace[path];
const track_path = trace ? [0, 1] : [];
const repeats = this.trace?.trace[`${path}/repeat/sequence/0`]?.length;
@@ -336,7 +313,6 @@ class HatScriptGraph extends LitElement {
})}
>
<hat-graph-node
.graphStart=${graphStart}
.iconPath=${mdiRefresh}
class=${classMap({
track: trace,
@@ -361,14 +337,9 @@ class HatScriptGraph extends LitElement {
`;
}
private render_scene_node(
node: SceneAction,
path: string,
graphStart = false
) {
private render_scene_node(node: SceneAction, path: string) {
return html`
<hat-graph-node
.graphStart=${graphStart}
.iconPath=${mdiExclamation}
@focus=${this.selectNode(node, path)}
class=${classMap({
@@ -380,14 +351,9 @@ class HatScriptGraph extends LitElement {
`;
}
private render_service_node(
node: ServiceAction,
path: string,
graphStart = false
) {
private render_service_node(node: ServiceAction, path: string) {
return html`
<hat-graph-node
.graphStart=${graphStart}
.iconPath=${mdiChevronRight}
@focus=${this.selectNode(node, path)}
class=${classMap({
@@ -401,12 +367,10 @@ class HatScriptGraph extends LitElement {
private render_wait_node(
node: WaitAction | WaitForTriggerAction,
path: string,
graphStart = false
path: string
) {
return html`
<hat-graph-node
.graphStart=${graphStart}
.iconPath=${mdiTrafficLight}
@focus=${this.selectNode(node, path)}
class=${classMap({
@@ -418,10 +382,9 @@ class HatScriptGraph extends LitElement {
`;
}
private render_other_node(node: Action, path: string, graphStart = false) {
private render_other_node(node: Action, path: string) {
return html`
<hat-graph-node
.graphStart=${graphStart}
.iconPath=${mdiCodeBrackets}
@focus=${this.selectNode(node, path)}
class=${classMap({
@@ -432,7 +395,7 @@ class HatScriptGraph extends LitElement {
`;
}
private render_node(node: Action, path: string, graphStart = false) {
private render_node(node: Action, path: string) {
const NODE_TYPES = {
choose: this.render_choose_node,
condition: this.render_condition_node,
@@ -448,7 +411,7 @@ class HatScriptGraph extends LitElement {
};
const type = Object.keys(NODE_TYPES).find((key) => key in node) || "other";
const nodeEl = NODE_TYPES[type].bind(this)(node, path, graphStart);
const nodeEl = NODE_TYPES[type].bind(this)(node, path);
this.renderedNodes[path] = { config: node, path };
if (this.trace && path in this.trace.trace) {
this.trackedNodes[path] = this.renderedNodes[path];
@@ -460,47 +423,35 @@ class HatScriptGraph extends LitElement {
const paths = Object.keys(this.trackedNodes);
const manual_triggered = this.trace && "trigger" in this.trace.trace;
let track_path = manual_triggered ? undefined : [0];
const trigger_nodes =
"trigger" in this.trace.config
? ensureArray(this.trace.config.trigger).map((trigger, i) => {
if (this.trace && `trigger/${i}` in this.trace.trace) {
track_path = [i];
}
return this.render_trigger(trigger, i);
})
: undefined;
const trigger_nodes = ensureArray(this.trace.config.trigger).map(
(trigger, i) => {
if (this.trace && `trigger/${i}` in this.trace.trace) {
track_path = [i];
}
return this.render_trigger(trigger, i);
}
);
try {
return html`
<hat-graph class="parent">
<div></div>
${trigger_nodes
? html`<hat-graph
branching
id="trigger"
.short=${trigger_nodes.length < 2}
.track_start=${track_path}
.track_end=${track_path}
>
${trigger_nodes}
</hat-graph>`
: ""}
${"condition" in this.trace.config
? html`<hat-graph id="condition">
${ensureArray(
this.trace.config.condition
)?.map((condition, i) => this.render_condition(condition!, i))}
</hat-graph>`
: ""}
${"action" in this.trace.config
? html`${ensureArray(this.trace.config.action).map((action, i) =>
this.render_node(action, `action/${i}`)
)}`
: ""}
${"sequence" in this.trace.config
? html`${ensureArray(this.trace.config.sequence).map((action, i) =>
this.render_node(action, `sequence/${i}`, i === 0)
)}`
: ""}
<hat-graph
branching
id="trigger"
.short=${trigger_nodes.length < 2}
.track_start=${track_path}
.track_end=${track_path}
>
${trigger_nodes}
</hat-graph>
<hat-graph id="condition">
${ensureArray(this.trace.config.condition)?.map((condition, i) =>
this.render_condition(condition!, i)
)}
</hat-graph>
${ensureArray(this.trace.config.action).map((action, i) =>
this.render_node(action, `action/${i}`)
)}
</hat-graph>
<div class="actions">
<mwc-icon-button
@@ -613,7 +564,6 @@ class HatScriptGraph extends LitElement {
}
.parent {
margin-left: 8px;
margin-top: 16px;
}
.error {
padding: 16px;

View File

@@ -51,18 +51,7 @@ export interface ForDict {
seconds?: number | string;
}
export interface ContextConstraint {
context_id?: string;
parent_id?: string;
user_id?: string | string[];
}
export interface BaseTrigger {
platform: string;
id?: string;
}
export interface StateTrigger extends BaseTrigger {
export interface StateTrigger {
platform: "state";
entity_id: string;
attribute?: string;
@@ -71,25 +60,25 @@ export interface StateTrigger extends BaseTrigger {
for?: string | number | ForDict;
}
export interface MqttTrigger extends BaseTrigger {
export interface MqttTrigger {
platform: "mqtt";
topic: string;
payload?: string;
}
export interface GeoLocationTrigger extends BaseTrigger {
export interface GeoLocationTrigger {
platform: "geo_location";
source: string;
zone: string;
event: "enter" | "leave";
}
export interface HassTrigger extends BaseTrigger {
export interface HassTrigger {
platform: "homeassistant";
event: "start" | "shutdown";
}
export interface NumericStateTrigger extends BaseTrigger {
export interface NumericStateTrigger {
platform: "numeric_state";
entity_id: string;
attribute?: string;
@@ -99,48 +88,54 @@ export interface NumericStateTrigger extends BaseTrigger {
for?: string | number | ForDict;
}
export interface SunTrigger extends BaseTrigger {
export interface SunTrigger {
platform: "sun";
offset: number;
event: "sunrise" | "sunset";
}
export interface TimePatternTrigger extends BaseTrigger {
export interface TimePatternTrigger {
platform: "time_pattern";
hours?: number | string;
minutes?: number | string;
seconds?: number | string;
}
export interface WebhookTrigger extends BaseTrigger {
export interface WebhookTrigger {
platform: "webhook";
webhook_id: string;
}
export interface ZoneTrigger extends BaseTrigger {
export interface ZoneTrigger {
platform: "zone";
entity_id: string;
zone: string;
event: "enter" | "leave";
}
export interface TagTrigger extends BaseTrigger {
export interface TagTrigger {
platform: "tag";
tag_id: string;
device_id?: string;
}
export interface TimeTrigger extends BaseTrigger {
export interface TimeTrigger {
platform: "time";
at: string;
}
export interface TemplateTrigger extends BaseTrigger {
export interface TemplateTrigger {
platform: "template";
value_template: string;
}
export interface EventTrigger extends BaseTrigger {
export interface ContextConstraint {
context_id?: string;
parent_id?: string;
user_id?: string | string[];
}
export interface EventTrigger {
platform: "event";
event_type: string;
event_data?: any;
@@ -163,26 +158,24 @@ export type Trigger =
| EventTrigger
| DeviceTrigger;
interface BaseCondition {
condition: string;
alias?: string;
}
export interface LogicalCondition extends BaseCondition {
export interface LogicalCondition {
condition: "and" | "not" | "or";
alias?: string;
conditions: Condition | Condition[];
}
export interface StateCondition extends BaseCondition {
export interface StateCondition {
condition: "state";
alias?: string;
entity_id: string;
attribute?: string;
state: string | number;
for?: string | number | ForDict;
}
export interface NumericStateCondition extends BaseCondition {
export interface NumericStateCondition {
condition: "numeric_state";
alias?: string;
entity_id: string;
attribute?: string;
above?: number;
@@ -190,37 +183,36 @@ export interface NumericStateCondition extends BaseCondition {
value_template?: string;
}
export interface SunCondition extends BaseCondition {
export interface SunCondition {
condition: "sun";
alias?: string;
after_offset: number;
before_offset: number;
after: "sunrise" | "sunset";
before: "sunrise" | "sunset";
}
export interface ZoneCondition extends BaseCondition {
export interface ZoneCondition {
condition: "zone";
alias?: string;
entity_id: string;
zone: string;
}
export interface TimeCondition extends BaseCondition {
export interface TimeCondition {
condition: "time";
alias?: string;
after?: string;
before?: string;
weekday?: string | string[];
}
export interface TemplateCondition extends BaseCondition {
export interface TemplateCondition {
condition: "template";
alias?: string;
value_template: string;
}
export interface TriggerCondition extends BaseCondition {
condition: "trigger";
id: string;
}
export type Condition =
| StateCondition
| NumericStateCondition
@@ -229,8 +221,7 @@ export type Condition =
| TimeCondition
| TemplateCondition
| DeviceCondition
| LogicalCondition
| TriggerCondition;
| LogicalCondition;
export const triggerAutomationActions = (
hass: HomeAssistant,

View File

@@ -27,12 +27,6 @@ export type ConfigEntryMutableParams = Partial<
>
>;
export const ERROR_STATES: ConfigEntry["state"][] = [
"migration_error",
"setup_error",
"setup_retry",
];
export const getConfigEntries = (hass: HomeAssistant) =>
hass.callApi<ConfigEntry[]>("GET", "config/config_entries/entry");

View File

@@ -1,7 +1,6 @@
import { computeStateName } from "../common/entity/compute_state_name";
import { HaFormSchema } from "../components/ha-form/ha-form";
import { HomeAssistant } from "../types";
import { BaseTrigger } from "./automation";
export interface DeviceAutomation {
alias?: string;
@@ -21,10 +20,9 @@ export interface DeviceCondition extends DeviceAutomation {
condition: "device";
}
export type DeviceTrigger = DeviceAutomation &
BaseTrigger & {
platform: "device";
};
export interface DeviceTrigger extends DeviceAutomation {
platform: "device";
}
export interface DeviceCapabilities {
extra_fields: HaFormSchema[];

View File

@@ -8,7 +8,6 @@ export enum LightColorModes {
ONOFF = "onoff",
BRIGHTNESS = "brightness",
COLOR_TEMP = "color_temp",
WHITE = "white",
HS = "hs",
XY = "xy",
RGB = "rgb",

View File

@@ -7,7 +7,6 @@ import { computeObjectId } from "../common/entity/compute_object_id";
import { navigate } from "../common/navigate";
import { HomeAssistant } from "../types";
import { Condition, Trigger } from "./automation";
import { BlueprintInput } from "./blueprint";
export const MODES = ["single", "restart", "queued", "parallel"] as const;
export const MODES_MAX = ["queued", "parallel"];
@@ -29,10 +28,6 @@ export interface ScriptConfig {
max?: number;
}
export interface BlueprintScriptConfig extends ScriptConfig {
use_blueprint: { path: string; input?: BlueprintInput };
}
export interface EventAction {
alias?: string;
event: string;

View File

@@ -1,25 +0,0 @@
import {
HassEntityAttributeBase,
HassEntityBase,
} from "home-assistant-js-websocket";
import { HomeAssistant } from "../types";
interface SelectEntityAttributes extends HassEntityAttributeBase {
options: string[];
}
export interface SelectEntity extends HassEntityBase {
attributes: SelectEntityAttributes;
}
export const setSelectOption = (
hass: HomeAssistant,
entity: string,
option: string
) =>
hass.callService(
"select",
"select_option",
{ option },
{ entity_id: entity }
);

View File

@@ -2,6 +2,7 @@ import { Connection, getCollection } from "home-assistant-js-websocket";
import { Store } from "home-assistant-js-websocket/dist/store";
import { LocalizeFunc } from "../../common/translations/localize";
import { HomeAssistant } from "../../types";
import { fetchFrontendUserData, saveFrontendUserData } from "../frontend";
import { HassioAddonsInfo } from "../hassio/addon";
import { HassioHassOSInfo, HassioHostInfo } from "../hassio/host";
import { NetworkInfo } from "../hassio/network";
@@ -13,6 +14,28 @@ import {
} from "../hassio/supervisor";
import { SupervisorStore } from "./store";
export interface SupervisorFrontendPrefrences {
snapshot_before_update: Record<string, boolean>;
}
declare global {
interface FrontendUserData {
supervisor: SupervisorFrontendPrefrences;
}
}
export const fetchSupervisorFrontendPreferences = async (
hass: HomeAssistant
): Promise<SupervisorFrontendPrefrences> => {
const stored = await fetchFrontendUserData(hass.connection, "supervisor");
return stored || { snapshot_before_update: {} };
};
export const saveSupervisorFrontendPreferences = (
hass: HomeAssistant,
data: SupervisorFrontendPrefrences
) => saveFrontendUserData(hass.connection, "supervisor", data);
export const supervisorWSbaseCommand = {
type: "supervisor/api",
method: "GET",

View File

@@ -4,7 +4,6 @@ import {
BlueprintAutomationConfig,
ManualAutomationConfig,
} from "./automation";
import { BlueprintScriptConfig, ScriptConfig } from "./script";
interface BaseTraceStep {
path: string;
@@ -55,7 +54,7 @@ export type ActionTraceStep =
| ChooseActionTraceStep
| ChooseChoiceActionTraceStep;
interface BaseTrace {
export interface AutomationTrace {
domain: string;
item_id: string;
last_step: string | null;
@@ -82,46 +81,23 @@ interface BaseTrace {
// The exception is in the trace itself or in the last element of the trace
// Script execution stopped by async_stop called on the script run because home assistant is shutting down, script mode is SCRIPT_MODE_RESTART etc:
| "cancelled";
}
interface BaseTraceExtended {
trace: Record<string, ActionTraceStep[]>;
context: Context;
error?: string;
}
export interface AutomationTrace extends BaseTrace {
domain: "automation";
// Automation only, should become it's own type when we support script in frontend
trigger: string;
}
export interface AutomationTraceExtended
extends AutomationTrace,
BaseTraceExtended {
export interface AutomationTraceExtended extends AutomationTrace {
trace: Record<string, ActionTraceStep[]>;
context: Context;
config: ManualAutomationConfig;
blueprint_inputs?: BlueprintAutomationConfig;
error?: string;
}
export interface ScriptTrace extends BaseTrace {
domain: "script";
}
export interface ScriptTraceExtended extends ScriptTrace, BaseTraceExtended {
config: ScriptConfig;
blueprint_inputs?: BlueprintScriptConfig;
}
export type TraceExtended = AutomationTraceExtended | ScriptTraceExtended;
interface TraceTypes {
automation: {
short: AutomationTrace;
extended: AutomationTraceExtended;
};
script: {
short: ScriptTrace;
extended: ScriptTraceExtended;
};
}
export const loadTrace = <T extends keyof TraceTypes>(
@@ -165,7 +141,7 @@ export const loadTraceContexts = (
});
export const getDataFromPath = (
config: TraceExtended["config"],
config: ManualAutomationConfig,
path: string
): any => {
const parts = path.split("/").reverse();

View File

@@ -21,7 +21,6 @@ export interface ZWaveJSClient {
export interface ZWaveJSController {
home_id: string;
nodes: number[];
is_heal_network_active: boolean;
}
export interface ZWaveJSNode {
@@ -78,11 +77,6 @@ export interface ZWaveJSRefreshNodeStatusMessage {
stage?: string;
}
export interface ZWaveJSHealNetworkStatusMessage {
event: string;
heal_node_status: { [key: number]: string };
}
export enum NodeStatus {
Unknown,
Asleep,
@@ -178,37 +172,6 @@ export const reinterviewNode = (
}
);
export const healNetwork = (
hass: HomeAssistant,
entry_id: string
): Promise<UnsubscribeFunc> =>
hass.callWS({
type: "zwave_js/begin_healing_network",
entry_id: entry_id,
});
export const stopHealNetwork = (
hass: HomeAssistant,
entry_id: string
): Promise<UnsubscribeFunc> =>
hass.callWS({
type: "zwave_js/stop_healing_network",
entry_id: entry_id,
});
export const subscribeHealNetworkProgress = (
hass: HomeAssistant,
entry_id: string,
callbackFunction: (message: ZWaveJSHealNetworkStatusMessage) => void
): Promise<UnsubscribeFunc> =>
hass.connection.subscribeMessage(
(message: any) => callbackFunction(message),
{
type: "zwave_js/subscribe_heal_network_progress",
entry_id: entry_id,
}
);
export const getIdentifiersFromDevice = (
device: DeviceRegistryEntry
): ZWaveJSNodeIdentifiers | undefined => {
@@ -230,18 +193,6 @@ export const getIdentifiersFromDevice = (
};
};
export type ZWaveJSLogUpdate = ZWaveJSLogMessageUpdate | ZWaveJSLogConfigUpdate;
interface ZWaveJSLogMessageUpdate {
type: "log_message";
log_message: ZWaveJSLogMessage;
}
interface ZWaveJSLogConfigUpdate {
type: "log_config";
log_config: ZWaveJSLogConfig;
}
export interface ZWaveJSLogMessage {
timestamp: string;
level: string;
@@ -252,10 +203,10 @@ export interface ZWaveJSLogMessage {
export const subscribeZWaveJSLogs = (
hass: HomeAssistant,
entry_id: string,
callback: (update: ZWaveJSLogUpdate) => void
callback: (message: ZWaveJSLogMessage) => void
) =>
hass.connection.subscribeMessage<ZWaveJSLogUpdate>(callback, {
type: "zwave_js/subscribe_log_updates",
hass.connection.subscribeMessage<ZWaveJSLogMessage>(callback, {
type: "zwave_js/subscribe_logs",
entry_id,
});

View File

@@ -232,6 +232,7 @@ class DataEntryFlowDialog extends LitElement {
<step-flow-pick-handler
.hass=${this.hass}
.handlers=${this._handlers}
.showAdvanced=${this._params.showAdvanced}
@handler-picked=${this._handlerPicked}
></step-flow-pick-handler>
`

View File

@@ -90,10 +90,7 @@ export const showConfigFlowDialog = (
},
renderShowFormStepFieldError(hass, step, error) {
return hass.localize(
`component.${step.handler}.config.error.${error}`,
step.description_placeholders
);
return hass.localize(`component.${step.handler}.config.error.${error}`);
},
renderExternalStepHeader(hass, step) {

View File

@@ -88,10 +88,9 @@ export const showOptionsFlowDialog = (
);
},
renderShowFormStepFieldError(hass, step, error) {
renderShowFormStepFieldError(hass, _step, error) {
return hass.localize(
`component.${configEntry.domain}.options.error.${error}`,
step.description_placeholders
`component.${configEntry.domain}.options.error.${error}`
);
},

View File

@@ -3,6 +3,7 @@ import "@polymer/paper-item/paper-item-body";
import Fuse from "fuse.js";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { fireEvent } from "../../common/dom/fire_event";
@@ -33,7 +34,9 @@ declare global {
class StepFlowPickHandler extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public handlers!: string[];
@property() public handlers!: string[];
@property() public showAdvanced?: boolean;
@state() private _filter?: string;
@@ -84,50 +87,47 @@ class StepFlowPickHandler extends LitElement {
width: `${this._width}px`,
height: `${this._height}px`,
})}
class=${classMap({ advanced: Boolean(this.showAdvanced) })}
>
${handlers.length
? handlers.map(
(handler: HandlerObj) =>
html`
<paper-icon-item
@click=${this._handlerPicked}
.handler=${handler}
>
<img
slot="item-icon"
loading="lazy"
src=${brandsUrl(handler.slug, "icon", true)}
referrerpolicy="no-referrer"
/>
${handlers.map(
(handler: HandlerObj) =>
html`
<paper-icon-item
@click=${this._handlerPicked}
.handler=${handler}
>
<img
slot="item-icon"
loading="lazy"
src=${brandsUrl(handler.slug, "icon", true)}
referrerpolicy="no-referrer"
/>
<paper-item-body> ${handler.name} </paper-item-body>
<ha-icon-next></ha-icon-next>
</paper-icon-item>
`
)
: html`
<p>
${this.hass.localize(
"ui.panel.config.integrations.note_about_integrations"
)}<br />
${this.hass.localize(
"ui.panel.config.integrations.note_about_website_reference"
)}<a
href="${documentationUrl(
this.hass,
`/integrations/${
this._filter ? `#search/${this._filter}` : ""
}`
)}"
target="_blank"
rel="noreferrer"
>${this.hass.localize(
"ui.panel.config.integrations.home_assistant_website"
)}</a
>.
</p>
`}
<paper-item-body> ${handler.name} </paper-item-body>
<ha-icon-next></ha-icon-next>
</paper-icon-item>
`
)}
</div>
${this.showAdvanced
? html`
<p>
${this.hass.localize(
"ui.panel.config.integrations.note_about_integrations"
)}<br />
${this.hass.localize(
"ui.panel.config.integrations.note_about_website_reference"
)}<a
href="${documentationUrl(this.hass, "/integrations/")}"
target="_blank"
rel="noreferrer"
>${this.hass.localize(
"ui.panel.config.integrations.home_assistant_website"
)}</a
>.
</p>
`
: ""}
`;
}
@@ -193,6 +193,9 @@ class StepFlowPickHandler extends LitElement {
div {
max-height: calc(100vh - 134px);
}
div.advanced {
max-height: calc(100vh - 250px);
}
}
paper-icon-item {
cursor: pointer;

View File

@@ -9,7 +9,6 @@ import {
TemplateResult,
} from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { supportsFeature } from "../../../common/entity/supports-feature";
import "../../../components/ha-attributes";
import "../../../components/ha-button-toggle-group";
@@ -29,6 +28,11 @@ import {
} from "../../../data/light";
import type { HomeAssistant } from "../../../types";
const toggleButtons = [
{ label: "Color", value: "color" },
{ label: "Temperature", value: LightColorModes.COLOR_TEMP },
];
@customElement("more-info-light")
class MoreInfoLight extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@@ -55,7 +59,7 @@ class MoreInfoLight extends LitElement {
@state() private _colorPickerColor?: [number, number, number];
@state() private _mode?: "color" | LightColorModes;
@state() private _mode?: "color" | LightColorModes.COLOR_TEMP;
protected render(): TemplateResult {
if (!this.hass || !this.stateObj) {
@@ -67,11 +71,6 @@ class MoreInfoLight extends LitElement {
LightColorModes.COLOR_TEMP
);
const supportsWhite = lightSupportsColorMode(
this.stateObj,
LightColorModes.WHITE
);
const supportsRgbww = lightSupportsColorMode(
this.stateObj,
LightColorModes.RGBWW
@@ -102,17 +101,16 @@ class MoreInfoLight extends LitElement {
${this.stateObj.state === "on"
? html`
${supportsTemp || supportsColor ? html`<hr />` : ""}
${supportsColor && (supportsTemp || supportsWhite)
${supportsTemp && supportsColor
? html`<ha-button-toggle-group
fullWidth
.buttons=${this._toggleButtons(supportsTemp, supportsWhite)}
.buttons=${toggleButtons}
.active=${this._mode}
@value-changed=${this._modeChanged}
></ha-button-toggle-group>`
: ""}
${supportsTemp &&
((!supportsColor && !supportsWhite) ||
this._mode === LightColorModes.COLOR_TEMP)
(!supportsColor || this._mode === LightColorModes.COLOR_TEMP)
? html`
<ha-labeled-slider
class="color_temp"
@@ -128,8 +126,7 @@ class MoreInfoLight extends LitElement {
></ha-labeled-slider>
`
: ""}
${supportsColor &&
((!supportsTemp && !supportsWhite) || this._mode === "color")
${supportsColor && (!supportsTemp || this._mode === "color")
? html`
<div class="segmentationContainer">
<ha-color-picker
@@ -254,7 +251,7 @@ class MoreInfoLight extends LitElement {
) {
this._mode = lightIsInColorMode(this.stateObj!)
? "color"
: this.stateObj!.attributes.color_mode;
: LightColorModes.COLOR_TEMP;
}
let brightnessAdjust = 100;
@@ -303,19 +300,6 @@ class MoreInfoLight extends LitElement {
}
}
private _toggleButtons = memoizeOne(
(supportsTemp: boolean, supportsWhite: boolean) => {
const modes = [{ label: "Color", value: "color" }];
if (supportsTemp) {
modes.push({ label: "Temperature", value: LightColorModes.COLOR_TEMP });
}
if (supportsWhite) {
modes.push({ label: "White", value: LightColorModes.WHITE });
}
return modes;
}
);
private _modeChanged(ev: CustomEvent) {
this._mode = ev.detail.value;
}
@@ -342,14 +326,6 @@ class MoreInfoLight extends LitElement {
this._brightnessSliderValue = bri;
if (this._mode === LightColorModes.WHITE) {
this.hass.callService("light", "turn_on", {
entity_id: this.stateObj!.entity_id,
white: Math.min(255, Math.round((bri * 255) / 100)),
});
return;
}
if (this._brightnessAdjusted) {
const rgb =
this.stateObj!.attributes.rgb_color ||

View File

@@ -2,7 +2,7 @@ import { html, LitElement, PropertyValues, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import { isComponentLoaded } from "../../common/config/is_component_loaded";
import { throttle } from "../../common/util/throttle";
import "../../components/chart/state-history-charts";
import "../../components/state-history-charts";
import { getRecentWithCache } from "../../data/cached-history";
import { HistoryResult } from "../../data/history";
import { HomeAssistant } from "../../types";

View File

@@ -4,6 +4,7 @@ import { isComponentLoaded } from "../../common/config/is_component_loaded";
import { computeStateDomain } from "../../common/entity/compute_state_domain";
import { throttle } from "../../common/util/throttle";
import "../../components/ha-circular-progress";
import "../../components/state-history-charts";
import { fetchUsers } from "../../data/user";
import { getLogbookData, LogbookEntry } from "../../data/logbook";
import { loadTraceContexts, TraceContexts } from "../../data/trace";
@@ -28,8 +29,6 @@ export class MoreInfoLogbook extends LitElement {
private _fetchUserPromise?: Promise<void>;
private _error?: string;
private _throttleGetLogbookEntries = throttle(() => {
this._getLogBookData();
}, 10000);
@@ -46,13 +45,7 @@ export class MoreInfoLogbook extends LitElement {
return html`
${isComponentLoaded(this.hass, "logbook")
? this._error
? html`<div class="no-entries">
${`${this.hass.localize(
"ui.components.logbook.retrieval_error"
)}: ${this._error}`}
</div>`
: !this._logbookEntries
? !this._logbookEntries
? html`
<ha-circular-progress
active
@@ -126,25 +119,17 @@ export class MoreInfoLogbook extends LitElement {
this._lastLogbookDate ||
new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
const now = new Date();
let newEntries;
let traceContexts;
try {
[newEntries, traceContexts] = await Promise.all([
getLogbookData(
this.hass,
lastDate.toISOString(),
now.toISOString(),
this.entityId,
true
),
this.hass.user?.is_admin ? loadTraceContexts(this.hass) : {},
this._fetchUserPromise,
]);
} catch (err) {
this._error = err.message;
}
const [newEntries, traceContexts] = await Promise.all([
getLogbookData(
this.hass,
lastDate.toISOString(),
now.toISOString(),
this.entityId,
true
),
loadTraceContexts(this.hass),
this._fetchUserPromise,
]);
this._logbookEntries = this._logbookEntries
? [...newEntries, ...this._logbookEntries]
: newEntries;

View File

@@ -20,5 +20,4 @@
"content" in document.createElement("template"))) {
document.write("<script src='/static/polyfills/webcomponents-bundle.js'><"+"/script>");
}
var isS11_12 = /.*Version\/(?:11|12)(?:\.\d+)*.*Safari\//.test(navigator.userAgent);
</script>

View File

@@ -43,16 +43,13 @@
<%= renderTemplate('_preload_roboto') %>
<script crossorigin="use-credentials">
// Safari 12 and below does not have a compliant ES2015 implementation of template literals, so we ship ES5
if (!isS11_12) {
import("<%= latestPageJS %>");
window.latestJS = true;
window.providersPromise = fetch("/auth/providers", {
credentials: "same-origin",
});
if (!window.globalThis) {
window.globalThis = window;
}
import("<%= latestPageJS %>");
window.latestJS = true;
window.providersPromise = fetch("/auth/providers", {
credentials: "same-origin",
});
if (!window.globalThis) {
window.globalThis = window;
}
</script>

View File

@@ -67,15 +67,12 @@
<%= renderTemplate('_preload_roboto') %>
<script <% if (!useWDS) { %>crossorigin="use-credentials"<% } %>>
// Safari 12 and below does not have a compliant ES2015 implementation of template literals, so we ship ES5
if (!isS11_12) {
import("<%= latestCoreJS %>");
import("<%= latestAppJS %>");
window.customPanelJS = "<%= latestCustomPanelJS %>";
window.latestJS = true;
if (!window.globalThis) {
window.globalThis = window;
}
import("<%= latestCoreJS %>");
import("<%= latestAppJS %>");
window.customPanelJS = "<%= latestCustomPanelJS %>";
window.latestJS = true;
if (!window.globalThis) {
window.globalThis = window;
}
</script>
<script>

View File

@@ -75,16 +75,13 @@
<%= renderTemplate('_preload_roboto') %>
<script crossorigin="use-credentials">
// Safari 12 and below does not have a compliant ES2015 implementation of template literals, so we ship ES5
if (!isS11_12) {
import("<%= latestPageJS %>");
window.latestJS = true;
window.stepsPromise = fetch("/api/onboarding", {
credentials: "same-origin",
});
if (!window.globalThis) {
window.globalThis = window;
}
import("<%= latestPageJS %>");
window.latestJS = true;
window.stepsPromise = fetch("/api/onboarding", {
credentials: "same-origin",
});
if (!window.globalThis) {
window.globalThis = window;
}
</script>

View File

@@ -43,7 +43,7 @@ const COMPONENTS = {
class PartialPanelResolver extends HassRouterPage {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean }) public narrow?: boolean;
@property() public narrow?: boolean;
private _waitForStart = false;
@@ -206,7 +206,7 @@ class PartialPanelResolver extends HassRouterPage {
this._currentPage &&
!this.hass.panels[this._currentPage]
) {
if (this.hass.config.state === STATE_NOT_RUNNING) {
if (this.hass.config.state !== STATE_NOT_RUNNING) {
this._waitForStart = true;
if (this.lastChild) {
this.removeChild(this.lastChild);

View File

@@ -20,7 +20,6 @@ import "./types/ha-automation-condition-state";
import "./types/ha-automation-condition-sun";
import "./types/ha-automation-condition-template";
import "./types/ha-automation-condition-time";
import "./types/ha-automation-condition-trigger";
import "./types/ha-automation-condition-zone";
const OPTIONS = [
@@ -33,7 +32,6 @@ const OPTIONS = [
"sun",
"template",
"time",
"trigger",
"zone",
];

View File

@@ -1,99 +0,0 @@
import { html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../../common/dom/fire_event";
import {
AutomationConfig,
Trigger,
TriggerCondition,
} from "../../../../../data/automation";
import { HomeAssistant } from "../../../../../types";
import "@polymer/paper-dropdown-menu/paper-dropdown-menu-light";
import { ensureArray } from "../../../../../common/ensure-array";
import { UnsubscribeFunc } from "home-assistant-js-websocket";
@customElement("ha-automation-condition-trigger")
export class HaTriggerCondition extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public condition!: TriggerCondition;
@state() private _triggers?: Trigger | Trigger[];
private _unsub?: UnsubscribeFunc;
public static get defaultConfig() {
return {
id: "",
};
}
connectedCallback() {
super.connectedCallback();
const details = { callback: (config) => this._automationUpdated(config) };
fireEvent(this, "subscribe-automation-config", details);
this._unsub = (details as any).unsub;
}
disconnectedCallback() {
super.disconnectedCallback();
if (this._unsub) {
this._unsub();
}
}
protected render() {
const { id } = this.condition;
if (!this._triggers) {
return this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.no_triggers"
);
}
return html`<paper-dropdown-menu-light
.label=${this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.id"
)}
no-animations
>
<paper-listbox
slot="dropdown-content"
.selected=${id}
attr-for-selected="data-trigger-id"
@selected-item-changed=${this._triggerPicked}
>
${ensureArray(this._triggers).map((trigger) =>
trigger.id
? html`
<paper-item data-trigger-id=${trigger.id}>
${trigger.id}
</paper-item>
`
: ""
)}
</paper-listbox>
</paper-dropdown-menu-light>`;
}
private _automationUpdated(config?: AutomationConfig) {
this._triggers = config?.trigger;
}
private _triggerPicked(ev: CustomEvent) {
ev.stopPropagation();
if (!ev.detail.value) {
return;
}
const newTrigger = ev.detail.value.dataset.triggerId;
if (this.condition.id === newTrigger) {
return;
}
fireEvent(this, "value-changed", {
value: { ...this.condition, id: newTrigger },
});
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-automation-condition-trigger": HaTriggerCondition;
}
}

View File

@@ -1,3 +1,4 @@
import "@polymer/paper-radio-button/paper-radio-button";
import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import { fireEvent } from "../../../../../common/dom/fire_event";

View File

@@ -11,7 +11,6 @@ import "@polymer/app-layout/app-header/app-header";
import "@polymer/app-layout/app-toolbar/app-toolbar";
import "@polymer/paper-dropdown-menu/paper-dropdown-menu-light";
import "@polymer/paper-input/paper-textarea";
import { UnsubscribeFunc } from "home-assistant-js-websocket";
import {
css,
CSSResultGroup,
@@ -52,9 +51,12 @@ import { HomeAssistant, Route } from "../../../types";
import { showToast } from "../../../util/toast";
import "../ha-config-section";
import { configSections } from "../ha-panel-config";
import "./action/ha-automation-action";
import { HaDeviceAction } from "./action/types/ha-automation-action-device_id";
import "./blueprint-automation-editor";
import "./condition/ha-automation-condition";
import "./manual-automation-editor";
import "./trigger/ha-automation-trigger";
import { HaDeviceTrigger } from "./trigger/types/ha-automation-trigger-device";
declare global {
@@ -63,10 +65,6 @@ declare global {
}
// for fire event
interface HASSDomEvents {
"subscribe-automation-config": {
callback: (config: AutomationConfig) => void;
unsub?: UnsubscribeFunc;
};
"ui-mode-not-available": Error;
duplicate: undefined;
}
@@ -97,13 +95,6 @@ export class HaAutomationEditor extends KeyboardShortcutMixin(LitElement) {
@query("ha-yaml-editor", true) private _editor?: HaYamlEditor;
private _configSubscriptions: Record<
string,
(config?: AutomationConfig) => void
> = {};
private _configSubscriptionsId = 1;
protected render(): TemplateResult {
const stateObj = this._entityId
? this.hass.states[this._entityId]
@@ -209,7 +200,6 @@ export class HaAutomationEditor extends KeyboardShortcutMixin(LitElement) {
class="content ${classMap({
"yaml-mode": this._mode === "yaml",
})}"
@subscribe-automation-config=${this._subscribeAutomationConfig}
>
${this._errors
? html` <div class="errors">${this._errors}</div> `
@@ -346,12 +336,6 @@ export class HaAutomationEditor extends KeyboardShortcutMixin(LitElement) {
) {
this._setEntityId();
}
if (changedProps.has("_config")) {
Object.values(this._configSubscriptions).forEach((sub) =>
sub(this._config)
);
}
}
private _setEntityId() {
@@ -532,15 +516,6 @@ export class HaAutomationEditor extends KeyboardShortcutMixin(LitElement) {
);
}
private _subscribeAutomationConfig(ev) {
const id = this._configSubscriptionsId++;
this._configSubscriptions[id] = ev.detail.callback;
ev.detail.unsub = () => {
delete this._configSubscriptions[id];
};
ev.detail.callback(this._config);
}
protected handleKeyboardSave() {
this._saveAutomation();
}

View File

@@ -51,7 +51,7 @@ class HaConfigAutomation extends HassRouterPage {
},
trace: {
tag: "ha-automation-trace",
load: () => import("./ha-automation-trace"),
load: () => import("./trace/ha-automation-trace"),
},
},
};

View File

@@ -1,16 +1,16 @@
import { dump } from "js-yaml";
import { html, LitElement, TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
import "../ha-code-editor";
import "../ha-icon-button";
import { TraceExtended } from "../../data/trace";
import { HomeAssistant } from "../../types";
import "../../../../components/ha-code-editor";
import "../../../../components/ha-icon-button";
import { AutomationTraceExtended } from "../../../../data/trace";
import { HomeAssistant } from "../../../../types";
@customElement("ha-trace-blueprint-config")
export class HaTraceBlueprintConfig extends LitElement {
@customElement("ha-automation-trace-blueprint-config")
export class HaAutomationTraceBlueprintConfig extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trace!: TraceExtended;
@property() public trace!: AutomationTraceExtended;
protected render(): TemplateResult {
return html`
@@ -24,6 +24,6 @@ export class HaTraceBlueprintConfig extends LitElement {
declare global {
interface HTMLElementTagNameMap {
"ha-trace-blueprint-config": HaTraceBlueprintConfig;
"ha-automation-trace-blueprint-config": HaAutomationTraceBlueprintConfig;
}
}

View File

@@ -1,16 +1,16 @@
import { dump } from "js-yaml";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
import "../ha-code-editor";
import "../ha-icon-button";
import { TraceExtended } from "../../data/trace";
import { HomeAssistant } from "../../types";
import "../../../../components/ha-code-editor";
import "../../../../components/ha-icon-button";
import { AutomationTraceExtended } from "../../../../data/trace";
import { HomeAssistant } from "../../../../types";
@customElement("ha-trace-config")
export class HaTraceConfig extends LitElement {
@customElement("ha-automation-trace-config")
export class HaAutomationTraceConfig extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trace!: TraceExtended;
@property() public trace!: AutomationTraceExtended;
protected render(): TemplateResult {
return html`
@@ -28,6 +28,6 @@ export class HaTraceConfig extends LitElement {
declare global {
interface HTMLElementTagNameMap {
"ha-trace-config": HaTraceConfig;
"ha-automation-trace-config": HaAutomationTraceConfig;
}
}

View File

@@ -1,19 +1,16 @@
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
import { LogbookEntry } from "../../data/logbook";
import { HomeAssistant } from "../../types";
import "./hat-logbook-note";
import "../../panels/logbook/ha-logbook";
import { TraceExtended } from "../../data/trace";
import "../../../../components/trace/hat-logbook-note";
import type { LogbookEntry } from "../../../../data/logbook";
import type { HomeAssistant } from "../../../../types";
import "../../../logbook/ha-logbook";
@customElement("ha-trace-logbook")
export class HaTraceLogbook extends LitElement {
@customElement("ha-automation-trace-logbook")
export class HaAutomationTraceLogbook extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean, reflect: true }) public narrow!: boolean;
@property({ attribute: false }) public trace!: TraceExtended;
@property({ attribute: false }) public logbookEntries!: LogbookEntry[];
protected render(): TemplateResult {
@@ -25,7 +22,7 @@ export class HaTraceLogbook extends LitElement {
.entries=${this.logbookEntries}
.narrow=${this.narrow}
></ha-logbook>
<hat-logbook-note .domain=${this.trace.domain}></hat-logbook-note>
<hat-logbook-note></hat-logbook-note>
`
: html`<div class="padded-box">
No Logbook entries found for this step.
@@ -45,6 +42,6 @@ export class HaTraceLogbook extends LitElement {
declare global {
interface HTMLElementTagNameMap {
"ha-trace-logbook": HaTraceLogbook;
"ha-automation-trace-logbook": HaAutomationTraceLogbook;
}
}

View File

@@ -2,33 +2,33 @@ import { dump } from "js-yaml";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { formatDateTimeWithSeconds } from "../../common/datetime/format_date_time";
import "../ha-code-editor";
import "../ha-icon-button";
import type { NodeInfo } from "./hat-graph";
import "./hat-logbook-note";
import { LogbookEntry } from "../../data/logbook";
import { formatDateTimeWithSeconds } from "../../../../common/datetime/format_date_time";
import "../../../../components/ha-code-editor";
import "../../../../components/ha-icon-button";
import type { NodeInfo } from "../../../../components/trace/hat-graph";
import "../../../../components/trace/hat-logbook-note";
import { LogbookEntry } from "../../../../data/logbook";
import {
ActionTraceStep,
AutomationTraceExtended,
ChooseActionTraceStep,
getDataFromPath,
TraceExtended,
} from "../../data/trace";
import "../../panels/logbook/ha-logbook";
import { traceTabStyles } from "./trace-tab-styles";
import { HomeAssistant } from "../../types";
} from "../../../../data/trace";
import { HomeAssistant } from "../../../../types";
import "../../../logbook/ha-logbook";
import { traceTabStyles } from "./styles";
@customElement("ha-trace-path-details")
export class HaTracePathDetails extends LitElement {
@customElement("ha-automation-trace-path-details")
export class HaAutomationTracePathDetails extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean, reflect: true }) public narrow!: boolean;
@property({ attribute: false }) public trace!: TraceExtended;
@property() private selected!: NodeInfo;
@property({ attribute: false }) public logbookEntries!: LogbookEntry[];
@property() public trace!: AutomationTraceExtended;
@property({ attribute: false }) public selected!: NodeInfo;
@property() public logbookEntries!: LogbookEntry[];
@property() renderedNodes: Record<string, any> = {};
@@ -230,7 +230,7 @@ export class HaTracePathDetails extends LitElement {
.entries=${entries}
.narrow=${this.narrow}
></ha-logbook>
<hat-logbook-note .domain=${this.trace.domain}></hat-logbook-note>
<hat-logbook-note></hat-logbook-note>
`
: html`<div class="padded-box">
No Logbook entries found for this step.
@@ -267,6 +267,6 @@ export class HaTracePathDetails extends LitElement {
declare global {
interface HTMLElementTagNameMap {
"ha-trace-path-details": HaTracePathDetails;
"ha-automation-trace-path-details": HaAutomationTracePathDetails;
}
}

View File

@@ -1,17 +1,17 @@
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
import type { NodeInfo } from "./hat-graph";
import "./hat-logbook-note";
import "./hat-trace-timeline";
import type { LogbookEntry } from "../../data/logbook";
import type { TraceExtended } from "../../data/trace";
import type { HomeAssistant } from "../../types";
import type { NodeInfo } from "../../../../components/trace/hat-graph";
import "../../../../components/trace/hat-logbook-note";
import "../../../../components/trace/hat-trace-timeline";
import type { LogbookEntry } from "../../../../data/logbook";
import type { AutomationTraceExtended } from "../../../../data/trace";
import type { HomeAssistant } from "../../../../types";
@customElement("ha-trace-timeline")
export class HaTraceTimeline extends LitElement {
@customElement("ha-automation-trace-timeline")
export class HaAutomationTraceTimeline extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trace!: TraceExtended;
@property({ attribute: false }) public trace!: AutomationTraceExtended;
@property({ attribute: false }) public logbookEntries!: LogbookEntry[];
@@ -27,7 +27,7 @@ export class HaTraceTimeline extends LitElement {
allowPick
>
</hat-trace-timeline>
<hat-logbook-note .domain=${this.trace.domain}></hat-logbook-note>
<hat-logbook-note></hat-logbook-note>
`;
}
@@ -45,6 +45,6 @@ export class HaTraceTimeline extends LitElement {
declare global {
interface HTMLElementTagNameMap {
"ha-trace-timeline": HaTraceTimeline;
"ha-automation-trace-timeline": HaAutomationTraceTimeline;
}
}

View File

@@ -9,28 +9,31 @@ import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { repeat } from "lit/directives/repeat";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import { formatDateTimeWithSeconds } from "../../../common/datetime/format_date_time";
import type { NodeInfo } from "../../../components/trace/hat-graph";
import "../../../components/trace/hat-script-graph";
import { AutomationEntity } from "../../../data/automation";
import { getLogbookDataForContext, LogbookEntry } from "../../../data/logbook";
import { isComponentLoaded } from "../../../../common/config/is_component_loaded";
import { formatDateTimeWithSeconds } from "../../../../common/datetime/format_date_time";
import type { NodeInfo } from "../../../../components/trace/hat-graph";
import "../../../../components/trace/hat-script-graph";
import { AutomationEntity } from "../../../../data/automation";
import {
getLogbookDataForContext,
LogbookEntry,
} from "../../../../data/logbook";
import {
AutomationTrace,
AutomationTraceExtended,
loadTrace,
loadTraces,
} from "../../../data/trace";
import { showAlertDialog } from "../../../dialogs/generic/show-dialog-box";
import { haStyle } from "../../../resources/styles";
import { HomeAssistant, Route } from "../../../types";
import { configSections } from "../ha-panel-config";
import "../../../components/trace/ha-trace-blueprint-config";
import "../../../components/trace/ha-trace-config";
import "../../../components/trace/ha-trace-logbook";
import "../../../components/trace/ha-trace-path-details";
import "../../../components/trace/ha-trace-timeline";
import { traceTabStyles } from "../../../components/trace/trace-tab-styles";
} from "../../../../data/trace";
import { showAlertDialog } from "../../../../dialogs/generic/show-dialog-box";
import { haStyle } from "../../../../resources/styles";
import { HomeAssistant, Route } from "../../../../types";
import { configSections } from "../../ha-panel-config";
import "./ha-automation-trace-blueprint-config";
import "./ha-automation-trace-config";
import "./ha-automation-trace-logbook";
import "./ha-automation-trace-path-details";
import "./ha-automation-trace-timeline";
import { traceTabStyles } from "./styles";
@customElement("ha-automation-trace")
export class HaAutomationTrace extends LitElement {
@@ -206,7 +209,7 @@ export class HaAutomationTrace extends LitElement {
@click=${this._showTab}
>
Blueprint Config
</button>
</div>
`
: ""}
</div>
@@ -216,47 +219,46 @@ export class HaAutomationTrace extends LitElement {
? ""
: this._view === "details"
? html`
<ha-trace-path-details
<ha-automation-trace-path-details
.hass=${this.hass}
.narrow=${this.narrow}
.trace=${this._trace}
.selected=${this._selected}
.logbookEntries=${this._logbookEntries}
.trackedNodes=${trackedNodes}
.renderedNodes=${renderedNodes!}
></ha-trace-path-details>
.renderedNodes=${renderedNodes}
></ha-automation-trace-path-details>
`
: this._view === "config"
? html`
<ha-trace-config
<ha-automation-trace-config
.hass=${this.hass}
.trace=${this._trace}
></ha-trace-config>
></ha-automation-trace-config>
`
: this._view === "logbook"
? html`
<ha-trace-logbook
<ha-automation-trace-logbook
.hass=${this.hass}
.narrow=${this.narrow}
.trace=${this._trace}
.logbookEntries=${this._logbookEntries}
></ha-trace-logbook>
></ha-automation-trace-logbook>
`
: this._view === "blueprint"
? html`
<ha-trace-blueprint-config
<ha-automation-trace-blueprint-config
.hass=${this.hass}
.trace=${this._trace}
></ha-trace-blueprint-config>
></ha-automation-trace-blueprint-config>
`
: html`
<ha-trace-timeline
<ha-automation-trace-timeline
.hass=${this.hass}
.trace=${this._trace}
.logbookEntries=${this._logbookEntries}
.selected=${this._selected}
@value-changed=${this._timelinePathPicked}
></ha-trace-timeline>
></ha-automation-trace-timeline>
`}
</div>
</div>

View File

@@ -162,14 +162,6 @@ export default class HaAutomationTriggerRow extends LitElement {
)}
</paper-listbox>
</paper-dropdown-menu-light>
<paper-input
.label=${this.hass.localize(
"ui.panel.config.automation.editor.triggers.id"
)}
.value=${this.trigger.id}
@value-changed=${this._idChanged}
>
</paper-input>
<div>
${dynamicElement(
`ha-automation-trigger-${this.trigger.platform}`,
@@ -220,35 +212,15 @@ export default class HaAutomationTriggerRow extends LitElement {
const elClass = customElements.get(`ha-automation-trigger-${type}`);
if (type !== this.trigger.platform) {
const value = {
platform: type,
...elClass.defaultConfig,
};
if (this.trigger.id) {
value.id = this.trigger.id;
}
fireEvent(this, "value-changed", {
value,
value: {
platform: type,
...elClass.defaultConfig,
},
});
}
}
private _idChanged(ev: CustomEvent) {
const newId = ev.detail.value;
if (newId === this.trigger.id) {
return;
}
const value = { ...this.trigger };
if (!newId) {
delete value.id;
} else {
value.id = newId;
}
fireEvent(this, "value-changed", {
value,
});
}
private _onYamlChange(ev: CustomEvent) {
ev.stopPropagation();
if (!ev.detail.isValid) {

View File

@@ -22,7 +22,6 @@ import {
enableConfigEntry,
reloadConfigEntry,
updateConfigEntry,
ERROR_STATES,
} from "../../../data/config_entries";
import type { DeviceRegistryEntry } from "../../../data/device_registry";
import type { EntityRegistryEntry } from "../../../data/entity_registry";
@@ -39,6 +38,12 @@ import type { HomeAssistant } from "../../../types";
import type { ConfigEntryExtended } from "./ha-config-integrations";
import "./ha-integration-header";
const ERROR_STATES: ConfigEntry["state"][] = [
"migration_error",
"setup_error",
"setup_retry",
];
const integrationsWithPanel = {
hassio: "/hassio/dashboard",
mqtt: "/config/mqtt",
@@ -298,7 +303,7 @@ export class HaIntegrationCard extends LitElement {
>
<ha-svg-icon .path=${mdiDotsVertical}></ha-svg-icon>
</mwc-icon-button>
<mwc-list-item @request-selected="${this._handleRename}">
<mwc-list-item @request-selected="${this._editEntryName}">
${this.hass.localize(
"ui.panel.config.integrations.config_entry.rename"
)}
@@ -415,15 +420,6 @@ export class HaIntegrationCard extends LitElement {
showOptionsFlowDialog(this, ev.target.closest("ha-card").configEntry);
}
private _handleRename(ev: CustomEvent<RequestSelectedDetail>): void {
if (!shouldHandleRequestSelectedEvent(ev)) {
return;
}
this._editEntryName(
((ev.target as HTMLElement).closest("ha-card") as any).configEntry
);
}
private _handleReload(ev: CustomEvent<RequestSelectedDetail>): void {
if (!shouldHandleRequestSelectedEvent(ev)) {
return;
@@ -582,7 +578,8 @@ export class HaIntegrationCard extends LitElement {
});
}
private async _editEntryName(configEntry: ConfigEntry) {
private async _editEntryName(ev) {
const configEntry = ev.target.closest("ha-card").configEntry;
const newName = await showPromptDialog(this, {
title: this.hass.localize("ui.panel.config.integrations.rename_dialog"),
defaultValue: configEntry.title,

View File

@@ -1,312 +0,0 @@
import "@material/mwc-button/mwc-button";
import "@material/mwc-linear-progress/mwc-linear-progress";
import { mdiStethoscope, mdiCheckCircle, mdiCloseCircle } from "@mdi/js";
import { UnsubscribeFunc } from "home-assistant-js-websocket";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../../common/dom/fire_event";
import { createCloseHeading } from "../../../../../components/ha-dialog";
import {
fetchNetworkStatus,
healNetwork,
stopHealNetwork,
subscribeHealNetworkProgress,
ZWaveJSHealNetworkStatusMessage,
ZWaveJSNetwork,
} from "../../../../../data/zwave_js";
import { haStyleDialog } from "../../../../../resources/styles";
import { HomeAssistant } from "../../../../../types";
import { ZWaveJSHealNetworkDialogParams } from "./show-dialog-zwave_js-heal-network";
@customElement("dialog-zwave_js-heal-network")
class DialogZWaveJSHealNetwork extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private entry_id?: string;
@state() private _status?: string;
@state() private _progress_total = 0;
@state() private _progress_finished = 0;
@state() private _progress_in_progress = 0;
private _subscribed?: Promise<UnsubscribeFunc>;
public showDialog(params: ZWaveJSHealNetworkDialogParams): void {
this._progress_total = 0;
this.entry_id = params.entry_id;
this._fetchData();
}
public closeDialog(): void {
this.entry_id = undefined;
this._status = undefined;
this._progress_total = 0;
this._unsubscribe();
fireEvent(this, "dialog-closed", { dialog: this.localName });
}
protected render(): TemplateResult {
if (!this.entry_id) {
return html``;
}
return html`
<ha-dialog
open
@closed=${this.closeDialog}
.heading=${createCloseHeading(
this.hass,
this.hass.localize("ui.panel.config.zwave_js.heal_network.title")
)}
>
${!this._status
? html`
<div class="flex-container">
<ha-svg-icon
.path=${mdiStethoscope}
class="introduction"
></ha-svg-icon>
<div class="status">
<p>
${this.hass.localize(
"ui.panel.config.zwave_js.heal_network.introduction"
)}
</p>
</div>
</div>
<p>
<em>
${this.hass.localize(
"ui.panel.config.zwave_js.heal_network.traffic_warning"
)}
</em>
</p>
<mwc-button slot="primaryAction" @click=${this._startHeal}>
${this.hass.localize(
"ui.panel.config.zwave_js.heal_network.start_heal"
)}
</mwc-button>
`
: ``}
${this._status === "started"
? html`
<div class="status">
<p>
<b>
${this.hass.localize(
"ui.panel.config.zwave_js.heal_network.in_progress"
)}
</b>
</p>
<p>
${this.hass.localize(
"ui.panel.config.zwave_js.heal_network.run_in_background"
)}
</p>
</div>
${!this._progress_total
? html`
<mwc-linear-progress indeterminate> </mwc-linear-progress>
`
: ""}
<mwc-button slot="secondaryAction" @click=${this._stopHeal}>
${this.hass.localize(
"ui.panel.config.zwave_js.heal_network.stop_heal"
)}
</mwc-button>
<mwc-button slot="primaryAction" @click=${this.closeDialog}>
${this.hass.localize("ui.panel.config.zwave_js.common.close")}
</mwc-button>
`
: ``}
${this._status === "failed"
? html`
<div class="flex-container">
<ha-svg-icon
.path=${mdiCloseCircle}
class="failed"
></ha-svg-icon>
<div class="status">
<p>
${this.hass.localize(
"ui.panel.config.zwave_js.heal_network.healing_failed"
)}
</p>
</div>
</div>
<mwc-button slot="primaryAction" @click=${this.closeDialog}>
${this.hass.localize("ui.panel.config.zwave_js.common.close")}
</mwc-button>
`
: ``}
${this._status === "finished"
? html`
<div class="flex-container">
<ha-svg-icon
.path=${mdiCheckCircle}
class="success"
></ha-svg-icon>
<div class="status">
<p>
${this.hass.localize(
"ui.panel.config.zwave_js.heal_network.healing_complete"
)}
</p>
</div>
</div>
<mwc-button slot="primaryAction" @click=${this.closeDialog}>
${this.hass.localize("ui.panel.config.zwave_js.common.close")}
</mwc-button>
`
: ``}
${this._status === "cancelled"
? html`
<div class="flex-container">
<ha-svg-icon
.path=${mdiCloseCircle}
class="failed"
></ha-svg-icon>
<div class="status">
<p>
${this.hass.localize(
"ui.panel.config.zwave_js.heal_network.healing_cancelled"
)}
</p>
</div>
</div>
<mwc-button slot="primaryAction" @click=${this.closeDialog}>
${this.hass.localize("ui.panel.config.zwave_js.common.close")}
</mwc-button>
`
: ``}
${this._progress_total && this._status !== "finished"
? html`
<mwc-linear-progress
determinate
.progress=${this._progress_finished}
.buffer=${this._progress_in_progress}
>
</mwc-linear-progress>
`
: ""}
</ha-dialog>
`;
}
private async _fetchData(): Promise<void> {
if (!this.hass) {
return;
}
const network: ZWaveJSNetwork = await fetchNetworkStatus(
this.hass!,
this.entry_id!
);
if (network.controller.is_heal_network_active) {
this._status = "started";
this._subscribed = subscribeHealNetworkProgress(
this.hass,
this.entry_id!,
this._handleMessage.bind(this)
);
}
}
private _startHeal(): void {
if (!this.hass) {
return;
}
healNetwork(this.hass, this.entry_id!);
this._status = "started";
this._subscribed = subscribeHealNetworkProgress(
this.hass,
this.entry_id!,
this._handleMessage.bind(this)
);
}
private _stopHeal(): void {
if (!this.hass) {
return;
}
stopHealNetwork(this.hass, this.entry_id!);
this._unsubscribe();
this._status = "cancelled";
}
private _handleMessage(message: ZWaveJSHealNetworkStatusMessage): void {
if (message.event === "heal network progress") {
let finished = 0;
let in_progress = 0;
for (const status of Object.values(message.heal_node_status)) {
if (status === "pending") {
in_progress++;
}
if (["skipped", "failed", "done"].includes(status)) {
finished++;
}
}
this._progress_total = Object.keys(message.heal_node_status).length;
this._progress_finished = finished / this._progress_total;
this._progress_in_progress = in_progress / this._progress_total;
}
if (message.event === "heal network done") {
this._unsubscribe();
this._status = "finished";
}
}
private _unsubscribe(): void {
if (this._subscribed) {
this._subscribed.then((unsub) => unsub());
this._subscribed = undefined;
}
}
static get styles(): CSSResultGroup {
return [
haStyleDialog,
css`
.success {
color: var(--success-color);
}
.failed {
color: var(--warning-color);
}
.flex-container {
display: flex;
align-items: center;
}
ha-svg-icon {
width: 68px;
height: 48px;
}
ha-svg-icon.introduction {
color: var(--primary-color);
}
.flex-container ha-svg-icon {
margin-right: 20px;
}
mwc-linear-progress {
margin-top: 8px;
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-zwave_js-heal-network": DialogZWaveJSHealNetwork;
}
}

View File

@@ -1,19 +0,0 @@
import { fireEvent } from "../../../../../common/dom/fire_event";
export interface ZWaveJSHealNetworkDialogParams {
entry_id: string;
}
export const loadHealNetworkDialog = () =>
import("./dialog-zwave_js-heal-network");
export const showZWaveJSHealNetworkDialog = (
element: HTMLElement,
healNetworkDialogParams: ZWaveJSHealNetworkDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-zwave_js-heal-network",
dialogImport: loadHealNetworkDialog,
dialogParams: healNetworkDialogParams,
});
};

View File

@@ -1,6 +1,6 @@
import "@material/mwc-button/mwc-button";
import "@material/mwc-icon-button/mwc-icon-button";
import { mdiAlertCircle, mdiCheckCircle, mdiCircle, mdiRefresh } from "@mdi/js";
import { mdiCheckCircle, mdiCircle, mdiRefresh } from "@mdi/js";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
@@ -17,11 +17,6 @@ import {
ZWaveJSNetwork,
ZWaveJSNode,
} from "../../../../../data/zwave_js";
import {
ConfigEntry,
getConfigEntries,
ERROR_STATES,
} from "../../../../../data/config_entries";
import {
showAlertDialog,
showConfirmationDialog,
@@ -32,10 +27,8 @@ import type { HomeAssistant, Route } from "../../../../../types";
import { fileDownload } from "../../../../../util/file_download";
import "../../../ha-config-section";
import { showZWaveJSAddNodeDialog } from "./show-dialog-zwave_js-add-node";
import { showZWaveJSHealNetworkDialog } from "./show-dialog-zwave_js-heal-network";
import { showZWaveJSRemoveNodeDialog } from "./show-dialog-zwave_js-remove-node";
import { configTabs } from "./zwave_js-config-router";
import { showOptionsFlowDialog } from "../../../../../dialogs/config-flow/show-dialog-options-flow";
@customElement("zwave_js-config-dashboard")
class ZWaveJSConfigDashboard extends LitElement {
@@ -49,8 +42,6 @@ class ZWaveJSConfigDashboard extends LitElement {
@property() public configEntryId?: string;
@state() private _configEntry?: ConfigEntry;
@state() private _network?: ZWaveJSNetwork;
@state() private _nodes?: ZWaveJSNode[];
@@ -68,14 +59,6 @@ class ZWaveJSConfigDashboard extends LitElement {
}
protected render(): TemplateResult {
if (!this._configEntry) {
return html``;
}
if (ERROR_STATES.includes(this._configEntry.state)) {
return this._renderErrorScreen();
}
return html`
<hass-tabs-subpage
.hass=${this.hass}
@@ -179,16 +162,6 @@ class ZWaveJSConfigDashboard extends LitElement {
"ui.panel.config.zwave_js.common.remove_node"
)}
</mwc-button>
<mwc-button @click=${this._healNetworkClicked}>
${this.hass.localize(
"ui.panel.config.zwave_js.common.heal_network"
)}
</mwc-button>
<mwc-button @click=${this._openOptionFlow}>
${this.hass.localize(
"ui.panel.config.zwave_js.common.reconfigure_server"
)}
</mwc-button>
</div>
</ha-card>
<ha-card>
@@ -236,83 +209,10 @@ class ZWaveJSConfigDashboard extends LitElement {
`;
}
private _renderErrorScreen() {
const item = this._configEntry!;
let stateText: [string, ...unknown[]] | undefined;
let stateTextExtra: TemplateResult | string | undefined;
if (item.disabled_by) {
stateText = [
"ui.panel.config.integrations.config_entry.disable.disabled_cause",
{
cause:
this.hass.localize(
`ui.panel.config.integrations.config_entry.disable.disabled_by.${item.disabled_by}`
) || item.disabled_by,
},
];
if (item.state === "failed_unload") {
stateTextExtra = html`.
${this.hass.localize(
"ui.panel.config.integrations.config_entry.disable_restart_confirm"
)}.`;
}
} else if (item.state === "not_loaded") {
stateText = ["ui.panel.config.integrations.config_entry.not_loaded"];
} else if (ERROR_STATES.includes(item.state)) {
stateText = [
`ui.panel.config.integrations.config_entry.state.${item.state}`,
];
if (item.reason) {
this.hass.loadBackendTranslation("config", item.domain);
stateTextExtra = html` ${this.hass.localize(
`component.${item.domain}.config.error.${item.reason}`
) || item.reason}`;
} else {
stateTextExtra = html`
<br />
<a href="/config/logs"
>${this.hass.localize(
"ui.panel.config.integrations.config_entry.check_the_logs"
)}</a
>
`;
}
}
return html` ${stateText
? html`
<div class="error-message">
<ha-svg-icon .path=${mdiAlertCircle}></ha-svg-icon>
<h3>
${this._configEntry!.title}: ${this.hass.localize(...stateText)}
</h3>
<p>${stateTextExtra}</p>
<mwc-button @click=${this._handleBack}>
${this.hass?.localize("ui.panel.error.go_back") || "go back"}
</mwc-button>
</div>
`
: ""}`;
}
private _handleBack(): void {
history.back();
}
private async _fetchData() {
if (!this.configEntryId) {
return;
}
const configEntries = await getConfigEntries(this.hass);
this._configEntry = configEntries.find(
(entry) => entry.entry_id === this.configEntryId!
);
if (ERROR_STATES.includes(this._configEntry!.state)) {
return;
}
const [network, dataCollectionStatus] = await Promise.all([
fetchNetworkStatus(this.hass!, this.configEntryId),
fetchDataCollectionStatus(this.hass!, this.configEntryId),
@@ -354,12 +254,6 @@ class ZWaveJSConfigDashboard extends LitElement {
});
}
private async _healNetworkClicked() {
showZWaveJSHealNetworkDialog(this, {
entry_id: this.configEntryId!,
});
}
private _dataCollectionToggled(ev) {
setDataCollectionPreference(
this.hass!,
@@ -368,17 +262,6 @@ class ZWaveJSConfigDashboard extends LitElement {
);
}
private async _openOptionFlow() {
if (!this.configEntryId) {
return;
}
const configEntries = await getConfigEntries(this.hass);
const configEntry = configEntries.find(
(entry) => entry.entry_id === this.configEntryId
);
showOptionsFlowDialog(this, configEntry!);
}
private async _dumpDebugClicked() {
await this._fetchNodeStatus();
@@ -450,27 +333,6 @@ class ZWaveJSConfigDashboard extends LitElement {
color: red;
}
.error-message {
display: flex;
color: var(--primary-text-color);
height: calc(100% - var(--header-height));
padding: 16px;
align-items: center;
justify-content: center;
flex-direction: column;
}
.error-message h3 {
text-align: center;
font-weight: bold;
}
.error-message ha-svg-icon {
color: var(--error-color);
width: 64px;
height: 64px;
}
.content {
margin-top: 24px;
}

View File

@@ -1,6 +1,5 @@
import "@polymer/paper-dropdown-menu/paper-dropdown-menu";
import "@polymer/paper-listbox/paper-listbox";
import { mdiDownload } from "@mdi/js";
import { UnsubscribeFunc } from "home-assistant-js-websocket";
import { css, CSSResultArray, html, LitElement } from "lit";
import { customElement, property, state, query } from "lit/decorators";
@@ -14,7 +13,6 @@ import "../../../../../layouts/hass-tabs-subpage";
import { SubscribeMixin } from "../../../../../mixins/subscribe-mixin";
import { haStyle } from "../../../../../resources/styles";
import { HomeAssistant, Route } from "../../../../../types";
import { fileDownload } from "../../../../../util/file_download";
import { configTabs } from "./zwave_js-config-router";
@customElement("zwave_js-logs")
@@ -33,20 +31,16 @@ class ZWaveJSLogs extends SubscribeMixin(LitElement) {
public hassSubscribe(): Array<UnsubscribeFunc | Promise<UnsubscribeFunc>> {
return [
subscribeZWaveJSLogs(this.hass, this.configEntryId, (update) => {
subscribeZWaveJSLogs(this.hass, this.configEntryId, (log) => {
if (!this.hasUpdated) {
return;
}
if (update.type === "log_message") {
if (Array.isArray(update.log_message.message)) {
for (const line of update.log_message.message) {
this._textarea!.value += `${line}\n`;
}
} else {
this._textarea!.value += `${update.log_message.message}\n`;
if (Array.isArray(log.message)) {
for (const line of log.message) {
this._textarea!.value += `${line}\n`;
}
} else {
this._logConfig = update.log_config;
this._textarea!.value += `${log.message}\n`;
}
}).then((unsub) => {
this._textarea!.value += `${this.hass.localize(
@@ -98,14 +92,6 @@ class ZWaveJSLogs extends SubscribeMixin(LitElement) {
`
: ""}
</div>
<mwc-icon-button
.label=${this.hass.localize(
"ui.panel.config.zwave_js.logs.download_logs"
)}
@click=${this._downloadLogs}
>
<ha-svg-icon .path=${mdiDownload}></ha-svg-icon>
</mwc-icon-button>
</ha-card>
<textarea readonly></textarea>
</div>
@@ -128,14 +114,6 @@ class ZWaveJSLogs extends SubscribeMixin(LitElement) {
);
}
private _downloadLogs() {
fileDownload(
this,
`data:text/plain;charset=utf-8,${encodeURI(this._textarea!.value)}`,
`zwave_js.log`
);
}
private _dropdownSelected(ev) {
if (ev.target === undefined || this._logConfig === undefined) {
return;
@@ -145,6 +123,7 @@ class ZWaveJSLogs extends SubscribeMixin(LitElement) {
return;
}
setZWaveJSLogLevel(this.hass!, this.configEntryId, selected);
this._logConfig.level = selected;
this._textarea!.value += `${this.hass.localize(
"ui.panel.config.zwave_js.logs.log_level_changed",
{ level: selected.charAt(0).toUpperCase() + selected.slice(1) }

View File

@@ -42,10 +42,6 @@ class HaConfigScript extends HassRouterPage {
edit: {
tag: "ha-script-editor",
},
trace: {
tag: "ha-script-trace",
load: () => import("./ha-script-trace"),
},
},
};
@@ -85,7 +81,7 @@ class HaConfigScript extends HassRouterPage {
if (
(!changedProps || changedProps.has("route")) &&
this._currentPage !== "dashboard"
this._currentPage === "edit"
) {
pageEl.creatingNew = undefined;
const scriptEntityId = this.routeTail.path.substr(1);

View File

@@ -297,16 +297,7 @@ export class HaScriptEditor extends KeyboardShortcutMixin(LitElement) {
<div
class="card-actions layout horizontal justified center"
>
<a
href="/config/script/trace/${this
.scriptEntityId}"
>
<mwc-button>
${this.hass.localize(
"ui.panel.config.script.editor.show_trace"
)}
</mwc-button>
</a>
<span></span>
<mwc-button
@click=${this._runScript}
title="${this.hass.localize(

View File

@@ -1,7 +1,6 @@
import "@material/mwc-icon-button";
import {
mdiHelpCircle,
mdiHistory,
mdiInformationOutline,
mdiPencil,
mdiPlay,
@@ -141,21 +140,6 @@ class HaScriptPicker extends LitElement {
</mwc-icon-button>
`,
};
columns.trace = {
title: "",
type: "icon-button",
template: (_info, script: any) => html`
<a href="/config/script/trace/${script.entity_id}">
<mwc-icon-button
.label=${this.hass.localize(
"ui.panel.config.script.picker.dev_script"
)}
>
<ha-svg-icon .path=${mdiHistory}></ha-svg-icon>
</mwc-icon-button>
</a>
`,
};
columns.edit = {
title: "",
type: "icon-button",

View File

@@ -1,502 +0,0 @@
import {
mdiDownload,
mdiPencil,
mdiRayEndArrow,
mdiRayStartArrow,
mdiRefresh,
} from "@mdi/js";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { repeat } from "lit/directives/repeat";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import { formatDateTimeWithSeconds } from "../../../common/datetime/format_date_time";
import type { NodeInfo } from "../../../components/trace/hat-graph";
import "../../../components/trace/hat-script-graph";
import { getLogbookDataForContext, LogbookEntry } from "../../../data/logbook";
import { ScriptEntity } from "../../../data/script";
import {
loadTrace,
loadTraces,
ScriptTrace,
ScriptTraceExtended,
} from "../../../data/trace";
import { showAlertDialog } from "../../../dialogs/generic/show-dialog-box";
import { haStyle } from "../../../resources/styles";
import { HomeAssistant, Route } from "../../../types";
import { traceTabStyles } from "../../../components/trace/trace-tab-styles";
import { configSections } from "../ha-panel-config";
import "../../../components/trace/ha-trace-blueprint-config";
import "../../../components/trace/ha-trace-config";
import "../../../components/trace/ha-trace-logbook";
import "../../../components/trace/ha-trace-path-details";
import "../../../components/trace/ha-trace-timeline";
@customElement("ha-script-trace")
export class HaScriptTrace extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property() public scriptEntityId!: string;
@property({ attribute: false }) public scripts!: ScriptEntity[];
@property({ type: Boolean }) public isWide?: boolean;
@property({ type: Boolean, reflect: true }) public narrow!: boolean;
@property({ attribute: false }) public route!: Route;
@state() private _traces?: ScriptTrace[];
@state() private _runId?: string;
@state() private _selected?: NodeInfo;
@state() private _trace?: ScriptTraceExtended;
@state() private _logbookEntries?: LogbookEntry[];
@state() private _view:
| "details"
| "config"
| "timeline"
| "logbook"
| "blueprint" = "details";
protected render(): TemplateResult {
const stateObj = this.scriptEntityId
? this.hass.states[this.scriptEntityId]
: undefined;
const graph = this.shadowRoot!.querySelector("hat-script-graph");
const trackedNodes = graph?.trackedNodes;
const renderedNodes = graph?.renderedNodes;
const title = stateObj?.attributes.friendly_name || this.scriptEntityId;
let devButtons: TemplateResult | string = "";
if (__DEV__) {
devButtons = html`<div style="position: absolute; right: 0;">
<button @click=${this._importTrace}>Import trace</button>
<button @click=${this._loadLocalStorageTrace}>Load stored trace</button>
</div>`;
}
const actionButtons = html`
<mwc-icon-button label="Refresh" @click=${() => this._loadTraces()}>
<ha-svg-icon .path=${mdiRefresh}></ha-svg-icon>
</mwc-icon-button>
<mwc-icon-button
.disabled=${!this._trace}
label="Download Trace"
@click=${this._downloadTrace}
>
<ha-svg-icon .path=${mdiDownload}></ha-svg-icon>
</mwc-icon-button>
`;
return html`
${devButtons}
<hass-tabs-subpage
.hass=${this.hass}
.narrow=${this.narrow}
.route=${this.route}
.tabs=${configSections.automation}
>
${this.narrow
? html`<span slot="header"> ${title} </span>
<div slot="toolbar-icon">${actionButtons}</div>`
: ""}
<div class="toolbar">
${!this.narrow
? html`<div>
${title}
<a
class="linkButton"
href="/config/script/edit/${this.scriptEntityId}"
>
<mwc-icon-button label="Edit Script" tabindex="-1">
<ha-svg-icon .path=${mdiPencil}></ha-svg-icon>
</mwc-icon-button>
</a>
</div>`
: ""}
${this._traces && this._traces.length > 0
? html`
<div>
<mwc-icon-button
.disabled=${this._traces[this._traces.length - 1].run_id ===
this._runId}
label="Older trace"
@click=${this._pickOlderTrace}
>
<ha-svg-icon .path=${mdiRayEndArrow}></ha-svg-icon>
</mwc-icon-button>
<select .value=${this._runId} @change=${this._pickTrace}>
${repeat(
this._traces,
(trace) => trace.run_id,
(trace) =>
html`<option value=${trace.run_id}>
${formatDateTimeWithSeconds(
new Date(trace.timestamp.start),
this.hass.locale
)}
</option>`
)}
</select>
<mwc-icon-button
.disabled=${this._traces[0].run_id === this._runId}
label="Newer trace"
@click=${this._pickNewerTrace}
>
<ha-svg-icon .path=${mdiRayStartArrow}></ha-svg-icon>
</mwc-icon-button>
</div>
`
: ""}
${!this.narrow ? html`<div>${actionButtons}</div>` : ""}
</div>
${this._traces === undefined
? html`<div class="container">Loading…</div>`
: this._traces.length === 0
? html`<div class="container">No traces found</div>`
: this._trace === undefined
? ""
: html`
<div class="main">
<div class="graph">
<hat-script-graph
.trace=${this._trace}
.selected=${this._selected?.path}
@graph-node-selected=${this._pickNode}
></hat-script-graph>
</div>
<div class="info">
<div class="tabs top">
${[
["details", "Step Details"],
["timeline", "Trace Timeline"],
["logbook", "Related logbook entries"],
["config", "Script Config"],
].map(
([view, label]) => html`
<button
tabindex="0"
.view=${view}
class=${classMap({ active: this._view === view })}
@click=${this._showTab}
>
${label}
</button>
`
)}
${this._trace.blueprint_inputs
? html`
<button
tabindex="0"
.view=${"blueprint"}
class=${classMap({
active: this._view === "blueprint",
})}
@click=${this._showTab}
>
Blueprint Config
</button>
`
: ""}
</div>
${this._selected === undefined ||
this._logbookEntries === undefined ||
trackedNodes === undefined
? ""
: this._view === "details"
? html`
<ha-trace-path-details
.hass=${this.hass}
.narrow=${this.narrow}
.trace=${this._trace}
.selected=${this._selected}
.logbookEntries=${this._logbookEntries}
.trackedNodes=${trackedNodes}
.renderedNodes=${renderedNodes!}
></ha-trace-path-details>
`
: this._view === "config"
? html`
<ha-trace-config
.hass=${this.hass}
.trace=${this._trace}
></ha-trace-config>
`
: this._view === "logbook"
? html`
<ha-trace-logbook
.hass=${this.hass}
.narrow=${this.narrow}
.trace=${this._trace}
.logbookEntries=${this._logbookEntries}
></ha-trace-logbook>
`
: this._view === "blueprint"
? html`
<ha-trace-blueprint-config
.hass=${this.hass}
.trace=${this._trace}
></ha-trace-blueprint-config>
`
: html`
<ha-trace-timeline
.hass=${this.hass}
.trace=${this._trace}
.logbookEntries=${this._logbookEntries}
.selected=${this._selected}
@value-changed=${this._timelinePathPicked}
></ha-trace-timeline>
`}
</div>
</div>
`}
</hass-tabs-subpage>
`;
}
protected firstUpdated(changedProps) {
super.firstUpdated(changedProps);
if (!this.scriptEntityId) {
return;
}
const params = new URLSearchParams(location.search);
this._loadTraces(params.get("run_id") || undefined);
}
protected updated(changedProps) {
super.updated(changedProps);
// Only reset if automationId has changed and we had one before.
if (changedProps.get("scriptEntityId")) {
this._traces = undefined;
this._runId = undefined;
this._trace = undefined;
this._logbookEntries = undefined;
if (this.scriptEntityId) {
this._loadTraces();
}
}
if (changedProps.has("_runId") && this._runId) {
this._trace = undefined;
this._logbookEntries = undefined;
this.shadowRoot!.querySelector("select")!.value = this._runId;
this._loadTrace();
}
}
private _pickOlderTrace() {
const curIndex = this._traces!.findIndex((tr) => tr.run_id === this._runId);
this._runId = this._traces![curIndex + 1].run_id;
this._selected = undefined;
}
private _pickNewerTrace() {
const curIndex = this._traces!.findIndex((tr) => tr.run_id === this._runId);
this._runId = this._traces![curIndex - 1].run_id;
this._selected = undefined;
}
private _pickTrace(ev) {
this._runId = ev.target.value;
this._selected = undefined;
}
private _pickNode(ev) {
this._selected = ev.detail;
}
private async _loadTraces(runId?: string) {
this._traces = await loadTraces(
this.hass,
"script",
this.scriptEntityId.split(".")[1]
);
// Newest will be on top.
this._traces.reverse();
if (runId) {
this._runId = runId;
}
// Check if current run ID still exists
if (
this._runId &&
!this._traces.some((trace) => trace.run_id === this._runId)
) {
this._runId = undefined;
this._selected = undefined;
// If we came here from a trace passed into the url, clear it.
if (runId) {
const params = new URLSearchParams(location.search);
params.delete("run_id");
history.replaceState(
null,
"",
`${location.pathname}?${params.toString()}`
);
}
await showAlertDialog(this, {
text: "Chosen trace is no longer available",
});
}
// See if we can set a default runID
if (!this._runId && this._traces.length > 0) {
this._runId = this._traces[0].run_id;
}
}
private async _loadTrace() {
const trace = await loadTrace(
this.hass,
"script",
this.scriptEntityId.split(".")[1],
this._runId!
);
this._logbookEntries = isComponentLoaded(this.hass, "logbook")
? await getLogbookDataForContext(
this.hass,
trace.timestamp.start,
trace.context.id
)
: [];
this._trace = trace;
}
private _downloadTrace() {
const aEl = document.createElement("a");
aEl.download = `trace ${this.scriptEntityId} ${
this._trace!.timestamp.start
}.json`;
aEl.href = `data:application/json;charset=utf-8,${encodeURI(
JSON.stringify(
{
trace: this._trace,
logbookEntries: this._logbookEntries,
},
undefined,
2
)
)}`;
aEl.click();
}
private _importTrace() {
const traceText = prompt("Enter downloaded trace");
if (!traceText) {
return;
}
localStorage.devTrace = traceText;
this._loadLocalTrace(traceText);
}
private _loadLocalStorageTrace() {
if (localStorage.devTrace) {
this._loadLocalTrace(localStorage.devTrace);
}
}
private _loadLocalTrace(traceText: string) {
const traceInfo = JSON.parse(traceText);
this._trace = traceInfo.trace;
this._logbookEntries = traceInfo.logbookEntries;
}
private _showTab(ev) {
this._view = (ev.target as any).view;
}
private _timelinePathPicked(ev) {
const path = ev.detail.value;
const nodes = this.shadowRoot!.querySelector("hat-script-graph")!
.trackedNodes;
if (nodes[path]) {
this._selected = nodes[path];
}
}
static get styles(): CSSResultGroup {
return [
haStyle,
traceTabStyles,
css`
.toolbar {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 20px;
height: var(--header-height);
padding: 0 16px;
background-color: var(--primary-background-color);
font-weight: 400;
color: var(--app-header-text-color, white);
border-bottom: var(--app-header-border-bottom, none);
box-sizing: border-box;
}
.toolbar > * {
display: flex;
align-items: center;
}
:host([narrow]) .toolbar > * {
display: contents;
}
.main {
height: calc(100% - 56px);
display: flex;
background-color: var(--card-background-color);
}
:host([narrow]) .main {
height: auto;
flex-direction: column;
}
.container {
padding: 16px;
}
.graph {
border-right: 1px solid var(--divider-color);
overflow-x: auto;
max-width: 50%;
}
:host([narrow]) .graph {
max-width: 100%;
}
.info {
flex: 1;
background-color: var(--card-background-color);
}
.linkButton {
color: var(--primary-text-color);
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-script-trace": HaScriptTrace;
}
}

View File

@@ -8,7 +8,7 @@ import "../../components/ha-circular-progress";
import "../../components/ha-date-range-picker";
import type { DateRangePickerRanges } from "../../components/ha-date-range-picker";
import "../../components/ha-menu-button";
import "../../components/chart/state-history-charts";
import "../../components/state-history-charts";
import { computeHistory, fetchDate } from "../../data/history";
import "../../layouts/ha-app-layout";
import { haStyle } from "../../resources/styles";

View File

@@ -19,7 +19,6 @@ import {
} from "../../data/logbook";
import { loadTraceContexts, TraceContexts } from "../../data/trace";
import { fetchUsers } from "../../data/user";
import { showAlertDialog } from "../../dialogs/generic/show-dialog-box";
import "../../layouts/ha-app-layout";
import { haStyle } from "../../resources/styles";
import { HomeAssistant } from "../../types";
@@ -251,28 +250,16 @@ export class HaPanelLogbook extends LitElement {
private async _getData() {
this._isLoading = true;
let entries;
let traceContexts;
try {
[entries, traceContexts] = await Promise.all([
getLogbookData(
this.hass,
this._startDate.toISOString(),
this._endDate.toISOString(),
this._entityId
),
isComponentLoaded(this.hass, "trace") && this.hass.user?.is_admin
? loadTraceContexts(this.hass)
: {},
this._fetchUserPromise,
]);
} catch (err) {
showAlertDialog(this, {
title: this.hass.localize("ui.components.logbook.retrieval_error"),
text: err.message,
});
}
const [entries, traceContexts] = await Promise.all([
getLogbookData(
this.hass,
this._startDate.toISOString(),
this._endDate.toISOString(),
this._entityId
),
isComponentLoaded(this.hass, "trace") ? loadTraceContexts(this.hass) : {},
this._fetchUserPromise,
]);
this._entries = entries;
this._traceContexts = traceContexts;

View File

@@ -10,7 +10,7 @@ import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { throttle } from "../../../common/util/throttle";
import "../../../components/ha-card";
import "../../../components/chart/state-history-charts";
import "../../../components/state-history-charts";
import { CacheConfig, getRecentWithCache } from "../../../data/cached-history";
import { HistoryResult } from "../../../data/history";
import { HomeAssistant } from "../../../types";
@@ -139,8 +139,8 @@ export class HuiHistoryGraphCard extends LitElement implements LovelaceCard {
.isLoadingData=${!this._stateHistory}
.historyData=${this._stateHistory}
.names=${this._names}
up-to-now
no-single
.upToNow=${true}
.noSingle=${true}
></state-history-charts>
</div>
</ha-card>

View File

@@ -66,8 +66,6 @@ export class HuiLogbookCard extends LitElement implements LovelaceCard {
private _fetchUserPromise?: Promise<void>;
private _error?: string;
private _throttleGetLogbookEntries = throttle(() => {
this._getLogBookData();
}, 10000);
@@ -189,15 +187,7 @@ export class HuiLogbookCard extends LitElement implements LovelaceCard {
class=${classMap({ "no-header": !this._config!.title })}
>
<div class="content">
${this._error
? html`
<div class="no-entries">
${`${this.hass.localize(
"ui.components.logbook.retrieval_error"
)}: ${this._error}`}
</div>
`
: !this._logbookEntries
${!this._logbookEntries
? html`
<ha-circular-progress
active
@@ -241,22 +231,17 @@ export class HuiLogbookCard extends LitElement implements LovelaceCard {
);
const lastDate = this._lastLogbookDate || hoursToShowDate;
const now = new Date();
let newEntries;
try {
[newEntries] = await Promise.all([
getLogbookData(
this.hass,
lastDate.toISOString(),
now.toISOString(),
this._configEntities!.map((entity) => entity.entity).toString(),
true
),
this._fetchUserPromise,
]);
} catch (err) {
this._error = err.message;
}
const [newEntries] = await Promise.all([
getLogbookData(
this.hass,
lastDate.toISOString(),
now.toISOString(),
this._configEntities!.map((entity) => entity.entity).toString(),
true
),
this._fetchUserPromise,
]);
const logbookEntries = this._logbookEntries
? [...newEntries, ...this._logbookEntries]

View File

@@ -25,10 +25,23 @@ import "../../../components/map/ha-map";
import { mdiImageFilterCenterFocus } from "@mdi/js";
import type { HaMap, HaMapPaths } from "../../../components/map/ha-map";
import memoizeOne from "memoize-one";
import { getColorByIndex } from "../../../common/color/colors";
const MINUTE = 60000;
const COLORS = [
"#0288D1",
"#00AA00",
"#984ea3",
"#00d2d5",
"#ff7f00",
"#af8d00",
"#7f80cd",
"#b3e900",
"#c42e60",
"#a65628",
"#f781bf",
"#8dd3c7",
];
@customElement("hui-map-card")
class HuiMapCard extends LitElement implements LovelaceCard {
@property({ attribute: false }) public hass!: HomeAssistant;
@@ -212,7 +225,7 @@ class HuiMapCard extends LitElement implements LovelaceCard {
if (color) {
return color;
}
color = getColorByIndex(this._colorIndex);
color = COLORS[this._colorIndex % COLORS.length];
this._colorIndex++;
this._colorDict[entityId] = color;
return color;

View File

@@ -447,37 +447,47 @@ export class HuiThermostatCard extends LitElement implements LovelaceCard {
--name-font-size: 1.2rem;
--brightness-font-size: 1.2rem;
--rail-border-color: transparent;
--auto-color: green;
--eco-color: springgreen;
--cool-color: #2b9af9;
--heat-color: #ff8100;
--manual-color: #44739e;
--off-color: #8a8a8a;
--fan_only-color: #8a8a8a;
--dry-color: #efbd07;
--idle-color: #8a8a8a;
--unknown-color: #bac;
}
.auto,
.heat_cool {
--mode-color: var(--state-climate-auto-color);
--mode-color: var(--auto-color);
}
.cool {
--mode-color: var(--state-climate-cool-color);
--mode-color: var(--cool-color);
}
.heat {
--mode-color: var(--state-climate-heat-color);
--mode-color: var(--heat-color);
}
.manual {
--mode-color: var(--state-climate-manual-color);
--mode-color: var(--manual-color);
}
.off {
--mode-color: var(--state-climate-off-color);
--mode-color: var(--off-color);
}
.fan_only {
--mode-color: var(--state-climate-fan_only-color);
--mode-color: var(--fan_only-color);
}
.eco {
--mode-color: var(--state-climate-eco-color);
--mode-color: var(--eco-color);
}
.dry {
--mode-color: var(--state-climate-dry-color);
--mode-color: var(--dry-color);
}
.idle {
--mode-color: var(--state-climate-idle-color);
--mode-color: var(--idle-color);
}
.unknown-mode {
--mode-color: var(--state-unknown-color);
--mode-color: var(--unknown-color);
}
.more-info {

View File

@@ -37,7 +37,6 @@ const LAZY_LOAD_TYPES = {
"input-text-entity": () => import("../entity-rows/hui-input-text-entity-row"),
"lock-entity": () => import("../entity-rows/hui-lock-entity-row"),
"number-entity": () => import("../entity-rows/hui-number-entity-row"),
"select-entity": () => import("../entity-rows/hui-select-entity-row"),
"timer-entity": () => import("../entity-rows/hui-timer-entity-row"),
conditional: () => import("../special-rows/hui-conditional-row"),
"weather-entity": () => import("../entity-rows/hui-weather-entity-row"),
@@ -69,7 +68,6 @@ const DOMAIN_TO_ELEMENT_TYPE = {
remote: "toggle",
scene: "scene",
script: "script",
select: "select",
sensor: "sensor",
timer: "timer",
switch: "toggle",

View File

@@ -81,7 +81,6 @@ export class HuiGraphFooterEditor
"ui.panel.lovelace.editor.card.config.optional"
)})"
.value=${this._hours_to_show}
min="1"
.configValue=${"hours_to_show"}
@value-changed=${this._valueChanged}
></paper-input>

View File

@@ -79,7 +79,6 @@ export class HuiHistoryGraphCardEditor
"ui.panel.lovelace.editor.card.config.optional"
)})"
.value="${this._hours_to_show}"
min="1"
.configValue=${"hours_to_show"}
@value-changed="${this._valueChanged}"
></paper-input>

View File

@@ -85,7 +85,6 @@ export class HuiLogbookCardEditor
"ui.panel.lovelace.editor.card.config.optional"
)})"
.value=${this._hours_to_show}
min="1"
.configValue=${"hours_to_show"}
@value-changed=${this._valueChanged}
></paper-input>

View File

@@ -177,7 +177,6 @@ export class HuiSensorCardEditor
)})"
type="number"
.value=${this._hours_to_show}
min="1"
.configValue=${"hours_to_show"}
@value-changed=${this._valueChanged}
></paper-input>

View File

@@ -11,7 +11,7 @@ import { customElement, property, state } from "lit/decorators";
import { computeStateDisplay } from "../../../common/entity/compute_state_display";
import { computeRTLDirection } from "../../../common/util/compute_rtl";
import "../../../components/ha-slider";
import { UNAVAILABLE } from "../../../data/entity";
import { UNAVAILABLE_STATES } from "../../../data/entity";
import { setValue } from "../../../data/input_text";
import { HomeAssistant } from "../../../types";
import { hasConfigOrEntityChanged } from "../common/has-changed";
@@ -75,7 +75,7 @@ class HuiNumberEntityRow extends LitElement implements LovelaceRow {
? html`
<div class="flex">
<ha-slider
.disabled=${stateObj.state === UNAVAILABLE}
.disabled=${UNAVAILABLE_STATES.includes(stateObj.state)}
.dir=${computeRTLDirection(this.hass)}
.step="${Number(stateObj.attributes.step)}"
.min="${Number(stateObj.attributes.min)}"
@@ -101,7 +101,7 @@ class HuiNumberEntityRow extends LitElement implements LovelaceRow {
<paper-input
no-label-float
auto-validate
.disabled=${stateObj.state === UNAVAILABLE}
.disabled=${UNAVAILABLE_STATES.includes(stateObj.state)}
pattern="[0-9]+([\\.][0-9]+)?"
.step="${Number(stateObj.attributes.step)}"
.min="${Number(stateObj.attributes.min)}"

View File

@@ -1,186 +0,0 @@
import "@polymer/paper-item/paper-item";
import "@polymer/paper-listbox/paper-listbox";
import {
css,
CSSResultGroup,
html,
LitElement,
PropertyValues,
TemplateResult,
} from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { ifDefined } from "lit/directives/if-defined";
import { DOMAINS_HIDE_MORE_INFO } from "../../../common/const";
import { stopPropagation } from "../../../common/dom/stop_propagation";
import { computeDomain } from "../../../common/entity/compute_domain";
import { computeStateName } from "../../../common/entity/compute_state_name";
import "../../../components/entity/state-badge";
import "../../../components/ha-paper-dropdown-menu";
import { UNAVAILABLE } from "../../../data/entity";
import { forwardHaptic } from "../../../data/haptics";
import { SelectEntity, setSelectOption } from "../../../data/select";
import { ActionHandlerEvent } from "../../../data/lovelace";
import { HomeAssistant } from "../../../types";
import { EntitiesCardEntityConfig } from "../cards/types";
import { actionHandler } from "../common/directives/action-handler-directive";
import { handleAction } from "../common/handle-action";
import { hasAction } from "../common/has-action";
import { hasConfigOrEntityChanged } from "../common/has-changed";
import { createEntityNotFoundWarning } from "../components/hui-warning";
import { LovelaceRow } from "./types";
@customElement("hui-select-entity-row")
class HuiSelectEntityRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: EntitiesCardEntityConfig;
public setConfig(config: EntitiesCardEntityConfig): void {
if (!config || !config.entity) {
throw new Error("Entity must be specified");
}
this._config = config;
}
protected shouldUpdate(changedProps: PropertyValues): boolean {
return hasConfigOrEntityChanged(this, changedProps);
}
protected render(): TemplateResult {
if (!this.hass || !this._config) {
return html``;
}
const stateObj = this.hass.states[this._config.entity] as
| SelectEntity
| undefined;
if (!stateObj) {
return html`
<hui-warning>
${createEntityNotFoundWarning(this.hass, this._config.entity)}
</hui-warning>
`;
}
const pointer =
(this._config.tap_action && this._config.tap_action.action !== "none") ||
(this._config.entity &&
!DOMAINS_HIDE_MORE_INFO.includes(computeDomain(this._config.entity)));
return html`
<state-badge
.stateObj=${stateObj}
.overrideIcon=${this._config.icon}
.overrideImage=${this._config.image}
class=${classMap({
pointer,
})}
@action=${this._handleAction}
.actionHandler=${actionHandler({
hasHold: hasAction(this._config!.hold_action),
hasDoubleClick: hasAction(this._config!.double_tap_action),
})}
tabindex=${ifDefined(pointer ? "0" : undefined)}
></state-badge>
<ha-paper-dropdown-menu
.label=${this._config.name || computeStateName(stateObj)}
.disabled=${stateObj.state === UNAVAILABLE}
@iron-select=${this._selectedChanged}
@click=${stopPropagation}
>
<paper-listbox slot="dropdown-content">
${stateObj.attributes.options
? stateObj.attributes.options.map(
(option) =>
html`
<paper-item .option=${option}
>${(stateObj.attributes.device_class &&
this.hass!.localize(
`component.select.state.${stateObj.attributes.device_class}.${option}`
)) ||
this.hass!.localize(
`component.select.state._.${option}`
) ||
option}</paper-item
>
`
)
: ""}
</paper-listbox>
</ha-paper-dropdown-menu>
`;
}
protected updated(changedProps: PropertyValues) {
super.updated(changedProps);
if (!this.hass || !this._config) {
return;
}
const stateObj = this.hass.states[this._config.entity] as
| SelectEntity
| undefined;
if (!stateObj) {
return;
}
// Update selected after rendering the items or else it won't work in Firefox
if (stateObj.attributes.options) {
this.shadowRoot!.querySelector(
"paper-listbox"
)!.selected = stateObj.attributes.options.indexOf(stateObj.state);
}
}
private _handleAction(ev: ActionHandlerEvent) {
handleAction(this, this.hass!, this._config!, ev.detail.action!);
}
static get styles(): CSSResultGroup {
return css`
:host {
display: flex;
align-items: center;
}
ha-paper-dropdown-menu {
margin-left: 16px;
flex: 1;
}
paper-item {
cursor: pointer;
min-width: 200px;
}
.pointer {
cursor: pointer;
}
state-badge:focus {
outline: none;
background: var(--divider-color);
border-radius: 100%;
}
`;
}
private _selectedChanged(ev): void {
const stateObj = this.hass!.states[this._config!.entity];
const option = ev.target.selectedItem.option;
if (option === stateObj.state) {
return;
}
forwardHaptic("light");
setSelectOption(this.hass!, stateObj.entity_id, option);
}
}
declare global {
interface HTMLElementTagNameMap {
"hui-select-entity-row": HuiSelectEntityRow;
}
}

View File

@@ -127,10 +127,6 @@ export class MasonryView extends LitElement implements LovelaceViewElement {
public willUpdate(changedProperties: PropertyValues) {
super.willUpdate(changedProperties);
if (this.lovelace?.editMode) {
import("./default-view-editable");
}
if (changedProperties.has("hass")) {
const oldHass = changedProperties.get("hass") as
| HomeAssistant
@@ -144,7 +140,14 @@ export class MasonryView extends LitElement implements LovelaceViewElement {
if (changedProperties.has("narrow")) {
this._updateColumns();
return;
}
}
protected updated(changedProperties: PropertyValues): void {
super.updated(changedProperties);
if (this.lovelace?.editMode) {
import("./default-view-editable");
}
const oldLovelace = changedProperties.get("lovelace") as
@@ -152,11 +155,10 @@ export class MasonryView extends LitElement implements LovelaceViewElement {
| undefined;
if (
changedProperties.has("cards") ||
(changedProperties.has("lovelace") &&
oldLovelace &&
(oldLovelace.config !== this.lovelace!.config ||
oldLovelace.editMode !== this.lovelace!.editMode))
changedProperties.has("lovelace") &&
oldLovelace &&
(oldLovelace.config !== this.lovelace?.config ||
oldLovelace.editMode !== this.lovelace?.editMode)
) {
this._createColumns();
}

View File

@@ -1,35 +0,0 @@
import {
LineController,
TimeScale,
LinearScale,
PointElement,
LineElement,
Filler,
Legend,
Title,
Tooltip,
CategoryScale,
Chart,
} from "chart.js";
import { TextBarElement } from "../components/chart/timeline-chart/textbar-element";
import { TimelineController } from "../components/chart/timeline-chart/timeline-controller";
import { TimeLineScale } from "../components/chart/timeline-chart/timeline-scale";
import "../components/chart/chart-date-adapter";
export { Chart } from "chart.js";
Chart.register(
Tooltip,
Title,
Legend,
Filler,
TimeScale,
LinearScale,
LineController,
PointElement,
LineElement,
TextBarElement,
TimeLineScale,
TimelineController,
CategoryScale
);

View File

@@ -0,0 +1,60 @@
import Chart from "chart.js";
import "chartjs-chart-timeline";
// This function add a new interaction mode to Chart.js that
// returns one point for every dataset.
Chart.Interaction.modes.neareach = function (chart, e, options) {
const getRange = {
x: (a, b) => Math.abs(a.x - b.x),
y: (a, b) => Math.abs(a.y - b.y),
// eslint-disable-next-line no-restricted-properties
xy: (a, b) => Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2),
};
const getRangeMax = {
x: (r) => r,
y: (r) => r,
xy: (r) => r * r,
};
let position;
if (e.native) {
position = {
x: e.x,
y: e.y,
};
} else {
position = Chart.helpers.getRelativePosition(e, chart);
}
const elements = [];
const elementsRange = [];
const datasets = chart.data.datasets;
let meta;
options.axis = options.axis || "xy";
const rangeFunc = getRange[options.axis];
const rangeMaxFunc = getRangeMax[options.axis];
for (let i = 0, ilen = datasets.length; i < ilen; ++i) {
if (!chart.isDatasetVisible(i)) {
continue;
}
meta = chart.getDatasetMeta(i);
for (let j = 0, jlen = meta.data.length; j < jlen; ++j) {
const element = meta.data[j];
if (!element._view.skip) {
const vm = element._view;
const range = rangeFunc(vm, position);
const oldRange = elementsRange[i];
if (range < rangeMaxFunc(vm.radius + vm.hitRadius)) {
if (oldRange === undefined || oldRange > range) {
elementsRange[i] = range;
elements[i] = element;
}
}
}
}
}
const ret = elements.filter((n) => n !== undefined);
return ret;
};
export default Chart;

Some files were not shown because too many files have changed in this diff Show More