mirror of
https://github.com/home-assistant/frontend.git
synced 2026-11-07 21:45:16 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eebc57d89a | ||
|
|
63b474f43c | ||
|
|
d5cc973c22 | ||
|
|
00e76021ce | ||
|
|
fb88d66421 | ||
|
|
23b161d257 | ||
|
|
123a32dd81 | ||
|
|
4dc713abe6 | ||
|
|
b9182e3ea6 | ||
|
|
9bd57fa122 | ||
|
|
4af7503112 | ||
|
|
984e63dcd0 | ||
|
|
f90ed06080 | ||
|
|
b176b8226b | ||
|
|
3f3e9297f7 | ||
|
|
83028028e8 | ||
|
|
37d7c6144c | ||
|
|
f469f3eeae | ||
|
|
069e87c913 | ||
|
|
46bdbee8f3 | ||
|
|
68def911a6 | ||
|
|
a8fdb99317 | ||
|
|
3d1bf61683 | ||
|
|
5cfdff0e21 | ||
|
|
54cefeb816 | ||
|
|
4458205273 | ||
|
|
0c2de46f11 | ||
|
|
6bef900455 | ||
|
|
438bfa2710 | ||
|
|
96864e951a | ||
|
|
a1355e5116 | ||
|
|
ae4366020c | ||
|
|
7f73d29b2f | ||
|
|
ebf453ccc7 | ||
|
|
a0d9afe695 | ||
|
|
c42d048736 | ||
|
|
2f62ed5f73 | ||
|
|
8b6caeecdd | ||
|
|
4800b4f7e9 | ||
|
|
c7afc3391c | ||
|
|
3e9490e547 | ||
|
|
7a1cd6bbfe | ||
|
|
a2c3147d33 | ||
|
|
7039e3ad9f |
No files matched your search
@@ -10,6 +10,7 @@ Use this skill when editing CSS, layout, visual hierarchy, theme integration, re
|
||||
## Theme And Layout Basics
|
||||
|
||||
- Use Home Assistant CSS custom properties instead of hardcoded colors.
|
||||
- CSS in the static HTML templates under `src/html/` must give custom properties a fallback value (for example `var(--ha-space-4, 16px)`), because the global tokens only exist once the JS-appended global stylesheet from `append-ha-style` has loaded.
|
||||
- Use `--ha-space-*` spacing tokens instead of hardcoded spacing where possible.
|
||||
- Keep components mobile-first and enhance for desktop.
|
||||
- Keep layouts RTL-safe. Prefer logical properties when they fit.
|
||||
|
||||
@@ -16,6 +16,7 @@ runs:
|
||||
with:
|
||||
path: |
|
||||
node_modules
|
||||
packages/*/node_modules
|
||||
~/.local/share/pnpm/store
|
||||
key: >-
|
||||
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
|
||||
@@ -35,6 +36,7 @@ runs:
|
||||
with:
|
||||
path: |
|
||||
node_modules
|
||||
packages/*/node_modules
|
||||
~/.local/share/pnpm/store
|
||||
key: >-
|
||||
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
|
||||
|
||||
@@ -28,6 +28,7 @@ runs:
|
||||
with:
|
||||
path: |
|
||||
node_modules
|
||||
packages/*/node_modules
|
||||
~/.local/share/pnpm/store
|
||||
key: >-
|
||||
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
|
||||
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
deploy_dev:
|
||||
runs-on: ubuntu-latest
|
||||
name: Deploy Development
|
||||
if: github.repository == 'home-assistant/frontend' && github.event_name != 'push'
|
||||
if: github.repository == 'home-assistant/frontend' && github.ref_name != 'master'
|
||||
environment:
|
||||
name: Cast Development
|
||||
url: ${{ steps.deploy.outputs.netlify_url }}
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
deploy_master:
|
||||
runs-on: ubuntu-latest
|
||||
name: Deploy Production
|
||||
if: github.repository == 'home-assistant/frontend' && github.event_name == 'push'
|
||||
if: github.repository == 'home-assistant/frontend' && github.ref_name == 'master'
|
||||
environment:
|
||||
name: Cast Production
|
||||
url: ${{ steps.deploy.outputs.netlify_url }}
|
||||
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
deploy_dev:
|
||||
runs-on: ubuntu-latest
|
||||
name: Demo Development
|
||||
if: github.repository == 'home-assistant/frontend' && (github.event_name != 'push' || github.ref_name != 'master')
|
||||
if: github.repository == 'home-assistant/frontend' && github.ref_name != 'master'
|
||||
environment:
|
||||
name: Demo Development
|
||||
url: ${{ steps.deploy.outputs.unique_deploy_url }}
|
||||
@@ -50,7 +50,7 @@ jobs:
|
||||
deploy_master:
|
||||
runs-on: ubuntu-latest
|
||||
name: Demo Production
|
||||
if: github.repository == 'home-assistant/frontend' && github.event_name == 'push' && github.ref_name == 'master'
|
||||
if: github.repository == 'home-assistant/frontend' && github.ref_name == 'master'
|
||||
environment:
|
||||
name: Demo Production
|
||||
url: ${{ steps.deploy.outputs.netlify_url }}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/* global module, require */
|
||||
// rspack/webpack loader that minifies the HTML, SVG, and CSS inside lit
|
||||
// tagged template literals using `minify-literals` (html-minifier-next +
|
||||
// lightningcss). Replaces the unmaintained babel-plugin-template-html-minifier.
|
||||
@@ -36,6 +35,14 @@ const initLoader = (browserslistEnv) => {
|
||||
return {
|
||||
minifyHTMLLiterals: minifyModule.minifyHTMLLiterals,
|
||||
lightningcssTargets,
|
||||
// With the legacy floor at Chrome 67, lightningcss rewrites rgba()
|
||||
// to 8-digit hex (#rrggbbaa). Some kiosk webviews served the legacy
|
||||
// build (e.g. Shelly Wall Display) can't parse that, so any
|
||||
// var(--divider-color) border falls back to currentColor. Always
|
||||
// compile hex alpha colors to rgba() in legacy builds.
|
||||
lightningcssInclude: browserslistEnv.startsWith("legacy")
|
||||
? lightningcssModule.Features.HexAlphaColors
|
||||
: 0,
|
||||
};
|
||||
})
|
||||
);
|
||||
@@ -67,12 +74,13 @@ module.exports = function minifyTemplateLiteralsLoader(source, map, meta) {
|
||||
const { browserslistEnv } = this.getOptions();
|
||||
|
||||
initLoader(browserslistEnv)
|
||||
.then(({ minifyHTMLLiterals, lightningcssTargets }) =>
|
||||
.then(({ minifyHTMLLiterals, lightningcssTargets, lightningcssInclude }) =>
|
||||
minifyHTMLLiterals(source, {
|
||||
fileName: this.resourcePath,
|
||||
html: htmlOptions,
|
||||
css: {
|
||||
targets: lightningcssTargets,
|
||||
include: lightningcssInclude,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
@@ -68,8 +68,42 @@ const CONFIG_FILES = [
|
||||
path.join(__dirname, "lit-disable-dev-mode-loader.cjs"),
|
||||
path.join(__dirname, "babel-plugins", "custom-polyfill-plugin.js"),
|
||||
path.join(__dirname, "babel-plugins", "inline-constants-plugin.cjs"),
|
||||
// Its exports define the components source aliases below
|
||||
path.join(__dirname, "..", "packages", "components", "package.json"),
|
||||
];
|
||||
|
||||
// Resolve @home-assistant/components entry points to their sources, so the package
|
||||
// needs no build step during development. The entry points are read from the
|
||||
// "ha-source" export condition of the package; subpath patterns are expanded
|
||||
// for every element, i.e. every directory with a global.ts, like "card".
|
||||
const COMPONENTS_PACKAGE_DIR = path.join(
|
||||
paths.root_dir,
|
||||
"packages",
|
||||
"components"
|
||||
);
|
||||
const COMPONENTS_SRC_DIR = path.join(
|
||||
COMPONENTS_PACKAGE_DIR,
|
||||
"src",
|
||||
"components"
|
||||
);
|
||||
const componentElements = fs
|
||||
.readdirSync(COMPONENTS_SRC_DIR, { recursive: true })
|
||||
.filter((file) => path.basename(file) === "global.ts")
|
||||
.map((file) => path.dirname(file).split(path.sep).join("/"));
|
||||
const componentsSourceAliases = Object.fromEntries(
|
||||
Object.entries(require("../packages/components/package.json").exports)
|
||||
.filter(([, target]) => target["ha-source"])
|
||||
.flatMap(([subpath, target]) =>
|
||||
(subpath.includes("*") ? componentElements : [undefined]).map((name) => [
|
||||
`${path.posix.join("@home-assistant/components", name ? subpath.replaceAll("*", name) : subpath)}$`,
|
||||
path.join(
|
||||
COMPONENTS_PACKAGE_DIR,
|
||||
name ? target["ha-source"].replaceAll("*", name) : target["ha-source"]
|
||||
),
|
||||
])
|
||||
)
|
||||
);
|
||||
|
||||
// Patches change a package's files but not its version, which is all the
|
||||
// node_modules snapshot checks, so their contents go into the version too.
|
||||
const PATCHES_DIR = path.join(paths.root_dir, "patches");
|
||||
@@ -244,6 +278,9 @@ const createRspackConfig = ({
|
||||
path: paths.root_dir,
|
||||
env: "legacy",
|
||||
}),
|
||||
// Keep rgba() instead of #rrggbbaa, see
|
||||
// minify-template-literals-loader.cjs
|
||||
include: { hexAlphaColors: true },
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -428,6 +465,7 @@ const createRspackConfig = ({
|
||||
"src/resources/polyfills/bigdecimal.ts"
|
||||
),
|
||||
}),
|
||||
...componentsSourceAliases,
|
||||
"lit/static-html$": "lit/static-html.js",
|
||||
"lit/decorators$": "lit/decorators.js",
|
||||
"lit/directive$": "lit/directive.js",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Cache-Control: public, max-age: 0, s-maxage=3600, must-revalidate
|
||||
Cache-Control: public, max-age=0, s-maxage=3600, must-revalidate
|
||||
Content-Security-Policy: form-action https:
|
||||
Feature-Policy: vibrate 'none'; geolocation 'none'; midi 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; vibrate 'none'; payment 'none'
|
||||
Referrer-Policy: no-referrer-when-downgrade
|
||||
@@ -8,13 +8,13 @@
|
||||
X-XSS-Protection: 1; mode=block
|
||||
|
||||
/images/*
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
|
||||
/manifest.json
|
||||
Cache-Control: public, max-age: 3600, s-maxage=3600
|
||||
Cache-Control: public, max-age=3600, s-maxage=3600
|
||||
|
||||
/frontend_es5/*
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
|
||||
/frontend_latest/*
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"background_color": "#FFFFFF",
|
||||
"description": "Show Home Assistant on your Chromecast or Google Assistant devices with a screen.",
|
||||
"description": "Show Home Assistant on your Chromecast or Google Home devices with a screen.",
|
||||
"dir": "ltr",
|
||||
"display": "standalone",
|
||||
"icons": [
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta property="og:type" content="website" />
|
||||
<meta
|
||||
property="og:description"
|
||||
content="Show Home Assistant on your Chromecast or Google Assistant devices with a screen."
|
||||
content="Show Home Assistant on your Chromecast or Google Home devices with a screen."
|
||||
/>
|
||||
<meta
|
||||
property="og:image"
|
||||
@@ -16,7 +16,7 @@
|
||||
<meta name="twitter:title" content="Home Assistant Cast" />
|
||||
<meta
|
||||
name="twitter:description"
|
||||
content="Show Home Assistant on your Chromecast or Google Assistant devices with a screen."
|
||||
content="Show Home Assistant on your Chromecast or Google Home devices with a screen."
|
||||
/>
|
||||
<meta
|
||||
name="twitter:image"
|
||||
|
||||
@@ -52,7 +52,7 @@
|
||||
<p>
|
||||
Home Assistant Cast allows you to show your Home Assistant data on a
|
||||
Chromecast device and allows you to interact with Home Assistant on
|
||||
Google Assistant devices with a screen.
|
||||
Google Home devices with a screen.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ const translateErr = (err) =>
|
||||
const INTRO = html`
|
||||
<p>
|
||||
Home Assistant Cast allows you to cast your Home Assistant installation to
|
||||
Chromecast video devices and to Google Assistant devices with a screen.
|
||||
Chromecast video devices and to Google Home devices with a screen.
|
||||
</p>
|
||||
<p>
|
||||
For more information, see the
|
||||
|
||||
@@ -6,7 +6,7 @@ const playerManager = castContext.getPlayerManager();
|
||||
|
||||
playerManager.setMessageInterceptor("LOAD", (loadRequestData) => {
|
||||
const media = loadRequestData.media;
|
||||
// Special handling if it came from Google Assistant
|
||||
// Special handling if it came from Google Home
|
||||
if (media.entity) {
|
||||
media.contentId = media.entity;
|
||||
media.streamType = "LIVE";
|
||||
|
||||
@@ -13,7 +13,7 @@ export const castDemoLovelace: () => LovelaceConfig = () => {
|
||||
{
|
||||
type: "markdown",
|
||||
title: "Home Assistant Cast",
|
||||
content: `With Home Assistant you can easily create interfaces (just like this one) which can be shown on Chromecast devices connected to TVs or Google Assistant devices with a screen.${
|
||||
content: `With Home Assistant you can easily create interfaces (just like this one) which can be shown on Chromecast devices connected to TVs or Google Home devices with a screen.${
|
||||
touchSupported
|
||||
? "\n\nYou are able to interact with this demo using the touch screen."
|
||||
: "\n\nOn a Google Nest Hub you are able to interact with Home Assistant Cast via the touch screen."
|
||||
|
||||
@@ -117,7 +117,7 @@ playerManager.setMessageInterceptor("LOAD", (loadRequestData) => {
|
||||
// We received a play media command, hide Lovelace and show media player
|
||||
showMediaPlayer();
|
||||
const media = loadRequestData.media;
|
||||
// Special handling if it came from Google Assistant
|
||||
// Special handling if it came from Google Home
|
||||
if (media.entity) {
|
||||
media.contentId = media.entity;
|
||||
media.streamType = "LIVE";
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
/*
|
||||
Cache-Control: public, max-age: 0, s-maxage=3600, must-revalidate
|
||||
Cache-Control: public, max-age=0, s-maxage=3600, must-revalidate
|
||||
Content-Security-Policy: form-action https:
|
||||
Referrer-Policy: no-referrer-when-downgrade
|
||||
X-Content-Type-Options: nosniff
|
||||
X-XSS-Protection: 1; mode=block
|
||||
|
||||
/api/*
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
|
||||
/assets/*
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
|
||||
/frontend_es5/*
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
|
||||
/frontend_latest/*
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
Access-Control-Allow-Origin: *
|
||||
|
||||
/embed.js
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import { ContextEvent } from "@lit/context";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { property, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { consume } from "../../../src/common/decorators/consume";
|
||||
import { computeRTLDirection } from "../../../src/common/util/compute_rtl";
|
||||
import { handleAction } from "../../../src/panels/lovelace/common/handle-action";
|
||||
import type { HomeAssistant } from "../../../src/types";
|
||||
import { embedHassContext } from "./context";
|
||||
import type { ScriptObject } from "./script-data";
|
||||
import { readScriptObject } from "./script-data";
|
||||
|
||||
const pageProvider = (): HTMLElement =>
|
||||
document.querySelector("ha-embed-provider") ??
|
||||
document.body.appendChild(document.createElement("ha-embed-provider"));
|
||||
|
||||
// Looks past shadow roots, so an element inside another component still
|
||||
// finds the provider around that component.
|
||||
const insideProvider = (element: Element): boolean => {
|
||||
let current: Element | null = element;
|
||||
|
||||
while (current) {
|
||||
if (current.closest("ha-embed-provider")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const root = current.getRootNode();
|
||||
current = root instanceof ShadowRoot ? root.host : null;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* The base of the embed elements that render dashboard content. The element
|
||||
* uses the provider with the ID in `provider`, else the closest provider
|
||||
* around it, else the first provider on the page. If the page has no
|
||||
* provider, the element adds an empty one.
|
||||
*/
|
||||
export abstract class EmbedElement<
|
||||
Config extends ScriptObject,
|
||||
> extends LitElement {
|
||||
/**
|
||||
* The configuration of the content, the same as in a dashboard. Also read
|
||||
* from a JSON or YAML script child, see `readScriptObject`.
|
||||
*/
|
||||
@property({ type: Object }) public config?: Config;
|
||||
|
||||
/** The ID of the `ha-embed-provider` to use. */
|
||||
@property() public provider?: string;
|
||||
|
||||
@state()
|
||||
@consume({ context: embedHassContext, subscribe: true })
|
||||
protected _hass?: HomeAssistant;
|
||||
|
||||
// A provider that is not an ancestor, which gets the context requests of the
|
||||
// element and its content. Context requests only reach ancestors by
|
||||
// themselves.
|
||||
private _linkedProvider?: HTMLElement;
|
||||
|
||||
private _scriptRead = false;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.addEventListener("context-request", (ev) => {
|
||||
if (!this._linkedProvider) {
|
||||
return;
|
||||
}
|
||||
|
||||
ev.stopPropagation();
|
||||
this._linkedProvider.dispatchEvent(
|
||||
new ContextEvent(
|
||||
ev.context,
|
||||
ev.contextTarget,
|
||||
ev.callback,
|
||||
ev.subscribe
|
||||
)
|
||||
);
|
||||
});
|
||||
// Cards fire their tap, hold and double tap actions for the app to handle
|
||||
this.addEventListener("hass-action", (ev) => {
|
||||
if (this._hass) {
|
||||
// The element that fired the action, so that fire-dom-event reaches
|
||||
// listeners inside custom cards, as in action-mixin
|
||||
const [origin] = ev.composedPath();
|
||||
const node = origin instanceof HTMLElement ? origin : this;
|
||||
|
||||
handleAction(node, this._hass, ev.detail.config, ev.detail.action);
|
||||
}
|
||||
});
|
||||
// The page's address belongs to the page, so only a hash on it, such as
|
||||
// an anchor, navigates there. The browser does that itself, as the app's
|
||||
// navigate() doesn't scroll to the anchor.
|
||||
this.addEventListener("hass-navigate", (ev) => {
|
||||
const { path, replace } = ev.detail;
|
||||
|
||||
ev.preventDefault();
|
||||
|
||||
if (!path.startsWith("#")) {
|
||||
this.navigateTo(path, replace);
|
||||
} else if (replace) {
|
||||
window.location.replace(path);
|
||||
} else {
|
||||
window.location.hash = path;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public connectedCallback() {
|
||||
// Before super.connectedCallback(), which sends the context requests.
|
||||
this._linkedProvider = this.provider
|
||||
? (document.getElementById(this.provider) ?? undefined)
|
||||
: insideProvider(this)
|
||||
? undefined
|
||||
: pageProvider();
|
||||
super.connectedCallback();
|
||||
|
||||
// Only once, so that moving the element keeps a config set since
|
||||
if (this._scriptRead) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._scriptRead = true;
|
||||
|
||||
const data = readScriptObject(this);
|
||||
|
||||
if (data !== undefined) {
|
||||
this.setScriptData(data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A navigate action of the content, other than to a hash on the page. It
|
||||
* leaves the page where it is, like actions that open a dialog. `replace`
|
||||
* is the action's `navigation_replace`.
|
||||
*/
|
||||
protected navigateTo(_path: string, _replace?: boolean) {
|
||||
// Nothing to navigate to, outside a dashboard
|
||||
}
|
||||
|
||||
/** Whether the data of a script child is a configuration of the content. */
|
||||
protected abstract isConfig(data: ScriptObject): data is Config;
|
||||
|
||||
/** Sets the data of a JSON or YAML script child, see `readScriptObject`. */
|
||||
protected setScriptData(data: ScriptObject) {
|
||||
if (this.isConfig(data)) {
|
||||
this.config = data;
|
||||
}
|
||||
}
|
||||
|
||||
/** The content, or `undefined` while there is nothing to render. */
|
||||
protected abstract renderContent(
|
||||
hass: HomeAssistant
|
||||
): TemplateResult | undefined;
|
||||
|
||||
// The content in the theme of the provider
|
||||
protected render() {
|
||||
const hass = this._hass;
|
||||
const content = hass && this.renderContent(hass);
|
||||
|
||||
if (!hass || !content) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`<div
|
||||
class=${classMap({ theme: true, dark: hass.themes.darkMode })}
|
||||
dir=${computeRTLDirection(hass)}
|
||||
>
|
||||
${content}
|
||||
</div>`;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import "./workers";
|
||||
// they are defined, and cards need a provider to request their context from.
|
||||
import "./ha-embed-provider";
|
||||
import "./ha-embed-card";
|
||||
import "./ha-embed-section";
|
||||
import "./ha-embed-view";
|
||||
import "./ha-embed-dashboard";
|
||||
// For custom cards, which can't load them themselves. The built-in cards only
|
||||
// load ha-list-item-button with the map card. The full app loads ha-select
|
||||
// with the more info dialog.
|
||||
|
||||
+22
-141
@@ -1,139 +1,44 @@
|
||||
import { ContextEvent } from "@lit/context";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { css, html } from "lit";
|
||||
import { customElement } from "lit/decorators";
|
||||
import { createRef, ref } from "lit/directives/ref";
|
||||
import { consume } from "../../../src/common/decorators/consume";
|
||||
import { computeRTLDirection } from "../../../src/common/util/compute_rtl";
|
||||
import type { LovelaceCardConfig } from "../../../src/data/lovelace/config/card";
|
||||
import { handleAction } from "../../../src/panels/lovelace/common/handle-action";
|
||||
import { computeCardGridSize } from "../../../src/panels/lovelace/common/compute-card-grid-size";
|
||||
import "../../../src/panels/lovelace/cards/hui-card";
|
||||
import type { HuiCard } from "../../../src/panels/lovelace/cards/hui-card";
|
||||
import type { HomeAssistant } from "../../../src/types";
|
||||
import { embedHassContext } from "./context";
|
||||
import { readScriptData } from "./script-data";
|
||||
import { embedThemeStyles } from "./theme-styles";
|
||||
|
||||
const pageProvider = (): HTMLElement =>
|
||||
document.querySelector("ha-embed-provider") ??
|
||||
document.body.appendChild(document.createElement("ha-embed-provider"));
|
||||
|
||||
// Looks past shadow roots, so a card inside another component still finds
|
||||
// the provider around that component.
|
||||
const insideProvider = (element: Element): boolean => {
|
||||
let current: Element | null = element;
|
||||
|
||||
while (current) {
|
||||
if (current.closest("ha-embed-provider")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const root = current.getRootNode();
|
||||
current = root instanceof ShadowRoot ? root.host : null;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
import { EmbedElement } from "./embed-element";
|
||||
import type { ScriptObject } from "./script-data";
|
||||
import { embedElementStyles } from "./theme-styles";
|
||||
|
||||
/**
|
||||
* Renders a Lovelace card. The card uses the provider with the ID in
|
||||
* `provider`, else the closest provider around it, else the first provider on
|
||||
* the page. If the page has no provider, the card adds an empty one.
|
||||
* Renders a Lovelace card with the backend of a provider, see `EmbedElement`.
|
||||
*
|
||||
* The card takes the columns and rows it would take in a section, so cards
|
||||
* in an element with `display: grid` and 12 columns lay out like a section.
|
||||
* It also sets `--column-size` and `--row-size` on itself.
|
||||
*/
|
||||
@customElement("ha-embed-card")
|
||||
export class HaEmbedCard extends LitElement {
|
||||
/**
|
||||
* The card configuration. Also read from a JSON or YAML script child, see
|
||||
* `readScriptData`.
|
||||
*/
|
||||
@property({ type: Object }) public config?: LovelaceCardConfig;
|
||||
|
||||
/** The ID of the `ha-embed-provider` to use. */
|
||||
@property() public provider?: string;
|
||||
|
||||
@state()
|
||||
@consume({ context: embedHassContext, subscribe: true })
|
||||
private _hass?: HomeAssistant;
|
||||
|
||||
// A provider that is not an ancestor, which gets the context requests of the
|
||||
// card and its content. Context requests only reach ancestors by themselves.
|
||||
private _linkedProvider?: HTMLElement;
|
||||
|
||||
private _scriptRead = false;
|
||||
|
||||
export class HaEmbedCard extends EmbedElement<LovelaceCardConfig> {
|
||||
private _card = createRef<HuiCard>();
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.addEventListener("context-request", (ev) => {
|
||||
if (!this._linkedProvider) {
|
||||
return;
|
||||
}
|
||||
ev.stopPropagation();
|
||||
this._linkedProvider.dispatchEvent(
|
||||
new ContextEvent(
|
||||
ev.context,
|
||||
ev.contextTarget,
|
||||
ev.callback,
|
||||
ev.subscribe
|
||||
)
|
||||
);
|
||||
});
|
||||
// Cards fire their tap, hold and double tap actions for the app to handle
|
||||
this.addEventListener("hass-action", (ev) => {
|
||||
if (this._hass) {
|
||||
// The element that fired the action, so that fire-dom-event reaches
|
||||
// listeners inside custom cards, as in action-mixin
|
||||
const node = (ev.composedPath()[0] as HTMLElement | undefined) ?? this;
|
||||
handleAction(node, this._hass, ev.detail.config, ev.detail.action);
|
||||
}
|
||||
});
|
||||
// A card names its type
|
||||
protected isConfig(data: ScriptObject): data is LovelaceCardConfig {
|
||||
return "type" in data && typeof data.type === "string";
|
||||
}
|
||||
|
||||
public connectedCallback() {
|
||||
// Before super.connectedCallback(), which sends the context requests.
|
||||
this._linkedProvider = this.provider
|
||||
? (document.getElementById(this.provider) ?? undefined)
|
||||
: insideProvider(this)
|
||||
? undefined
|
||||
: pageProvider();
|
||||
super.connectedCallback();
|
||||
|
||||
// Only once, so that moving the card keeps a config set since
|
||||
if (this._scriptRead) {
|
||||
return;
|
||||
protected renderContent(hass: HomeAssistant) {
|
||||
if (!this.config) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
this._scriptRead = true;
|
||||
|
||||
const config = readScriptData(this) as LovelaceCardConfig | undefined;
|
||||
if (config) {
|
||||
this.config = config;
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this._hass || !this.config) {
|
||||
return nothing;
|
||||
}
|
||||
return html`<div
|
||||
class=${classMap({ theme: true, dark: this._hass.themes.darkMode })}
|
||||
dir=${computeRTLDirection(this._hass)}
|
||||
>
|
||||
<hui-card
|
||||
${ref(this._card)}
|
||||
.hass=${this._hass}
|
||||
.config=${this.config}
|
||||
.layout=${"grid"}
|
||||
@card-updated=${this._updateSize}
|
||||
@card-visibility-changed=${this._updateSize}
|
||||
></hui-card>
|
||||
</div>`;
|
||||
return html`<hui-card
|
||||
${ref(this._card)}
|
||||
.hass=${hass}
|
||||
.config=${this.config}
|
||||
.layout=${"grid"}
|
||||
@card-updated=${this._updateSize}
|
||||
@card-visibility-changed=${this._updateSize}
|
||||
></hui-card>`;
|
||||
}
|
||||
|
||||
protected updated() {
|
||||
@@ -163,7 +68,7 @@ export class HaEmbedCard extends LitElement {
|
||||
};
|
||||
|
||||
static styles = [
|
||||
embedThemeStyles,
|
||||
embedElementStyles,
|
||||
css`
|
||||
/* The sizes of a card in a section, see hui-grid-section */
|
||||
:host {
|
||||
@@ -176,9 +81,6 @@ export class HaEmbedCard extends LitElement {
|
||||
:host([full-width]) {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
:host([hidden]) {
|
||||
display: none;
|
||||
}
|
||||
:host([fit-rows]) .theme {
|
||||
height: calc(
|
||||
(var(--row-size, 1) * (var(--row-height) + var(--row-gap))) - var(
|
||||
@@ -186,27 +88,6 @@ export class HaEmbedCard extends LitElement {
|
||||
)
|
||||
);
|
||||
}
|
||||
/* The text styles the app sets on html and body, so that the card does
|
||||
not inherit the text styles of the page that embeds it. */
|
||||
.theme {
|
||||
color: var(--primary-text-color);
|
||||
font-family: var(--ha-font-family-body);
|
||||
font-size: var(--ha-font-size-m);
|
||||
font-weight: var(--ha-font-weight-body);
|
||||
line-height: normal;
|
||||
letter-spacing: normal;
|
||||
text-align: start;
|
||||
-moz-osx-font-smoothing: var(--ha-moz-osx-font-smoothing);
|
||||
-webkit-font-smoothing: var(--ha-font-smoothing);
|
||||
}
|
||||
/* What setDirectionStyles sets on the app for a right-to-left language,
|
||||
here only for the card */
|
||||
.theme[dir="rtl"] {
|
||||
--direction: rtl;
|
||||
--float-start: right;
|
||||
--float-end: left;
|
||||
--scale-direction: -1;
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html } from "lit";
|
||||
import { customElement } from "lit/decorators";
|
||||
import { createRef, ref } from "lit/directives/ref";
|
||||
import memoizeOne from "memoize-one";
|
||||
import type { HASSDomEvent } from "../../../src/common/dom/fire_event";
|
||||
import type {
|
||||
LovelaceConfig,
|
||||
LovelaceRawConfig,
|
||||
} from "../../../src/data/lovelace/config/types";
|
||||
import "../../../src/panels/lovelace/hui-root";
|
||||
import type { HomeAssistant } from "../../../src/types";
|
||||
import { EmbedLovelaceElement, isDashboardConfig } from "./lovelace";
|
||||
import type { ScriptObject } from "./script-data";
|
||||
|
||||
/**
|
||||
* Renders a dashboard, or a dashboard strategy, with its tabs, with the
|
||||
* backend of a provider, see `EmbedElement`. Each dashboard keeps its own
|
||||
* view in `view`, so switching tabs and following links to its views don't
|
||||
* change the page's URL. The dashboard scrolls inside the element, under its
|
||||
* toolbar.
|
||||
*/
|
||||
@customElement("ha-embed-dashboard")
|
||||
export class HaEmbedDashboard extends EmbedLovelaceElement<LovelaceRawConfig> {
|
||||
private _scroller = createRef<HTMLDivElement>();
|
||||
|
||||
// The route of hui-root, here without a page URL around it. A new
|
||||
// configuration gives a new route, as hui-root only looks up the view of
|
||||
// the path again when its route changes, and the views may have moved.
|
||||
private _route = memoizeOne(
|
||||
(view: string | undefined, _config: LovelaceConfig) => ({
|
||||
prefix: "",
|
||||
path: `/${view ?? ""}`,
|
||||
})
|
||||
);
|
||||
|
||||
protected get rawConfig() {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
protected isConfig(data: ScriptObject): data is LovelaceRawConfig {
|
||||
return isDashboardConfig(data);
|
||||
}
|
||||
|
||||
// The view shown, and the views before it, which the back button of a
|
||||
// subview without a `back_path` goes back through, as the browser's back
|
||||
// would in the app
|
||||
private _shownView?: string;
|
||||
|
||||
private _history: (string | undefined)[] = [];
|
||||
|
||||
// Going back, or a navigate action with `navigation_replace`, which
|
||||
// replaces the view shown rather than adding to the views before it
|
||||
private _skipHistory = false;
|
||||
|
||||
protected updated(changedProps: PropertyValues) {
|
||||
super.updated(changedProps);
|
||||
|
||||
if (this.view === this._shownView) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._shownView !== undefined) {
|
||||
if (!this._skipHistory) {
|
||||
this._history.push(this._shownView);
|
||||
}
|
||||
|
||||
this._scroller.value?.scrollTo({ top: 0 });
|
||||
}
|
||||
|
||||
this._skipHistory = false;
|
||||
this._shownView = this.view;
|
||||
}
|
||||
|
||||
protected navigateTo(path: string, replace?: boolean) {
|
||||
const view = this.viewOfPath(path);
|
||||
|
||||
if (view === undefined || this.isSameView(view, this.view)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._skipHistory = Boolean(replace);
|
||||
this.view = view;
|
||||
}
|
||||
|
||||
// The embedded attribute is in the template, so that hui-root has it when
|
||||
// it connects and skips the listeners on the page
|
||||
protected renderContent(hass: HomeAssistant) {
|
||||
if (!this._lovelace?.config.views.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return html`<div class="scroller" ${ref(this._scroller)}>
|
||||
<hui-root
|
||||
embedded
|
||||
no-edit
|
||||
.hass=${hass}
|
||||
.lovelace=${this._lovelace}
|
||||
.route=${this._route(this.view, this._lovelace.config)}
|
||||
.narrow=${this._narrow.value ?? false}
|
||||
@view-navigate=${this._viewNavigate}
|
||||
></hui-root>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
// A tab, or the back button of a subview, which goes to its `back_path`
|
||||
// when that is one of the dashboard's views, else to the view before it
|
||||
private _viewNavigate(ev: HASSDomEvent<HASSDomEvents["view-navigate"]>) {
|
||||
const view = this.viewOfPath(ev.detail.path);
|
||||
|
||||
if (!ev.detail.back) {
|
||||
if (view !== undefined) {
|
||||
this.view = view;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const target = view === undefined ? this._previousView() : view;
|
||||
|
||||
// Following a `back_path` goes back too, so the view it goes to leaves
|
||||
// the views before
|
||||
if (
|
||||
view !== undefined &&
|
||||
this.isSameView(this._history[this._history.length - 1], view)
|
||||
) {
|
||||
this._history.pop();
|
||||
}
|
||||
|
||||
if (!this.isSameView(target, this.view)) {
|
||||
this._skipHistory = true;
|
||||
this.view = target;
|
||||
}
|
||||
}
|
||||
|
||||
// The last view before that isn't the one shown, else the first view
|
||||
private _previousView(): string | undefined {
|
||||
while (this._history.length) {
|
||||
const previous = this._history.pop();
|
||||
|
||||
if (!this.isSameView(previous, this.view)) {
|
||||
return previous;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
static styles = [
|
||||
EmbedLovelaceElement.styles,
|
||||
css`
|
||||
/* Contained, so that the toolbar and background of hui-root, which are
|
||||
fixed to the window in the app, are fixed to the element */
|
||||
:host {
|
||||
height: 600px;
|
||||
contain: layout paint;
|
||||
}
|
||||
.theme,
|
||||
.scroller {
|
||||
height: 100%;
|
||||
}
|
||||
.scroller {
|
||||
overflow: auto;
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-embed-dashboard": HaEmbedDashboard;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { listenMediaQuery } from "../../../src/common/dom/media_query";
|
||||
import type { AreaRegistryEntry } from "../../../src/data/area/area_registry";
|
||||
import type { CalendarEventApiData } from "../../../src/data/calendar";
|
||||
import { reducedMotionContext } from "../../../src/data/context";
|
||||
import type { DeviceRegistryEntry } from "../../../src/data/device/device_registry";
|
||||
import type { EnergyInfo, EnergyPreferences } from "../../../src/data/energy";
|
||||
import { EMPTY_PREFERENCES } from "../../../src/data/energy";
|
||||
import type { EntityRegistryEntry } from "../../../src/data/entity/entity_registry";
|
||||
@@ -22,6 +23,8 @@ import {
|
||||
mockCalendarEvents,
|
||||
WORK_EVENTS,
|
||||
} from "../stubs/calendar";
|
||||
import type { DemoDevice } from "../stubs/device_registry";
|
||||
import { toDeviceRegistryEntry } from "../stubs/device_registry";
|
||||
import { extEntry, newEntry } from "../stubs/entity_registry";
|
||||
import { mockHistory } from "../stubs/history";
|
||||
import { mockIcons } from "../stubs/icons";
|
||||
@@ -40,6 +43,7 @@ import { readScriptData } from "./script-data";
|
||||
interface EmbedProviderData {
|
||||
entities?: EntityInput[];
|
||||
areas?: DemoArea[];
|
||||
devices?: DemoDevice[];
|
||||
calendars?: Record<string, CalendarEventApiData[]>;
|
||||
energy?: Partial<EnergyPreferences>;
|
||||
}
|
||||
@@ -54,8 +58,8 @@ const areaName = (areaId: string) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Holds a mocked Home Assistant backend for all `ha-embed-card` elements
|
||||
* inside it. Cards in the same provider share their entities.
|
||||
* Holds a mocked Home Assistant backend for all embed elements inside it.
|
||||
* Elements in the same provider share their entities.
|
||||
*/
|
||||
@customElement("ha-embed-provider")
|
||||
export class HaEmbedProvider extends LitElement {
|
||||
@@ -67,13 +71,19 @@ export class HaEmbedProvider extends LitElement {
|
||||
* All entities of the backend. Each change replaces all entities.
|
||||
* Also read from a JSON or YAML script child, see `readScriptData`. The
|
||||
* script holds either the list of entities or an object with `entities`,
|
||||
* `areas`, `calendars` and `energy`.
|
||||
* `areas`, `devices`, `calendars` and `energy`.
|
||||
*/
|
||||
@property({ type: Array }) public entities: EntityInput[] = [];
|
||||
|
||||
/** All areas. Without them, an area for each `area_id` of the entities. */
|
||||
/**
|
||||
* All areas. Without them, an area for each `area_id` of the entities and
|
||||
* devices.
|
||||
*/
|
||||
@property({ attribute: false }) public areas?: DemoArea[];
|
||||
|
||||
/** All devices, which entities reference with their `device_id`. */
|
||||
@property({ attribute: false }) public devices?: DemoDevice[];
|
||||
|
||||
/**
|
||||
* Events of calendar entities by entity ID. Calendars without events here
|
||||
* get sample events around today.
|
||||
@@ -155,7 +165,11 @@ export class HaEmbedProvider extends LitElement {
|
||||
hass.mockWS("config/area_registry/list", (_msg, currentHass) =>
|
||||
Object.values(currentHass.areas)
|
||||
);
|
||||
// The registry of the entities, without settings such as calendar colors
|
||||
hass.mockWS("config/device_registry/list", (_msg, currentHass) =>
|
||||
Object.values(currentHass.devices)
|
||||
);
|
||||
// The registry of the entities, with the options each entity sets, such
|
||||
// as timer presets. Other settings, such as calendar colors, are not set.
|
||||
const registryEntries = (currentHass: MockHomeAssistant) =>
|
||||
Object.values(currentHass.entities).map(
|
||||
(entity): EntityRegistryEntry => ({
|
||||
@@ -166,6 +180,9 @@ export class HaEmbedProvider extends LitElement {
|
||||
}),
|
||||
area_id: entity.area_id ?? null,
|
||||
device_id: entity.device_id ?? null,
|
||||
options:
|
||||
this.entities.find((item) => item.entity_id === entity.entity_id)
|
||||
?.options ?? null,
|
||||
})
|
||||
);
|
||||
hass.mockWS("config/entity_registry/list", (_msg, currentHass) =>
|
||||
@@ -222,6 +239,7 @@ export class HaEmbedProvider extends LitElement {
|
||||
} else if (data) {
|
||||
this.entities = data.entities ?? [];
|
||||
this.areas = data.areas;
|
||||
this.devices = data.devices;
|
||||
this.calendars = data.calendars;
|
||||
this.energy = data.energy;
|
||||
}
|
||||
@@ -238,14 +256,19 @@ export class HaEmbedProvider extends LitElement {
|
||||
this._applyColorScheme();
|
||||
}
|
||||
|
||||
if (changedProps.has("entities") || changedProps.has("areas")) {
|
||||
if (
|
||||
changedProps.has("entities") ||
|
||||
changedProps.has("areas") ||
|
||||
changedProps.has("devices")
|
||||
) {
|
||||
const devices = this.devices ?? [];
|
||||
const areas: DemoArea[] =
|
||||
this.areas ??
|
||||
[
|
||||
...new Set(
|
||||
this.entities
|
||||
.map((entity) => entity.area_id)
|
||||
.filter((areaId) => areaId !== undefined)
|
||||
[...this.entities, ...devices].flatMap((item) =>
|
||||
item.area_id === undefined ? [] : [item.area_id]
|
||||
)
|
||||
),
|
||||
].map((areaId) => ({ area_id: areaId, name: areaName(areaId) }));
|
||||
|
||||
@@ -253,11 +276,16 @@ export class HaEmbedProvider extends LitElement {
|
||||
areas.forEach((area) => {
|
||||
areasById[area.area_id] = toAreaRegistryEntry(area);
|
||||
});
|
||||
// Before the entities, so that their names can include the area
|
||||
this.hass.updateHass({ areas: areasById });
|
||||
const devicesById: Record<string, DeviceRegistryEntry> = {};
|
||||
devices.forEach((device) => {
|
||||
devicesById[device.id] = toDeviceRegistryEntry(device);
|
||||
});
|
||||
// Before the entities, so that their names can include the area and
|
||||
// device
|
||||
this.hass.updateHass({ areas: areasById, devices: devicesById });
|
||||
|
||||
// Entities that services changed keep their state when only the areas
|
||||
// change
|
||||
// or devices change
|
||||
if (changedProps.has("entities")) {
|
||||
this.hass.addEntities(this.entities, true);
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html } from "lit";
|
||||
import { customElement } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import type { HASSDomEvent } from "../../../src/common/dom/fire_event";
|
||||
import { normalizeSectionConfig } from "../../../src/data/lovelace/config/normalize";
|
||||
import type { LovelaceSectionRawConfig } from "../../../src/data/lovelace/config/section";
|
||||
import "../../../src/panels/lovelace/sections/hui-section";
|
||||
import {
|
||||
renderSectionContainer,
|
||||
sectionContainerStyles,
|
||||
} from "../../../src/panels/lovelace/sections/section-container";
|
||||
import type { HomeAssistant } from "../../../src/types";
|
||||
import { EmbedElement } from "./embed-element";
|
||||
import type { ScriptObject } from "./script-data";
|
||||
import { embedElementStyles } from "./theme-styles";
|
||||
|
||||
/**
|
||||
* Renders a dashboard section, or a section strategy, with the backend of a
|
||||
* provider, see `EmbedElement`. The section takes the width of the element.
|
||||
*/
|
||||
@customElement("ha-embed-section")
|
||||
export class HaEmbedSection extends EmbedElement<LovelaceSectionRawConfig> {
|
||||
// A title becomes a heading card, as on a dashboard
|
||||
private _normalizedConfig = memoizeOne(normalizeSectionConfig);
|
||||
|
||||
// A section has cards, sections inside it, a strategy that makes them, a
|
||||
// title, or the type of a custom section
|
||||
protected isConfig(data: ScriptObject): data is LovelaceSectionRawConfig {
|
||||
return (
|
||||
"cards" in data ||
|
||||
"sections" in data ||
|
||||
"strategy" in data ||
|
||||
"title" in data ||
|
||||
("type" in data && typeof data.type === "string")
|
||||
);
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues) {
|
||||
super.willUpdate(changedProps);
|
||||
|
||||
// The section that hid the element is gone, and the next one starts
|
||||
// visible without telling it
|
||||
if (changedProps.has("config") && !this.config) {
|
||||
this.hidden = false;
|
||||
}
|
||||
}
|
||||
|
||||
// In the container that draws the background of the section, as in a
|
||||
// sections view
|
||||
protected renderContent(hass: HomeAssistant) {
|
||||
if (!this.config) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const config = this._normalizedConfig(this.config);
|
||||
|
||||
return renderSectionContainer(
|
||||
hass,
|
||||
config,
|
||||
html`<hui-section
|
||||
.hass=${hass}
|
||||
.config=${config}
|
||||
@section-visibility-changed=${this._visibilityChanged}
|
||||
></hui-section>`
|
||||
);
|
||||
}
|
||||
|
||||
private _visibilityChanged(
|
||||
ev: HASSDomEvent<HASSDomEvents["section-visibility-changed"]>
|
||||
) {
|
||||
// Sections inside the section fire the same event
|
||||
if (ev.target !== ev.currentTarget) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.hidden = !ev.detail.value;
|
||||
}
|
||||
|
||||
static styles = [
|
||||
embedElementStyles,
|
||||
sectionContainerStyles,
|
||||
css`
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-embed-section": HaEmbedSection;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { css, html } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { keyed } from "lit/directives/keyed";
|
||||
import memoizeOne from "memoize-one";
|
||||
import type {
|
||||
LovelaceConfig,
|
||||
LovelaceRawConfig,
|
||||
} from "../../../src/data/lovelace/config/types";
|
||||
import type { LovelaceViewRawConfig } from "../../../src/data/lovelace/config/view";
|
||||
import "../../../src/panels/lovelace/views/hui-view";
|
||||
import "../../../src/panels/lovelace/views/hui-view-background";
|
||||
import "../../../src/panels/lovelace/views/hui-view-container";
|
||||
import type { HomeAssistant } from "../../../src/types";
|
||||
import {
|
||||
EmbedLovelaceElement,
|
||||
findViewIndex,
|
||||
isDashboardConfig,
|
||||
} from "./lovelace";
|
||||
import type { ScriptObject } from "./script-data";
|
||||
|
||||
/**
|
||||
* Renders a dashboard view, a view strategy, or one view of a dashboard or
|
||||
* dashboard strategy, with the backend of a provider, see `EmbedElement`.
|
||||
* `config` holds the view.
|
||||
*/
|
||||
@customElement("ha-embed-view")
|
||||
export class HaEmbedView extends EmbedLovelaceElement<LovelaceViewRawConfig> {
|
||||
/**
|
||||
* A dashboard configuration or dashboard strategy, to show its `view`
|
||||
* instead of `config`. Also read from the `dashboard` key of a script child,
|
||||
* next to `view`.
|
||||
*/
|
||||
@property({ type: Object }) public dashboard?: LovelaceRawConfig;
|
||||
|
||||
private _viewDashboard = memoizeOne(
|
||||
(view: LovelaceViewRawConfig): LovelaceConfig => ({ views: [view] })
|
||||
);
|
||||
|
||||
protected get rawConfig() {
|
||||
return this.dashboard ?? (this.config && this._viewDashboard(this.config));
|
||||
}
|
||||
|
||||
// A view strategy and a dashboard strategy both have a `strategy` key, so
|
||||
// a dashboard comes in its own key, which no view has
|
||||
protected isConfig(data: ScriptObject): data is LovelaceViewRawConfig {
|
||||
return !("dashboard" in data);
|
||||
}
|
||||
|
||||
protected setScriptData(data: ScriptObject) {
|
||||
if (!("dashboard" in data)) {
|
||||
super.setScriptData(data);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const { dashboard } = data;
|
||||
|
||||
if (
|
||||
typeof dashboard === "object" &&
|
||||
dashboard !== null &&
|
||||
isDashboardConfig(dashboard)
|
||||
) {
|
||||
this.dashboard = dashboard;
|
||||
}
|
||||
|
||||
if (
|
||||
"view" in data &&
|
||||
(typeof data.view === "string" || typeof data.view === "number")
|
||||
) {
|
||||
this.view ??= String(data.view);
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing for a dashboard without views, such as an empty strategy result.
|
||||
// The view's theme and background, or the dashboard's background, as in
|
||||
// hui-root. Each view gets its own hui-view, as there, so that a view
|
||||
// strategy still generating for the view before can't replace the cards of
|
||||
// this one.
|
||||
protected renderContent(hass: HomeAssistant) {
|
||||
const views = this._lovelace?.config.views;
|
||||
|
||||
if (!this._lovelace || !views?.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const index = findViewIndex(views, this.view);
|
||||
const viewConfig = views[index];
|
||||
|
||||
const background =
|
||||
viewConfig.background || this._lovelace.config.background;
|
||||
|
||||
return html`<hui-view-container .hass=${hass} .theme=${viewConfig.theme}>
|
||||
<hui-view-background .hass=${hass} .background=${background}>
|
||||
</hui-view-background>
|
||||
${keyed(
|
||||
viewConfig,
|
||||
html`<hui-view
|
||||
.hass=${hass}
|
||||
.lovelace=${this._lovelace}
|
||||
.index=${index}
|
||||
.narrow=${this._narrow.value ?? false}
|
||||
></hui-view>`
|
||||
)}
|
||||
</hui-view-container>`;
|
||||
}
|
||||
|
||||
// A fixed background stays inside the element. With a height set on the
|
||||
// element, a panel view fills it, and other views keep their own height.
|
||||
static styles = [
|
||||
EmbedLovelaceElement.styles,
|
||||
css`
|
||||
:host {
|
||||
contain: layout paint;
|
||||
}
|
||||
.theme,
|
||||
hui-view-container,
|
||||
hui-view {
|
||||
display: block;
|
||||
height: 100%;
|
||||
}
|
||||
/* The background sits below the view, above the element's own */
|
||||
hui-view-container {
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-embed-view": HaEmbedView;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import { ResizeController } from "@lit-labs/observers/resize-controller";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { css } from "lit";
|
||||
import { property, state } from "lit/decorators";
|
||||
import { normalizeLovelaceConfig } from "../../../src/data/lovelace/config/normalize";
|
||||
import type { LovelaceRawConfig } from "../../../src/data/lovelace/config/types";
|
||||
import { isStrategyDashboard } from "../../../src/data/lovelace/config/types";
|
||||
import type { LovelaceViewRawConfig } from "../../../src/data/lovelace/config/view";
|
||||
import {
|
||||
checkStrategyShouldRegenerate,
|
||||
generateLovelaceDashboardStrategy,
|
||||
} from "../../../src/panels/lovelace/strategies/get-strategy";
|
||||
import type { Lovelace } from "../../../src/panels/lovelace/types";
|
||||
import type { HomeAssistant } from "../../../src/types";
|
||||
import { EmbedElement } from "./embed-element";
|
||||
import type { ScriptObject } from "./script-data";
|
||||
import { embedElementStyles } from "./theme-styles";
|
||||
|
||||
// The width below which the app is narrow, see home-assistant-main
|
||||
const NARROW_WIDTH = 870;
|
||||
|
||||
/** The index of the view with this path or index, if there is one. */
|
||||
const viewIndex = (
|
||||
views: LovelaceViewRawConfig[],
|
||||
view: string
|
||||
): number | undefined => {
|
||||
const byPath = views.findIndex((item) => item.path === view);
|
||||
|
||||
if (byPath !== -1) {
|
||||
return byPath;
|
||||
}
|
||||
|
||||
const index = Number(view);
|
||||
|
||||
return Number.isInteger(index) && index >= 0 && index < views.length
|
||||
? index
|
||||
: undefined;
|
||||
};
|
||||
|
||||
/** Whether script data is a dashboard: its views, or a strategy for them. */
|
||||
export const isDashboardConfig = (
|
||||
data: ScriptObject
|
||||
): data is LovelaceRawConfig => "views" in data || "strategy" in data;
|
||||
|
||||
/** The index of the view with this path or index, else the first view. */
|
||||
export const findViewIndex = (
|
||||
views: LovelaceViewRawConfig[],
|
||||
view?: string
|
||||
): number => (view === undefined ? 0 : (viewIndex(views, view) ?? 0));
|
||||
|
||||
/**
|
||||
* The base of the embed elements that render a dashboard, or one of its
|
||||
* views. It generates dashboard strategies, again when the registries they
|
||||
* depend on change, and holds a dashboard that can't be edited or saved.
|
||||
*/
|
||||
export abstract class EmbedLovelaceElement<
|
||||
Config extends ScriptObject,
|
||||
> extends EmbedElement<Config> {
|
||||
/** The path or index of the view to show. Without it, the first view. */
|
||||
@property() public view?: string;
|
||||
|
||||
@state() protected _lovelace?: Lovelace;
|
||||
|
||||
// Narrow like the app at the same width, measured on the element because
|
||||
// it rarely takes the width of the page
|
||||
protected _narrow = new ResizeController(this, {
|
||||
callback: (entries) =>
|
||||
(entries[0]?.contentRect.width ?? NARROW_WIDTH) < NARROW_WIDTH,
|
||||
});
|
||||
|
||||
// The configuration of the dashboard in `_lovelace`, or being generated
|
||||
private _rawConfig?: LovelaceRawConfig;
|
||||
|
||||
// Counts the generations started, so that only the latest one is shown.
|
||||
// Generating again for changed registries keeps the same configuration.
|
||||
private _generation = 0;
|
||||
|
||||
// The backend at the last update, to tell what a strategy depends on changed
|
||||
private _previousHass?: HomeAssistant;
|
||||
|
||||
/** The dashboard to render. The same object until it changes. */
|
||||
protected abstract get rawConfig(): LovelaceRawConfig | undefined;
|
||||
|
||||
/**
|
||||
* The view of the dashboard a path goes to, relative like `batteries` or
|
||||
* with the dashboard like `/maintenance/batteries`, if it has that view.
|
||||
*/
|
||||
protected viewOfPath(path: string | undefined): string | undefined {
|
||||
const views = this._lovelace?.config.views;
|
||||
|
||||
const view = path
|
||||
? decodeURI(new URL(path, "http://embed/").pathname)
|
||||
.split("/")
|
||||
.filter(Boolean)
|
||||
.pop()
|
||||
: undefined;
|
||||
|
||||
return views && view !== undefined && viewIndex(views, view) !== undefined
|
||||
? view
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/** Whether two paths or indexes go to the same view of the dashboard. */
|
||||
protected isSameView(a?: string, b?: string): boolean {
|
||||
const views = this._lovelace?.config.views;
|
||||
|
||||
return views
|
||||
? findViewIndex(views, a) === findViewIndex(views, b)
|
||||
: a === b;
|
||||
}
|
||||
|
||||
// A path to one of the dashboard's views shows that view. Other paths leave
|
||||
// the dashboard where it is.
|
||||
protected navigateTo(path: string) {
|
||||
const view = this.viewOfPath(path);
|
||||
|
||||
if (view !== undefined) {
|
||||
this.view = view;
|
||||
}
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues) {
|
||||
super.willUpdate(changedProps);
|
||||
|
||||
const raw = this.rawConfig;
|
||||
const oldHass = this._previousHass;
|
||||
|
||||
this._previousHass = this._hass;
|
||||
|
||||
// Without a configuration, nothing is shown, and a generation still
|
||||
// running is dropped
|
||||
if (!raw) {
|
||||
if (this._rawConfig) {
|
||||
this._rawConfig = undefined;
|
||||
this._lovelace = undefined;
|
||||
this._generation++;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this._hass) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A strategy is only asked whether to generate again when the backend
|
||||
// changed, as in ha-panel-lovelace, not when the generated dashboard
|
||||
// arrives
|
||||
if (
|
||||
raw !== this._rawConfig ||
|
||||
(oldHass &&
|
||||
oldHass !== this._hass &&
|
||||
isStrategyDashboard(raw) &&
|
||||
this._hass.config.state === "RUNNING" &&
|
||||
checkStrategyShouldRegenerate(
|
||||
"dashboard",
|
||||
raw.strategy,
|
||||
oldHass,
|
||||
this._hass
|
||||
))
|
||||
) {
|
||||
this._rawConfig = raw;
|
||||
this._generate(raw, this._hass, ++this._generation);
|
||||
}
|
||||
}
|
||||
|
||||
private async _generate(
|
||||
raw: LovelaceRawConfig,
|
||||
hass: HomeAssistant,
|
||||
generation: number
|
||||
) {
|
||||
const generated = isStrategyDashboard(raw)
|
||||
? await generateLovelaceDashboardStrategy(raw, hass)
|
||||
: raw;
|
||||
|
||||
const config = normalizeLovelaceConfig(generated);
|
||||
|
||||
// A newer generation has started. A generated dashboard has its views,
|
||||
// rather than a strategy.
|
||||
if (generation !== this._generation || isStrategyDashboard(config)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._lovelace = {
|
||||
config,
|
||||
rawConfig: raw,
|
||||
editMode: false,
|
||||
urlPath: null,
|
||||
mode: "generated",
|
||||
locale: hass.locale,
|
||||
enableFullEditMode: () => undefined,
|
||||
saveConfig: async () => undefined,
|
||||
deleteConfig: async () => undefined,
|
||||
setEditMode: () => undefined,
|
||||
showToast: () => undefined,
|
||||
embedded: true,
|
||||
};
|
||||
}
|
||||
|
||||
// The background of a dashboard, and no insets for a notch or home bar
|
||||
static styles: CSSResultGroup = [
|
||||
embedElementStyles,
|
||||
css`
|
||||
:host {
|
||||
display: block;
|
||||
--app-safe-area-inset-top: 0px;
|
||||
--app-safe-area-inset-bottom: 0px;
|
||||
--app-safe-area-inset-left: 0px;
|
||||
--app-safe-area-inset-right: 0px;
|
||||
}
|
||||
.theme {
|
||||
position: relative;
|
||||
background: var(--primary-background-color);
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
@@ -15,3 +15,17 @@ export const readScriptData = (element: HTMLElement): unknown => {
|
||||
? load(script.textContent!)
|
||||
: JSON.parse(script.textContent!);
|
||||
};
|
||||
|
||||
/** The data of a script child that holds an object, such as a config. */
|
||||
export type ScriptObject = object;
|
||||
|
||||
/** The object in a script child, see `readScriptData`, if it holds one. */
|
||||
export const readScriptObject = (
|
||||
element: HTMLElement
|
||||
): ScriptObject | undefined => {
|
||||
const data = readScriptData(element);
|
||||
|
||||
return typeof data === "object" && data !== null && !Array.isArray(data)
|
||||
? data
|
||||
: undefined;
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { unsafeCSS } from "lit";
|
||||
import { css, unsafeCSS } from "lit";
|
||||
import { hex2rgb } from "../../../src/common/color/convert-color";
|
||||
import { darkColorVariables } from "../../../src/resources/theme/color";
|
||||
import { darkSemanticVariables } from "../../../src/resources/theme/semantic.globals";
|
||||
@@ -59,3 +59,37 @@ export const embedThemeStyles = unsafeCSS(
|
||||
scopeThemeStyles(themeStyles, ".theme") +
|
||||
`.theme.dark{${darkVariables.join("")}}`
|
||||
);
|
||||
|
||||
/**
|
||||
* The styles of every embed element: the theme, and the page styles of the
|
||||
* app, for the `.theme` wrapper of `EmbedElement`.
|
||||
*/
|
||||
export const embedElementStyles = [
|
||||
embedThemeStyles,
|
||||
css`
|
||||
:host([hidden]) {
|
||||
display: none;
|
||||
}
|
||||
/* The text styles the app sets on html and body, so that the content does
|
||||
not inherit the text styles of the page that embeds it. */
|
||||
.theme {
|
||||
color: var(--primary-text-color);
|
||||
font-family: var(--ha-font-family-body);
|
||||
font-size: var(--ha-font-size-m);
|
||||
font-weight: var(--ha-font-weight-body);
|
||||
line-height: normal;
|
||||
letter-spacing: normal;
|
||||
text-align: start;
|
||||
-moz-osx-font-smoothing: var(--ha-moz-osx-font-smoothing);
|
||||
-webkit-font-smoothing: var(--ha-font-smoothing);
|
||||
}
|
||||
/* What setDirectionStyles sets on the app for a right-to-left language,
|
||||
here only for the content */
|
||||
.theme[dir="rtl"] {
|
||||
--direction: rtl;
|
||||
--float-start: right;
|
||||
--float-end: left;
|
||||
--scale-direction: -1;
|
||||
}
|
||||
`,
|
||||
];
|
||||
@@ -108,15 +108,24 @@
|
||||
against a mocked backend in the browser. No Home Assistant server is
|
||||
necessary.
|
||||
</p>
|
||||
<p>There are two components:</p>
|
||||
<p>
|
||||
<code><ha-embed-provider></code> holds the mocked backend and its
|
||||
entities. These components render dashboard content with the backend of
|
||||
a provider:
|
||||
</p>
|
||||
<ul>
|
||||
<li><code><ha-embed-card></code> renders one card.</li>
|
||||
<li>
|
||||
<code><ha-embed-provider></code> holds the mocked backend and
|
||||
its entities.
|
||||
<code><ha-embed-section></code> renders one section, or a
|
||||
section strategy.
|
||||
</li>
|
||||
<li>
|
||||
<code><ha-embed-card></code> renders one card. It uses the
|
||||
backend of a provider.
|
||||
<code><ha-embed-view></code> renders one view, a view strategy,
|
||||
or one view of a dashboard.
|
||||
</li>
|
||||
<li>
|
||||
<code><ha-embed-dashboard></code> renders a dashboard, or a
|
||||
dashboard strategy, with its tabs.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
@@ -324,6 +333,193 @@
|
||||
</script><!-- htmlmin:ignore -->
|
||||
</ha-embed-card>
|
||||
</div>
|
||||
<p>
|
||||
The other components find their provider the same way, and take the
|
||||
same <code>provider</code> attribute.
|
||||
</p>
|
||||
|
||||
<h2>Sections</h2>
|
||||
<p>
|
||||
<code><ha-embed-section></code> renders a section the same way as
|
||||
in a sections view. The configuration is the same as in a dashboard,
|
||||
so headings span the top, and a <code>strategy</code> generates the
|
||||
section. The section takes the width of the component.
|
||||
</p>
|
||||
<pre><code><ha-embed-section>
|
||||
<script type="text/yaml">
|
||||
cards:
|
||||
- type: heading
|
||||
heading: Kitchen
|
||||
- type: tile
|
||||
entity: light.kitchen
|
||||
- type: tile
|
||||
entity: switch.kettle
|
||||
</script>
|
||||
</ha-embed-section></code></pre>
|
||||
<ha-embed-provider>
|
||||
<!-- htmlmin:ignore --><script type="text/yaml">
|
||||
entities:
|
||||
- entity_id: light.kitchen_ceiling
|
||||
state: "on"
|
||||
device_id: kitchen_ceiling
|
||||
attributes:
|
||||
friendly_name: Ceiling
|
||||
supported_color_modes: [brightness]
|
||||
color_mode: brightness
|
||||
brightness: 200
|
||||
- entity_id: switch.kettle
|
||||
state: "off"
|
||||
area_id: kitchen
|
||||
attributes:
|
||||
friendly_name: Kettle
|
||||
device_class: outlet
|
||||
- entity_id: sensor.kitchen_temperature
|
||||
state: "21.4"
|
||||
area_id: kitchen
|
||||
attributes:
|
||||
friendly_name: Kitchen temperature
|
||||
device_class: temperature
|
||||
state_class: measurement
|
||||
unit_of_measurement: °C
|
||||
devices:
|
||||
- id: kitchen_ceiling
|
||||
name: Kitchen ceiling light
|
||||
manufacturer: Acme
|
||||
model: Smart bulb
|
||||
area_id: kitchen
|
||||
</script><!-- htmlmin:ignore -->
|
||||
<div class="single">
|
||||
<ha-embed-section>
|
||||
<!-- htmlmin:ignore --><script type="text/yaml">
|
||||
cards:
|
||||
- type: heading
|
||||
heading: Kitchen
|
||||
- type: tile
|
||||
entity: light.kitchen_ceiling
|
||||
tap_action:
|
||||
action: toggle
|
||||
- type: tile
|
||||
entity: switch.kettle
|
||||
tap_action:
|
||||
action: toggle
|
||||
- type: tile
|
||||
entity: sensor.kitchen_temperature
|
||||
grid_options:
|
||||
columns: 12
|
||||
</script><!-- htmlmin:ignore -->
|
||||
</ha-embed-section>
|
||||
</div>
|
||||
</ha-embed-provider>
|
||||
|
||||
<h2>Views</h2>
|
||||
<p>
|
||||
<code><ha-embed-view></code> renders a view, with its badges and
|
||||
layout. A <code>strategy</code> generates the view. Give the component
|
||||
the width the view needs: masonry and sidebar views pick their columns
|
||||
from the width of the page, not the component.
|
||||
</p>
|
||||
<pre><code><ha-embed-view>
|
||||
<script type="text/yaml">
|
||||
type: sections
|
||||
badges:
|
||||
- entity: sensor.outside_temperature
|
||||
sections:
|
||||
- cards: …
|
||||
</script>
|
||||
</ha-embed-view></code></pre>
|
||||
<p>
|
||||
To show one view of a dashboard, or of a dashboard strategy, put the
|
||||
dashboard in <code>dashboard</code> and the path or index of the view
|
||||
in <code>view</code>. Without <code>view</code>, the first view shows.
|
||||
</p>
|
||||
<pre><code><ha-embed-view>
|
||||
<script type="text/yaml">
|
||||
dashboard:
|
||||
strategy:
|
||||
type: custom:my-dashboard
|
||||
view: overview
|
||||
</script>
|
||||
</ha-embed-view></code></pre>
|
||||
<ha-embed-view provider="shared">
|
||||
<!-- htmlmin:ignore --><script type="text/yaml">
|
||||
type: sections
|
||||
max_columns: 2
|
||||
badges:
|
||||
- entity: sensor.outside_temperature
|
||||
sections:
|
||||
- cards:
|
||||
- type: heading
|
||||
heading: Living room
|
||||
- type: tile
|
||||
entity: light.living_room
|
||||
tap_action:
|
||||
action: toggle
|
||||
- type: tile
|
||||
entity: switch.coffee_maker
|
||||
tap_action:
|
||||
action: toggle
|
||||
- cards:
|
||||
- type: heading
|
||||
heading: Hallway
|
||||
- type: thermostat
|
||||
entity: climate.hallway
|
||||
</script><!-- htmlmin:ignore -->
|
||||
</ha-embed-view>
|
||||
|
||||
<h2>Dashboards</h2>
|
||||
<p>
|
||||
<code><ha-embed-dashboard></code> renders a dashboard with its
|
||||
tabs. A <code>strategy</code> generates the dashboard. Each dashboard
|
||||
keeps its own tab, so switching tabs does not change the address of
|
||||
your page. The dashboard scrolls inside the component, under its
|
||||
toolbar. The component is 600 pixels high; set its
|
||||
<code>height</code> to change that. Set <code>view</code> to the path
|
||||
or index of the first view to show.
|
||||
</p>
|
||||
<pre><code><ha-embed-dashboard style="height: 480px">
|
||||
<script type="text/yaml">
|
||||
views:
|
||||
- title: Home
|
||||
path: home
|
||||
cards: …
|
||||
- title: Climate
|
||||
path: climate
|
||||
cards: …
|
||||
</script>
|
||||
</ha-embed-dashboard></code></pre>
|
||||
<ha-embed-dashboard provider="shared" style="height: 480px">
|
||||
<!-- htmlmin:ignore --><script type="text/yaml">
|
||||
views:
|
||||
- title: Home
|
||||
path: home
|
||||
type: sections
|
||||
max_columns: 2
|
||||
sections:
|
||||
- cards:
|
||||
- type: heading
|
||||
heading: Living room
|
||||
- type: tile
|
||||
entity: light.living_room
|
||||
tap_action:
|
||||
action: toggle
|
||||
- type: tile
|
||||
entity: switch.coffee_maker
|
||||
tap_action:
|
||||
action: toggle
|
||||
- cards:
|
||||
- type: heading
|
||||
heading: Outside
|
||||
- type: tile
|
||||
entity: sensor.outside_temperature
|
||||
- title: Climate
|
||||
path: climate
|
||||
type: sections
|
||||
sections:
|
||||
- cards:
|
||||
- type: thermostat
|
||||
entity: climate.hallway
|
||||
</script><!-- htmlmin:ignore -->
|
||||
</ha-embed-dashboard>
|
||||
|
||||
<h2>Light and dark mode</h2>
|
||||
<p>
|
||||
@@ -375,7 +571,7 @@ provider.entities = Object.values(provider.hass.states).map((entity) =>
|
||||
<code>provider.hass.states</code>.
|
||||
</p>
|
||||
|
||||
<h2>Areas, calendars and energy</h2>
|
||||
<h2>Areas, devices, calendars and energy</h2>
|
||||
<p>
|
||||
Some cards need data that is not an entity. To set it, put an object in
|
||||
the script tag of the provider instead of the list. The object has the
|
||||
@@ -385,7 +581,15 @@ provider.entities = Object.values(provider.hass.states).map((entity) =>
|
||||
<li>
|
||||
<code>areas</code>: a list of areas, each with an
|
||||
<code>area_id</code> and a <code>name</code>. Without it, each
|
||||
<code>area_id</code> of the entities becomes an area.
|
||||
<code>area_id</code> of the entities and devices becomes an area.
|
||||
</li>
|
||||
<li>
|
||||
<code>devices</code>: a list of devices, each with an
|
||||
<code>id</code> and a <code>name</code>, and optionally a
|
||||
<code>manufacturer</code>, <code>model</code> and
|
||||
<code>area_id</code>. Entities belong to a device with their
|
||||
<code>device_id</code>, and cards and strategies then find the
|
||||
device and its name.
|
||||
</li>
|
||||
<li>
|
||||
<code>calendars</code>: the events of calendar entities, by entity
|
||||
@@ -679,14 +883,92 @@ customElements.define("embed-demo-custom-card", EmbedDemoCustomCard);</code></pr
|
||||
<td>Attribute and property</td>
|
||||
<td>
|
||||
The ID of the provider to use. Without it, the card uses the
|
||||
provider around it, else the first provider on the page.
|
||||
provider around it, else the first provider on the page. The other
|
||||
components take it too.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<h3><code><ha-embed-section></code></h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>config</code></td>
|
||||
<td>Attribute and property</td>
|
||||
<td>
|
||||
The section configuration or section strategy, the same as in a
|
||||
dashboard. A JSON or YAML script child sets the first
|
||||
configuration.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<h3><code><ha-embed-view></code></h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>config</code></td>
|
||||
<td>Attribute and property</td>
|
||||
<td>
|
||||
The view configuration or view strategy, the same as in a
|
||||
dashboard. A JSON or YAML script child sets the first
|
||||
configuration.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>dashboard</code></td>
|
||||
<td>Attribute and property</td>
|
||||
<td>
|
||||
A dashboard configuration or dashboard strategy, to show one of its
|
||||
views instead of <code>config</code>. A script child with a
|
||||
<code>dashboard</code> key, and optionally <code>view</code>, sets
|
||||
it.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>view</code></td>
|
||||
<td>Attribute and property</td>
|
||||
<td>
|
||||
The path or index of the view of <code>dashboard</code> to show.
|
||||
Without it, the first view.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<h3><code><ha-embed-dashboard></code></h3>
|
||||
<table>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>config</code></td>
|
||||
<td>Attribute and property</td>
|
||||
<td>
|
||||
The dashboard configuration or dashboard strategy. A JSON or YAML
|
||||
script child sets the first configuration.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>view</code></td>
|
||||
<td>Attribute and property</td>
|
||||
<td>
|
||||
The path or index of the first view to show. Without it, the first
|
||||
view.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p>
|
||||
The mocked backend knows the actions of lights, switches, climate,
|
||||
covers, fans, locks, media players, and more. Actions that open dialogs,
|
||||
such as <code>more-info</code>, do nothing.
|
||||
such as <code>more-info</code>, do nothing. Dashboards can't be edited,
|
||||
and their toolbar only shows their tabs.
|
||||
</p>
|
||||
</main>
|
||||
<script>
|
||||
|
||||
@@ -1,6 +1,60 @@
|
||||
import type { DeviceRegistryEntry } from "../../../src/data/device/device_registry";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
/** The fields of a device that the demo devices leave at their default. */
|
||||
export const baseDevice: Omit<
|
||||
DeviceRegistryEntry,
|
||||
| "id"
|
||||
| "name"
|
||||
| "manufacturer"
|
||||
| "model"
|
||||
| "config_entries"
|
||||
| "primary_config_entry"
|
||||
| "entry_type"
|
||||
> = {
|
||||
config_entries_subentries: {},
|
||||
connections: [],
|
||||
identifiers: [],
|
||||
model_id: null,
|
||||
labels: [],
|
||||
sw_version: null,
|
||||
hw_version: null,
|
||||
serial_number: null,
|
||||
via_device_id: null,
|
||||
area_id: null,
|
||||
name_by_user: null,
|
||||
disabled_by: null,
|
||||
configuration_url: null,
|
||||
parent_device_id: null,
|
||||
created_at: 0,
|
||||
modified_at: 0,
|
||||
};
|
||||
|
||||
export interface DemoDevice {
|
||||
id: string;
|
||||
name: string;
|
||||
manufacturer?: string;
|
||||
model?: string;
|
||||
area_id?: string;
|
||||
via_device_id?: string;
|
||||
entry_type?: "service";
|
||||
}
|
||||
|
||||
export const toDeviceRegistryEntry = (
|
||||
device: DemoDevice
|
||||
): DeviceRegistryEntry => ({
|
||||
...baseDevice,
|
||||
id: device.id,
|
||||
name: device.name,
|
||||
manufacturer: device.manufacturer ?? null,
|
||||
model: device.model ?? null,
|
||||
area_id: device.area_id ?? null,
|
||||
via_device_id: device.via_device_id ?? null,
|
||||
entry_type: device.entry_type ?? null,
|
||||
config_entries: [],
|
||||
primary_config_entry: null,
|
||||
});
|
||||
|
||||
export const mockDeviceRegistry = (
|
||||
hass: MockHomeAssistant,
|
||||
data: DeviceRegistryEntry[] = []
|
||||
|
||||
@@ -1,24 +1,6 @@
|
||||
import type { DeviceRegistryEntry } from "../../../src/data/device/device_registry";
|
||||
import { connectivityDevices } from "./connectivity/fixtures";
|
||||
|
||||
const baseDevice = {
|
||||
config_entries_subentries: {},
|
||||
connections: [] as [string, string][],
|
||||
identifiers: [] as [string, string][],
|
||||
model_id: null,
|
||||
labels: [] as string[],
|
||||
sw_version: null,
|
||||
hw_version: null,
|
||||
serial_number: null,
|
||||
via_device_id: null,
|
||||
area_id: null,
|
||||
name_by_user: null,
|
||||
disabled_by: null,
|
||||
configuration_url: null,
|
||||
parent_device_id: null,
|
||||
created_at: 0,
|
||||
modified_at: 0,
|
||||
};
|
||||
import { baseDevice } from "./device_registry";
|
||||
|
||||
export const demoDevices: DeviceRegistryEntry[] = [
|
||||
{
|
||||
|
||||
@@ -97,6 +97,14 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
stat_consumption: "sensor.water_garden",
|
||||
},
|
||||
],
|
||||
device_consumption_gas: [
|
||||
{
|
||||
stat_consumption: "sensor.gas_kitchen",
|
||||
},
|
||||
{
|
||||
stat_consumption: "sensor.gas_heat_pump",
|
||||
},
|
||||
],
|
||||
}));
|
||||
hass.mockWS("energy/info", (): EnergyInfo => ({
|
||||
cost_sensors: {},
|
||||
@@ -106,6 +114,7 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
energy_sources: Array.from({ length: 6 }, () => []),
|
||||
device_consumption: Array.from({ length: 6 }, () => []),
|
||||
device_consumption_water: Array.from({ length: 2 }, () => []),
|
||||
device_consumption_gas: Array.from({ length: 2 }, () => []),
|
||||
}));
|
||||
hass.mockWS(
|
||||
"energy/fossil_energy_consumption",
|
||||
|
||||
@@ -160,6 +160,26 @@ export const energyEntities = () =>
|
||||
unit_of_measurement: "L",
|
||||
},
|
||||
},
|
||||
"sensor.gas_kitchen": {
|
||||
entity_id: "sensor.gas_kitchen",
|
||||
state: "100",
|
||||
attributes: {
|
||||
friendly_name: "Gas kitchen",
|
||||
unit_of_measurement: "m³",
|
||||
device_class: "gas",
|
||||
state_class: "total_increasing",
|
||||
},
|
||||
},
|
||||
"sensor.gas_heat_pump": {
|
||||
entity_id: "sensor.gas_heat_pump",
|
||||
state: "500",
|
||||
attributes: {
|
||||
friendly_name: "Gas heat pump",
|
||||
unit_of_measurement: "m³",
|
||||
device_class: "gas",
|
||||
state_class: "total_increasing",
|
||||
},
|
||||
},
|
||||
"sensor.energy_car": {
|
||||
entity_id: "sensor.energy_car",
|
||||
state: "4",
|
||||
|
||||
@@ -158,6 +158,24 @@ const statisticsFunctions: Record<
|
||||
(bucketStart, bucketEnd) =>
|
||||
(20 * (bucketEnd.getTime() - bucketStart.getTime())) / 3600000
|
||||
),
|
||||
"sensor.gas_kitchen": (_id, start, end, period = "hour") =>
|
||||
generateSumStatistics(
|
||||
start,
|
||||
end,
|
||||
period,
|
||||
100,
|
||||
(bucketStart, bucketEnd) =>
|
||||
(0.1 * (bucketEnd.getTime() - bucketStart.getTime())) / 3600000
|
||||
),
|
||||
"sensor.gas_heat_pump": (_id, start, end, period = "hour") =>
|
||||
generateSumStatistics(
|
||||
start,
|
||||
end,
|
||||
period,
|
||||
500,
|
||||
(bucketStart, bucketEnd) =>
|
||||
(0.6 * (bucketEnd.getTime() - bucketStart.getTime())) / 3600000
|
||||
),
|
||||
"sensor.energy_consumption_tarif_1": (
|
||||
_id: string,
|
||||
start: Date,
|
||||
|
||||
@@ -301,6 +301,14 @@ export default tseslint.config(
|
||||
globals: globals.node,
|
||||
},
|
||||
},
|
||||
{
|
||||
// Published as native ESM, where package subpath imports such as
|
||||
// "lit/decorators.js" need their extension.
|
||||
files: ["packages/*/src/**/*.ts"],
|
||||
rules: {
|
||||
"import-x/extensions": ["error", "ignorePackages", { ts: "never" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
plugins: {
|
||||
html,
|
||||
|
||||
@@ -81,6 +81,10 @@ export default [
|
||||
header: "Feedback and status",
|
||||
pages: ["ha-alert", "ha-spinner", "ha-tip", "ha-bar", "ha-gauge"],
|
||||
},
|
||||
{
|
||||
header: "Charts",
|
||||
pages: ["state-history-charts", "statistics-chart"],
|
||||
},
|
||||
{
|
||||
header: "Labels and text",
|
||||
pages: ["ha-badge", "ha-label-badge", "ha-chips", "ha-marquee-text"],
|
||||
|
||||
@@ -4,7 +4,7 @@ title: "Our story"
|
||||
|
||||
## Open source home automation that puts local control and privacy first
|
||||
|
||||
Home Assistant is a free and open-source software for home automation that is designed to be the central control system for smart home devices with a focus on local control and privacy. It can be accessed via a web-based user interface, via apps for Android and iOS, or using voice commands via a supported virtual assistant like Google Assistant and Amazon Alexa.
|
||||
Home Assistant is a free and open-source software for home automation that is designed to be the central control system for smart home devices with a focus on local control and privacy. It can be accessed via a web-based user interface, via apps for Android and iOS, or using voice commands via a supported virtual assistant like Google Home and Amazon Alexa.
|
||||
|
||||
IoT devices and services are supported by modular support for controlling proprietary ecosystems if they provide public access via an Open API for third-party integrations and protocols like Bluetooth, MQTT, Zigbee, and Z-Wave, After the Home Assistant software application is installed as a computer appliance it will act as a central control system for home automation. Information from all entities it sees can be used and controlled from within scripts trigger automations using scheduling and "blueprint" subroutines, e.g. for controlling lighting, climate, entertainment systems, and appliances.
|
||||
|
||||
@@ -36,6 +36,6 @@ Durability for the Open Home means that devices are designed and built to keep w
|
||||
|
||||
The project was started as a Python application by Paulus Schoutsen in September 2013 and first published publicly on GitHub in November 2013. In July 2017, a managed operating system called Hass.io was initially introduced to make it easier use to use Home Assistant on single-board computers like the Raspberry Pi series. Its bundled "supervisor" management system allowed users to manage, backup, and update the local installation and introduced the option to extend the functionality of the software with add-ons.
|
||||
|
||||
An optional subscription service was introduced in December 2017 for $5/month to solve the complexities associated with secured remote access, as well as linking to Amazon Alexa and Google Assistant. Nabu Casa, Inc. was formed in September 2018 to take over the subscription service. The company's funding is based solely on revenue from the subscription service. It is used to finance the project's infrastructure and to pay for full-time employees contributing to the project.
|
||||
An optional subscription service was introduced in December 2017 for $5/month to solve the complexities associated with secured remote access, as well as linking to Amazon Alexa and Google Home. Nabu Casa, Inc. was formed in September 2018 to take over the subscription service. The company's funding is based solely on revenue from the subscription service. It is used to finance the project's infrastructure and to pay for full-time employees contributing to the project.
|
||||
|
||||
In January 2020, branding was adjusted to make it easier to refer to different parts of the project. The main piece of software was renamed to Home Assistant Core, while the full suite of software with the embedded operating system and bundled "supervisor" management system was renamed to Home Assistant.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
title: History charts
|
||||
subtitle: State history as timelines and line charts.
|
||||
---
|
||||
|
||||
`<state-history-charts>` renders the state history of entities: a timeline for entities with text states, and a line chart per unit for numeric ones. It is used by the history panel, the history graph card and the more-info history. The data below is generated, so the charts work without a backend.
|
||||
@@ -0,0 +1,211 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import "../../../../src/components/chart/state-history-charts";
|
||||
import "../../../../src/components/ha-card";
|
||||
import type {
|
||||
HistoryResult,
|
||||
LineChartState,
|
||||
TimelineState,
|
||||
} from "../../../../src/data/history";
|
||||
import { provideHass } from "../../../../src/fake_data/provide_hass";
|
||||
import type { HomeAssistant } from "../../../../src/types";
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
const HOURS = 48;
|
||||
|
||||
const END = new Date();
|
||||
END.setMinutes(0, 0, 0);
|
||||
const START = new Date(END.getTime() - HOURS * HOUR);
|
||||
|
||||
const ENTITIES = [
|
||||
{
|
||||
entity_id: "sensor.outdoor_temperature",
|
||||
state: "12.4",
|
||||
attributes: {
|
||||
friendly_name: "Outdoor temperature",
|
||||
device_class: "temperature",
|
||||
state_class: "measurement",
|
||||
unit_of_measurement: "°C",
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "light.living_room",
|
||||
state: "on",
|
||||
attributes: { friendly_name: "Living room light" },
|
||||
},
|
||||
{
|
||||
entity_id: "binary_sensor.front_door",
|
||||
state: "off",
|
||||
attributes: { friendly_name: "Front door", device_class: "door" },
|
||||
},
|
||||
];
|
||||
|
||||
const temperatureStates = (): LineChartState[] =>
|
||||
Array.from({ length: HOURS * 2 }, (_, index) => {
|
||||
const time = START.getTime() + (index * HOUR) / 2;
|
||||
const hourOfDay = new Date(time).getHours();
|
||||
const value =
|
||||
10 +
|
||||
4 * Math.sin(((hourOfDay - 9) / 24) * 2 * Math.PI) +
|
||||
0.5 * Math.sin(time / HOUR);
|
||||
return {
|
||||
state: value.toFixed(1),
|
||||
last_changed: time,
|
||||
};
|
||||
});
|
||||
|
||||
const toggleStates = (
|
||||
onHours: [number, number][],
|
||||
onLabel: string,
|
||||
offLabel: string
|
||||
): TimelineState[] => {
|
||||
const on = { state: "on", state_localize: onLabel };
|
||||
const off = { state: "off", state_localize: offLabel };
|
||||
const states: TimelineState[] = [{ ...off, last_changed: START.getTime() }];
|
||||
onHours.forEach(([from, to]) => {
|
||||
states.push(
|
||||
{ ...on, last_changed: START.getTime() + from * HOUR },
|
||||
{ ...off, last_changed: START.getTime() + to * HOUR }
|
||||
);
|
||||
});
|
||||
return states;
|
||||
};
|
||||
|
||||
const HISTORY: HistoryResult = {
|
||||
line: [
|
||||
{
|
||||
unit: "°C",
|
||||
device_class: "temperature",
|
||||
identifier: "temperature",
|
||||
data: [
|
||||
{
|
||||
domain: "sensor",
|
||||
name: "Outdoor temperature",
|
||||
entity_id: "sensor.outdoor_temperature",
|
||||
states: temperatureStates(),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
timeline: [
|
||||
{
|
||||
name: "Living room light",
|
||||
entity_id: "light.living_room",
|
||||
data: toggleStates(
|
||||
[
|
||||
[6, 8],
|
||||
[18, 23],
|
||||
[30, 32],
|
||||
[42, 47],
|
||||
],
|
||||
"On",
|
||||
"Off"
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "Front door",
|
||||
entity_id: "binary_sensor.front_door",
|
||||
data: toggleStates(
|
||||
[
|
||||
[7.5, 7.6],
|
||||
[17, 17.2],
|
||||
[31.5, 31.6],
|
||||
[41, 41.1],
|
||||
],
|
||||
"Open",
|
||||
"Closed"
|
||||
),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const LIGHT_ONLY: HistoryResult = {
|
||||
line: [],
|
||||
timeline: [HISTORY.timeline[0]],
|
||||
};
|
||||
|
||||
interface Example {
|
||||
title: string;
|
||||
description: string;
|
||||
history: HistoryResult;
|
||||
showNames?: boolean;
|
||||
insideLabels?: boolean;
|
||||
syncCharts?: boolean;
|
||||
}
|
||||
|
||||
const EXAMPLES: Example[] = [
|
||||
{
|
||||
title: "Names in a column",
|
||||
description:
|
||||
"The default layout, like the history graph card: timeline names on the left and a line chart for each unit.",
|
||||
history: HISTORY,
|
||||
},
|
||||
{
|
||||
title: "Names inside the timeline, synced zoom",
|
||||
description:
|
||||
"Like the history panel: names sit under each timeline bar, and zooming one chart zooms all of them.",
|
||||
history: HISTORY,
|
||||
insideLabels: true,
|
||||
syncCharts: true,
|
||||
},
|
||||
{
|
||||
title: "Single entity without names",
|
||||
description:
|
||||
"Like the more-info dialog, where the entity is already known.",
|
||||
history: LIGHT_ONLY,
|
||||
showNames: false,
|
||||
},
|
||||
];
|
||||
|
||||
@customElement("demo-components-state-history-charts")
|
||||
export class DemoStateHistoryCharts extends LitElement {
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProps);
|
||||
const hass = provideHass(this);
|
||||
hass.updateTranslations(null, "en");
|
||||
hass.addEntities(ENTITIES);
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.hass) {
|
||||
return nothing;
|
||||
}
|
||||
return EXAMPLES.map(
|
||||
(example) => html`
|
||||
<ha-card header=${example.title}>
|
||||
<div class="card-content">
|
||||
<p>${example.description}</p>
|
||||
<state-history-charts
|
||||
.historyData=${example.history}
|
||||
.startTime=${START}
|
||||
.endTime=${END}
|
||||
.showNames=${example.showNames ?? true}
|
||||
.insideLabels=${example.insideLabels ?? false}
|
||||
.syncCharts=${example.syncCharts ?? false}
|
||||
.clickForMoreInfo=${false}
|
||||
></state-history-charts>
|
||||
</div>
|
||||
</ha-card>
|
||||
`
|
||||
);
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
ha-card {
|
||||
max-width: 800px;
|
||||
margin: 24px auto;
|
||||
}
|
||||
p {
|
||||
margin-top: 0;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"demo-components-state-history-charts": DemoStateHistoryCharts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
title: Statistics chart
|
||||
subtitle: Long-term statistics as a bar or line chart.
|
||||
---
|
||||
|
||||
`<statistics-chart>` renders long-term statistics from the recorder. It is used by the statistics graph card, the more-info history and the statistics developer tools. The data below is generated, so the charts work without a backend.
|
||||
@@ -0,0 +1,212 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import "../../../../src/components/chart/statistics-chart";
|
||||
import "../../../../src/components/ha-card";
|
||||
import type {
|
||||
Statistics,
|
||||
StatisticsMetaData,
|
||||
StatisticType,
|
||||
StatisticValue,
|
||||
} from "../../../../src/data/recorder";
|
||||
import { StatisticMeanType } from "../../../../src/data/recorder";
|
||||
import { provideHass } from "../../../../src/fake_data/provide_hass";
|
||||
import type { HomeAssistant } from "../../../../src/types";
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
const HOURS = 48;
|
||||
|
||||
const END = new Date();
|
||||
END.setMinutes(0, 0, 0);
|
||||
const START = new Date(END.getTime() - HOURS * HOUR);
|
||||
|
||||
const round = (value: number, digits: number) =>
|
||||
Math.round(value * 10 ** digits) / 10 ** digits;
|
||||
|
||||
const hourlyValues = (
|
||||
compute: (start: number) => Partial<StatisticValue>
|
||||
): StatisticValue[] =>
|
||||
Array.from({ length: HOURS }, (_, hour) => {
|
||||
const start = START.getTime() + hour * HOUR;
|
||||
return { start, end: start + HOUR, ...compute(start) };
|
||||
});
|
||||
|
||||
const energyValues = (dayUse: number, eveningUse: number) => {
|
||||
let sum = 0;
|
||||
return hourlyValues((start) => {
|
||||
const hourOfDay = new Date(start).getHours();
|
||||
const base = hourOfDay < 7 ? 0.1 : hourOfDay < 18 ? dayUse : eveningUse;
|
||||
const change = round(base + 0.2 * Math.abs(Math.sin(start / HOUR)), 2);
|
||||
sum += change;
|
||||
return { change, sum: round(sum, 2) };
|
||||
});
|
||||
};
|
||||
|
||||
const temperatureValues = (average: number, swing: number) =>
|
||||
hourlyValues((start) => {
|
||||
const hourOfDay = new Date(start).getHours();
|
||||
const mean =
|
||||
average +
|
||||
swing * Math.sin(((hourOfDay - 9) / 24) * 2 * Math.PI) +
|
||||
0.3 * Math.sin(start / HOUR);
|
||||
return {
|
||||
mean: round(mean, 1),
|
||||
min: round(mean - 0.4, 1),
|
||||
max: round(mean + 0.4, 1),
|
||||
};
|
||||
});
|
||||
|
||||
const HEAT_PUMP_ID = "sensor.heat_pump_energy";
|
||||
const LIGHTING_ID = "sensor.lighting_energy";
|
||||
const LIVING_ROOM_ID = "sensor.living_room_temperature";
|
||||
const BEDROOM_ID = "sensor.bedroom_temperature";
|
||||
|
||||
const HEAT_PUMP = energyValues(0.4, 1.2);
|
||||
const LIGHTING = energyValues(0.05, 0.3);
|
||||
const LIVING_ROOM = temperatureValues(21, 1.5);
|
||||
const BEDROOM = temperatureValues(18.5, 1);
|
||||
|
||||
const energyMetadata = (id: string, name: string): StatisticsMetaData => ({
|
||||
statistic_id: id,
|
||||
statistics_unit_of_measurement: "kWh",
|
||||
source: "recorder",
|
||||
name,
|
||||
has_sum: true,
|
||||
mean_type: StatisticMeanType.NONE,
|
||||
unit_class: "energy",
|
||||
});
|
||||
|
||||
const temperatureMetadata = (id: string, name: string): StatisticsMetaData => ({
|
||||
statistic_id: id,
|
||||
statistics_unit_of_measurement: "°C",
|
||||
source: "recorder",
|
||||
name,
|
||||
has_sum: false,
|
||||
mean_type: StatisticMeanType.ARITHMETIC,
|
||||
unit_class: "temperature",
|
||||
});
|
||||
|
||||
const METADATA: Record<string, StatisticsMetaData> = {
|
||||
[HEAT_PUMP_ID]: energyMetadata(HEAT_PUMP_ID, "Heat pump"),
|
||||
[LIGHTING_ID]: energyMetadata(LIGHTING_ID, "Lighting"),
|
||||
[LIVING_ROOM_ID]: temperatureMetadata(LIVING_ROOM_ID, "Living room"),
|
||||
[BEDROOM_ID]: temperatureMetadata(BEDROOM_ID, "Bedroom"),
|
||||
};
|
||||
|
||||
const NAMES = Object.fromEntries(
|
||||
Object.values(METADATA).map((meta) => [meta.statistic_id, meta.name!])
|
||||
);
|
||||
|
||||
interface Example {
|
||||
title: string;
|
||||
description: string;
|
||||
statistics: Statistics;
|
||||
statTypes: StatisticType[];
|
||||
chartType: "line" | "line-stack" | "bar" | "bar-stack";
|
||||
unit: string;
|
||||
hideLegend?: boolean;
|
||||
height?: string;
|
||||
}
|
||||
|
||||
const EXAMPLES: Example[] = [
|
||||
{
|
||||
title: "Sum as bars",
|
||||
description:
|
||||
"The change of a sum for each hour, like an energy statistics graph card.",
|
||||
statistics: { [HEAT_PUMP_ID]: HEAT_PUMP },
|
||||
statTypes: ["change"],
|
||||
chartType: "bar",
|
||||
unit: "kWh",
|
||||
},
|
||||
{
|
||||
title: "Stacked bars",
|
||||
description: "Several sums stacked, to compare what each one adds.",
|
||||
statistics: { [HEAT_PUMP_ID]: HEAT_PUMP, [LIGHTING_ID]: LIGHTING },
|
||||
statTypes: ["change"],
|
||||
chartType: "bar-stack",
|
||||
unit: "kWh",
|
||||
},
|
||||
{
|
||||
title: "Mean, min and max",
|
||||
description: "A measurement with its hourly mean, min and max.",
|
||||
statistics: { [LIVING_ROOM_ID]: LIVING_ROOM },
|
||||
statTypes: ["mean", "min", "max"],
|
||||
chartType: "line",
|
||||
unit: "°C",
|
||||
},
|
||||
{
|
||||
title: "Several statistics",
|
||||
description: "The mean of several measurements with the same unit.",
|
||||
statistics: { [LIVING_ROOM_ID]: LIVING_ROOM, [BEDROOM_ID]: BEDROOM },
|
||||
statTypes: ["mean"],
|
||||
chartType: "line",
|
||||
unit: "°C",
|
||||
},
|
||||
{
|
||||
title: "Without legend",
|
||||
description:
|
||||
"A single statistic with a fixed height, like in the more-info dialog.",
|
||||
statistics: { [LIVING_ROOM_ID]: LIVING_ROOM },
|
||||
statTypes: ["mean", "min", "max"],
|
||||
chartType: "line",
|
||||
unit: "°C",
|
||||
hideLegend: true,
|
||||
height: "240px",
|
||||
},
|
||||
];
|
||||
|
||||
@customElement("demo-components-statistics-chart")
|
||||
export class DemoStatisticsChart extends LitElement {
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProps);
|
||||
const hass = provideHass(this);
|
||||
hass.updateTranslations(null, "en");
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.hass) {
|
||||
return nothing;
|
||||
}
|
||||
return EXAMPLES.map(
|
||||
(example) => html`
|
||||
<ha-card header=${example.title}>
|
||||
<div class="card-content">
|
||||
<p>${example.description}</p>
|
||||
<statistics-chart
|
||||
.statisticsData=${example.statistics}
|
||||
.metadata=${METADATA}
|
||||
.names=${NAMES}
|
||||
.statTypes=${example.statTypes}
|
||||
.chartType=${example.chartType}
|
||||
period="hour"
|
||||
.unit=${example.unit}
|
||||
.startTime=${START}
|
||||
.endTime=${END}
|
||||
.hideLegend=${example.hideLegend ?? false}
|
||||
.height=${example.height}
|
||||
.clickForMoreInfo=${false}
|
||||
></statistics-chart>
|
||||
</div>
|
||||
</ha-card>
|
||||
`
|
||||
);
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
ha-card {
|
||||
max-width: 800px;
|
||||
margin: 24px auto;
|
||||
}
|
||||
p {
|
||||
margin-top: 0;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"demo-components-statistics-chart": DemoStatisticsChart;
|
||||
}
|
||||
}
|
||||
@@ -121,7 +121,7 @@ const brandEntries: ConfigEntryExtended[] = (
|
||||
["tuya", "Tuya", "setup_error"],
|
||||
["unifi", "UniFi Network", "not_loaded"],
|
||||
["met", "Meteorologisk institutt (Met.no)", "setup_error"],
|
||||
["google_assistant", "Google Assistant", "not_loaded"],
|
||||
["google_assistant", "Google Home", "not_loaded"],
|
||||
["homekit_controller", "HomeKit Device", "setup_retry"],
|
||||
] as [string, string, ConfigEntryExtended["state"]][]
|
||||
).map(([domain, name, entryState]) =>
|
||||
|
||||
+15
-14
@@ -13,7 +13,7 @@
|
||||
"lint:prettier": "prettier . --cache --check",
|
||||
"format:prettier": "prettier . --cache --write",
|
||||
"lint:types": "node ./node_modules/@typescript/native/bin/tsc && node ./node_modules/@typescript/native/bin/tsc -p .github/scripts",
|
||||
"lint:lit": "lit-analyzer \"{.,*}/src/**/*.ts\"",
|
||||
"lint:lit": "lit-analyzer \"{.,*,packages/*}/src/**/*.ts\"",
|
||||
"lint:element-imports": "eslint \"**/src/**/*.{js,ts,html}\" --ignore-pattern=.gitignore --rule '{\"ha/no-unused-element-import\": \"warn\"}'",
|
||||
"lint:licenses": "node --no-deprecation script/check-licenses",
|
||||
"lint": "pnpm run lint:eslint && pnpm run lint:prettier && pnpm run lint:types && pnpm run lint:lit",
|
||||
@@ -40,7 +40,7 @@
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "8.0.10",
|
||||
"@babel/runtime": "8.1.0",
|
||||
"@braintree/sanitize-url": "7.1.2",
|
||||
"@codemirror/autocomplete": "6.20.4",
|
||||
"@codemirror/commands": "6.11.1",
|
||||
@@ -78,9 +78,9 @@
|
||||
"@mdi/svg": "7.4.47",
|
||||
"@replit/codemirror-indentation-markers": "6.5.3",
|
||||
"@swc/helpers": "0.5.23",
|
||||
"@tsparticles/engine": "4.5.0",
|
||||
"@tsparticles/preset-links": "4.5.0",
|
||||
"@versatiles/style": "7.1.0",
|
||||
"@tsparticles/engine": "4.5.1",
|
||||
"@tsparticles/preset-links": "4.5.1",
|
||||
"@versatiles/style": "8.1.1",
|
||||
"@vibrant/color": "4.0.4",
|
||||
"@vvo/tzdb": "6.202.0",
|
||||
"@webcomponents/scoped-custom-element-registry": "0.0.10",
|
||||
@@ -98,7 +98,7 @@
|
||||
"echarts": "6.1.0",
|
||||
"echarts-extension-chart2music": "0.1.1",
|
||||
"element-internals-polyfill": "3.0.2",
|
||||
"fullcalendar": "7.1.3",
|
||||
"fullcalendar": "7.1.4",
|
||||
"fuse.js": "7.5.0",
|
||||
"hls.js": "1.7.4",
|
||||
"home-assistant-js-websocket": "9.8.1",
|
||||
@@ -110,7 +110,7 @@
|
||||
"lit": "3.3.3",
|
||||
"lit-html": "3.3.3",
|
||||
"maplibre-gl": "6.16.0",
|
||||
"marked": "18.1.2",
|
||||
"marked": "18.1.3",
|
||||
"memoize-one": "6.0.0",
|
||||
"nanoid": "6.0.2",
|
||||
"node-vibrant": "4.0.4",
|
||||
@@ -123,7 +123,7 @@
|
||||
"sortablejs": "1.15.7",
|
||||
"stacktrace-js": "2.0.2",
|
||||
"superstruct": "2.0.2",
|
||||
"temporal-polyfill": "1.0.6",
|
||||
"temporal-polyfill": "1.0.7",
|
||||
"tinykeys": "4.0.1",
|
||||
"weekstart": "2.0.0",
|
||||
"workbox-cacheable-response": "7.4.1",
|
||||
@@ -137,23 +137,24 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ampproject/remapping": "2.3.0",
|
||||
"@babel/core": "8.0.10",
|
||||
"@babel/core": "8.1.0",
|
||||
"@babel/helper-compilation-targets": "8.0.7",
|
||||
"@babel/helper-define-polyfill-provider": "1.0.0",
|
||||
"@babel/plugin-transform-class-properties": "8.0.1",
|
||||
"@babel/plugin-transform-private-methods": "8.0.1",
|
||||
"@babel/plugin-transform-runtime": "8.0.6",
|
||||
"@babel/preset-env": "8.0.7",
|
||||
"@bundle-stats/plugin-webpack-filter": "4.23.0",
|
||||
"@bundle-stats/plugin-webpack-filter": "4.23.1",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@gfx/zopfli": "1.0.15",
|
||||
"@home-assistant/components": "workspace:*",
|
||||
"@html-eslint/eslint-plugin": "0.67.0",
|
||||
"@lokalise/node-api": "17.0.1",
|
||||
"@octokit/auth-oauth-device": "8.0.5",
|
||||
"@octokit/rest": "22.0.1",
|
||||
"@playwright/test": "1.64.1",
|
||||
"@rsdoctor/rspack-plugin": "1.6.5",
|
||||
"@rspack/core": "2.3.0",
|
||||
"@rspack/core": "2.3.1",
|
||||
"@rspack/dev-server": "2.2.2",
|
||||
"@types/babel__plugin-transform-runtime": "7.9.5",
|
||||
"@types/chromecast-caf-receiver": "7.0.1",
|
||||
@@ -170,7 +171,7 @@
|
||||
"@types/sortablejs": "1.15.9",
|
||||
"@types/tar": "7.0.87",
|
||||
"@typescript/native": "npm:[email protected]",
|
||||
"@vitest/coverage-v8": "5.0.5",
|
||||
"@vitest/coverage-v8": "5.1.0",
|
||||
"babel-loader": "10.1.1",
|
||||
"babel-plugin-polyfill-corejs3": "1.0.0",
|
||||
"browserslist": "4.29.5",
|
||||
@@ -217,12 +218,12 @@
|
||||
"typescript-eslint": "8.72.1",
|
||||
"vite": "8.3.5",
|
||||
"vite-tsconfig-paths": "6.1.1",
|
||||
"vitest": "5.0.5",
|
||||
"vitest": "5.1.0",
|
||||
"webpack-stats-plugin": "1.1.3",
|
||||
"webpackbar": "7.0.0",
|
||||
"workbox-build": "7.4.1"
|
||||
},
|
||||
"packageManager": "[email protected]6.1",
|
||||
"packageManager": "[email protected]7.0",
|
||||
"volta": {
|
||||
"node": "24.22.2"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# @home-assistant/components
|
||||
|
||||
Home Assistant Components (`hac-*`): framework-agnostic web components built
|
||||
with [Lit](https://lit.dev).
|
||||
|
||||
> Work in progress, not published yet.
|
||||
|
||||
## Registration
|
||||
|
||||
Every element is imported on its own, in one of two ways:
|
||||
|
||||
| Import | Registers in | For |
|
||||
| --------------------------------------------- | -------------------- | ----------------------------------------------------------- |
|
||||
| `@home-assistant/components/<element>` | Global registry | Home Assistant itself |
|
||||
| `@home-assistant/components/<element>/scoped` | Your scoped registry | Custom cards and other code that runs inside Home Assistant |
|
||||
|
||||
`<element>` is the tag name without the `hac-` prefix, like `card` for
|
||||
`hac-card`.
|
||||
|
||||
Both use the copy bundled with your code. A scoped copy is isolated from the
|
||||
one Home Assistant registers globally, so a custom card keeps the version it
|
||||
was built with.
|
||||
|
||||
Global registration skips tag names that are already registered, so the first
|
||||
registration wins and nothing throws.
|
||||
|
||||
### Global
|
||||
|
||||
```ts
|
||||
import "@home-assistant/components/card";
|
||||
```
|
||||
|
||||
### Scoped
|
||||
|
||||
Pass the component's elements to `ScopedElementsMixin` for Lit, or to
|
||||
`createScopedElementRegistry` for plain custom elements. Forgetting the
|
||||
elements is a TypeScript error, and a runtime error in plain JavaScript.
|
||||
|
||||
Lit:
|
||||
|
||||
```ts
|
||||
import { LitElement, html } from "lit";
|
||||
import { ScopedElementsMixin } from "@home-assistant/components/scoped";
|
||||
import { hacCard } from "@home-assistant/components/card/scoped";
|
||||
|
||||
class MyCard extends ScopedElementsMixin(LitElement, [hacCard]) {
|
||||
render() {
|
||||
return html`<hac-card>…</hac-card>`;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Plain custom elements:
|
||||
|
||||
```js
|
||||
import {
|
||||
attachScopedShadow,
|
||||
createScopedElement,
|
||||
createScopedElementRegistry,
|
||||
} from "@home-assistant/components/scoped";
|
||||
import { hacCard } from "@home-assistant/components/card/scoped";
|
||||
|
||||
// Create the registry once, outside the class: all instances of the card share it
|
||||
const registry = createScopedElementRegistry([hacCard]);
|
||||
|
||||
class MyCard extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
const root = attachScopedShadow(this, { mode: "open" }, registry);
|
||||
root.innerHTML = "<hac-card>…</hac-card>";
|
||||
// or: root.append(createScopedElement(root, "hac-card"));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`innerHTML`, `insertAdjacentHTML` and `createScopedElement` use the scoped
|
||||
registry. `document.createElement` uses the global one, so avoid it for
|
||||
scoped elements.
|
||||
|
||||
Scoped registries need native support (Chrome 146+, Safari 26) or
|
||||
`@webcomponents/scoped-custom-element-registry`, which Home Assistant loads.
|
||||
Without either, elements are registered globally instead, and an already
|
||||
registered tag name keeps its existing class.
|
||||
|
||||
Only elements rendered inside the shadow root use the scoped registry. Light
|
||||
DOM content, such as slotted elements, uses the registry of the tree it is
|
||||
written in.
|
||||
|
||||
`lit` is a peer dependency.
|
||||
|
||||
### TypeScript
|
||||
|
||||
Each element's entry points declare its tag in `HTMLElementTagNameMap`, so
|
||||
`document.querySelector("hac-card")` and templates are typed once the element
|
||||
is imported. For the class itself, import its type from the `scoped` entry
|
||||
point; `import type` loads nothing at runtime:
|
||||
|
||||
```ts
|
||||
import type { HacCard } from "@home-assistant/components/card/scoped";
|
||||
```
|
||||
|
||||
The package has no root entry point: each element and the scoped helpers
|
||||
(`@home-assistant/components/scoped`) have their own.
|
||||
|
||||
## Theming
|
||||
|
||||
Each component exposes its own `--hac-*` custom properties, documented in its
|
||||
source, which take precedence. Next come the theme variables of the existing
|
||||
Home Assistant element it replaces, so current themes keep working: `hac-card`
|
||||
reads the variables of `ha-card` (`--ha-card-background`,
|
||||
`--card-background-color`, `--ha-card-border-radius`, …). Last come the
|
||||
semantic color tokens (`--ha-color-*`, like `--ha-color-surface-default`) and
|
||||
their light values, so the components also render outside Home Assistant.
|
||||
|
||||
The legacy theme variables are a temporary bridge for this experiment, not the
|
||||
target design. Home Assistant always defines some of them, like
|
||||
`--card-background-color`, so inside Home Assistant they currently win over
|
||||
the semantic tokens. Once themes move to the semantic tokens, the legacy
|
||||
variables will be removed from the fallbacks.
|
||||
|
||||
## Structure
|
||||
|
||||
Each element has its own directory, named like its import path:
|
||||
|
||||
```
|
||||
src/components/card/ <hac-card> -> @home-assistant/components/card
|
||||
hac-card.ts class, does not register itself
|
||||
info.ts tag name and version
|
||||
global.ts registers globally
|
||||
scoped.ts element for a scoped registry -> …/card/scoped
|
||||
```
|
||||
|
||||
Shared code lives in `src/utils/`: `registration/` for defining elements
|
||||
(global and scoped) and `element/` for helpers that components use
|
||||
themselves, like slot checks.
|
||||
|
||||
Every element has its own version in `info.ts`.
|
||||
|
||||
Entry points are mapped with subpath patterns in `package.json`, so a new
|
||||
element directory needs no `package.json` change. Only `global.ts` files have
|
||||
side effects, which `sideEffects` relies on for tree shaking.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
pnpm --filter @home-assistant/components build # ESM, type declarations and custom-elements.json to dist/
|
||||
pnpm --filter @home-assistant/components dev # rebuild on change
|
||||
```
|
||||
|
||||
Inside this repository the app uses the sources directly through
|
||||
the `ha-source` export condition, so no build is needed during development.
|
||||
The package is built with [Rslib](https://rslib.rs) in bundleless mode: every
|
||||
source file becomes its own ES module. The build then generates a
|
||||
[custom elements manifest](https://custom-elements-manifest.open-wc.org) from
|
||||
the JSDoc of each element, so document new slots, parts, CSS properties and
|
||||
events there.
|
||||
@@ -0,0 +1,84 @@
|
||||
// Generates dist/custom-elements.json from the JSDoc of the hac elements, for
|
||||
// editors and documentation tools. Only hac-*.ts files declare elements; the
|
||||
// entry points just re-export them.
|
||||
|
||||
const forEachDeclaration = (customElementsManifest, callback) => {
|
||||
for (const module of customElementsManifest.modules) {
|
||||
for (const declaration of module.declarations ?? []) {
|
||||
callback(declaration);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// The analyzer leaves the readme empty. Paths in the manifest are relative to
|
||||
// the package root, like the module paths.
|
||||
const packageReadme = () => ({
|
||||
name: "package-readme",
|
||||
packageLinkPhase({ customElementsManifest }) {
|
||||
customElementsManifest.readme = "README.md";
|
||||
},
|
||||
});
|
||||
|
||||
// Elements are documented with @summary, which the analyzer only puts into
|
||||
// `summary`. Most tools show `description`, so fall back to the summary.
|
||||
const summaryAsDescription = () => ({
|
||||
name: "summary-as-description",
|
||||
packageLinkPhase({ customElementsManifest }) {
|
||||
forEachDeclaration(customElementsManifest, (declaration) => {
|
||||
if (!declaration.description && declaration.summary) {
|
||||
declaration.description = declaration.summary;
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Private and protected members are internal, so keep them out of the
|
||||
// documented API.
|
||||
const publicApiOnly = () => ({
|
||||
name: "public-api-only",
|
||||
packageLinkPhase({ customElementsManifest }) {
|
||||
forEachDeclaration(customElementsManifest, (declaration) => {
|
||||
declaration.members = declaration.members?.filter(
|
||||
(member) => !member.privacy || member.privacy === "public"
|
||||
);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const distPaths = () => {
|
||||
const toDist = (value) => value.replace(/^src\/(.+)\.ts$/, "dist/$1.js");
|
||||
const rewrite = (node) => {
|
||||
if (Array.isArray(node)) {
|
||||
node.forEach(rewrite);
|
||||
return;
|
||||
}
|
||||
if (!node || typeof node !== "object") {
|
||||
return;
|
||||
}
|
||||
for (const [key, value] of Object.entries(node)) {
|
||||
if ((key === "path" || key === "module") && typeof value === "string") {
|
||||
node[key] = toDist(value);
|
||||
} else {
|
||||
rewrite(value);
|
||||
}
|
||||
}
|
||||
};
|
||||
return {
|
||||
name: "dist-paths",
|
||||
packageLinkPhase({ customElementsManifest }) {
|
||||
rewrite(customElementsManifest.modules);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default {
|
||||
globs: ["src/components/**/hac-*.ts"],
|
||||
outdir: "dist",
|
||||
litelement: true,
|
||||
plugins: [
|
||||
packageReadme(),
|
||||
summaryAsDescription(),
|
||||
publicApiOnly(),
|
||||
distPaths(),
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"name": "@home-assistant/components",
|
||||
"version": "0.0.0",
|
||||
"description": "Home Assistant web components (hac-* elements) built with Lit",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/home-assistant/frontend.git",
|
||||
"directory": "packages/components"
|
||||
},
|
||||
"type": "module",
|
||||
"sideEffects": [
|
||||
"./dist/components/**/global.js",
|
||||
"./src/components/**/global.ts"
|
||||
],
|
||||
"customElements": "dist/custom-elements.json",
|
||||
"exports": {
|
||||
"./scoped": {
|
||||
"ha-source": "./src/scoped.ts",
|
||||
"types": "./dist/scoped.d.ts",
|
||||
"import": "./dist/scoped.js"
|
||||
},
|
||||
"./package.json": "./package.json",
|
||||
"./*/scoped": {
|
||||
"ha-source": "./src/components/*/scoped.ts",
|
||||
"types": "./dist/components/*/scoped.d.ts",
|
||||
"import": "./dist/components/*/scoped.js"
|
||||
},
|
||||
"./*/info": {
|
||||
"ha-source": "./src/components/*/info.ts",
|
||||
"types": "./dist/components/*/info.d.ts",
|
||||
"import": "./dist/components/*/info.js"
|
||||
},
|
||||
"./*": {
|
||||
"ha-source": "./src/components/*/global.ts",
|
||||
"types": "./dist/components/*/global.d.ts",
|
||||
"import": "./dist/components/*/global.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rslib build && cem analyze",
|
||||
"dev": "rslib build --watch",
|
||||
"prepublishOnly": "pnpm run build"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"lit": "^3.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@custom-elements-manifest/analyzer": "0.11.0",
|
||||
"@rslib/core": "1.0.5",
|
||||
"lit": "3.3.3",
|
||||
"typescript": "6.0.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { defineConfig } from "@rslib/core";
|
||||
|
||||
// Bundleless build: every source file becomes its own ESM file, so consumers'
|
||||
// bundlers only include the entry points they import. Only global.ts files
|
||||
// register elements; everything else is free of side effects.
|
||||
export default defineConfig({
|
||||
source: {
|
||||
entry: { index: ["./src/**/*.ts"] },
|
||||
decorators: { version: "legacy" },
|
||||
tsconfigPath: "./tsconfig.json",
|
||||
},
|
||||
tools: {
|
||||
swc: { jsc: { transform: { decoratorMetadata: false } } },
|
||||
},
|
||||
lib: [
|
||||
{
|
||||
format: "esm",
|
||||
bundle: false,
|
||||
syntax: "es2021",
|
||||
dts: true,
|
||||
output: { target: "web", distPath: { root: "./dist" } },
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import { define } from "../../utils/registration/define";
|
||||
import { HacCard } from "./hac-card";
|
||||
import { TAG_NAME } from "./info";
|
||||
|
||||
// Registers <hac-card> in the global registry, as used by Home Assistant
|
||||
define(TAG_NAME, HacCard);
|
||||
|
||||
export { HacCard };
|
||||
@@ -0,0 +1,165 @@
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { property, state } from "lit/decorators.js";
|
||||
import {
|
||||
hasAssignedContent,
|
||||
hasAssignedElements,
|
||||
} from "../../utils/element/slot";
|
||||
|
||||
/**
|
||||
* @element hac-card
|
||||
*
|
||||
* @summary
|
||||
* Card that groups related content, with an optional header and footer.
|
||||
*
|
||||
* @slot header - Header of the card. Its spacing replaces the top padding of
|
||||
* the content.
|
||||
* @slot - Content of the card. Its padding is omitted when empty.
|
||||
* @slot footer - Footer of the card. Hidden when empty.
|
||||
*
|
||||
* @csspart header - Wrapper of the header slot.
|
||||
* @csspart content - Wrapper of the default slot.
|
||||
* @csspart footer - Wrapper of the footer slot.
|
||||
*
|
||||
* @cssprop --hac-card-background - Background of the card.
|
||||
* @cssprop --hac-card-color - Text color of the card.
|
||||
* @cssprop --hac-card-border-color - Border color of the card and the footer divider.
|
||||
* @cssprop --hac-card-border-width - Border width of the card.
|
||||
* @cssprop --hac-card-border-radius - Border radius of the card.
|
||||
* @cssprop --hac-card-box-shadow - Box shadow of the card.
|
||||
* @cssprop --hac-card-content-padding - Padding of the content.
|
||||
* @cssprop --hac-card-footer-padding - Padding of the footer.
|
||||
*/
|
||||
export class HacCard extends LitElement {
|
||||
/**
|
||||
* Visual style of the card. `outlined` draws a border without a shadow.
|
||||
* `raised` hides the border and lifts the card with a shadow instead.
|
||||
*/
|
||||
@property({ reflect: true }) public appearance: "outlined" | "raised" =
|
||||
"outlined";
|
||||
|
||||
@state() private _hasHeader = false;
|
||||
|
||||
@state() private _hasFooter = false;
|
||||
|
||||
@state() private _hasContent = false;
|
||||
|
||||
protected render() {
|
||||
return html`
|
||||
<div class="header" part="header" ?hidden=${!this._hasHeader}>
|
||||
<slot name="header" @slotchange=${this._headerChanged}></slot>
|
||||
</div>
|
||||
<div
|
||||
class="content ${this._hasHeader ? "below-header" : ""}"
|
||||
part="content"
|
||||
?hidden=${!this._hasContent}
|
||||
>
|
||||
<slot @slotchange=${this._contentChanged}></slot>
|
||||
</div>
|
||||
<div class="footer" part="footer" ?hidden=${!this._hasFooter}>
|
||||
<slot name="footer" @slotchange=${this._footerChanged}></slot>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private _headerChanged(ev: Event) {
|
||||
this._hasHeader = hasAssignedElements(ev);
|
||||
}
|
||||
|
||||
private _contentChanged(ev: Event) {
|
||||
this._hasContent = hasAssignedContent(ev);
|
||||
}
|
||||
|
||||
private _footerChanged(ev: Event) {
|
||||
this._hasFooter = hasAssignedElements(ev);
|
||||
}
|
||||
|
||||
/*
|
||||
* Fallback order: --hac-card-*, then the theme variables of ha-card
|
||||
* (--ha-card-*, --card-background-color, --divider-color,
|
||||
* --primary-text-color) so existing themes keep working, then the semantic
|
||||
* tokens and their light values for use outside Home Assistant.
|
||||
* The ha-card variables are temporary, see "Theming" in the README.
|
||||
*/
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
position: relative;
|
||||
box-sizing: border-box;
|
||||
background: var(
|
||||
--hac-card-background,
|
||||
var(
|
||||
--ha-card-background,
|
||||
var(--card-background-color, var(--ha-color-surface-default, #fff))
|
||||
)
|
||||
);
|
||||
backdrop-filter: var(--ha-card-backdrop-filter, none);
|
||||
color: var(
|
||||
--hac-card-color,
|
||||
var(--primary-text-color, var(--ha-color-on-surface-default, #141414))
|
||||
);
|
||||
border: var(--hac-card-border-width, var(--ha-card-border-width, 1px))
|
||||
solid
|
||||
var(
|
||||
--hac-card-border-color,
|
||||
var(
|
||||
--ha-card-border-color,
|
||||
var(--divider-color, var(--ha-color-border-neutral-quiet, #e6e6e6))
|
||||
)
|
||||
);
|
||||
border-radius: var(
|
||||
--hac-card-border-radius,
|
||||
var(--ha-card-border-radius, var(--ha-border-radius-lg, 12px))
|
||||
);
|
||||
box-shadow: var(--hac-card-box-shadow, var(--ha-card-box-shadow, none));
|
||||
}
|
||||
|
||||
:host([appearance="raised"]) {
|
||||
border-color: transparent;
|
||||
box-shadow: var(
|
||||
--hac-card-box-shadow,
|
||||
var(
|
||||
--ha-card-box-shadow,
|
||||
var(
|
||||
--ha-box-shadow-s,
|
||||
0 1px 2px 0 rgba(0, 0, 0, 0.08),
|
||||
0 1px 3px 0 rgba(0, 0, 0, 0.12)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
.content {
|
||||
padding: var(--hac-card-content-padding, var(--ha-space-4, 16px));
|
||||
}
|
||||
|
||||
/* The header already provides the spacing above the content */
|
||||
.content.below-header {
|
||||
padding-block-start: 0;
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-2, 8px);
|
||||
padding: var(--hac-card-footer-padding, var(--ha-space-2, 8px));
|
||||
border-block-start: 1px solid
|
||||
var(
|
||||
--hac-card-border-color,
|
||||
var(--divider-color, var(--ha-color-border-neutral-quiet, #e6e6e6))
|
||||
);
|
||||
}
|
||||
|
||||
.header[hidden],
|
||||
.content[hidden],
|
||||
.footer[hidden] {
|
||||
display: none;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"hac-card": HacCard;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Tag name of the element. */
|
||||
export const TAG_NAME = "hac-card";
|
||||
|
||||
/** Version of <hac-card>. */
|
||||
export const VERSION = "0.1.0";
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { ElementDefinition } from "../../utils/registration/definition";
|
||||
import { HacCard } from "./hac-card";
|
||||
import { TAG_NAME } from "./info";
|
||||
|
||||
export { HacCard };
|
||||
|
||||
/**
|
||||
* The bundled <hac-card> for a scoped registry:
|
||||
* `ScopedElementsMixin(LitElement, [hacCard])` or
|
||||
* `createScopedElementRegistry([hacCard])`.
|
||||
*/
|
||||
export const hacCard: ElementDefinition<typeof HacCard> = {
|
||||
tagName: TAG_NAME,
|
||||
element: HacCard,
|
||||
};
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { LitElement } from "lit";
|
||||
import { define } from "./utils/registration/define";
|
||||
import type { ElementDefinition } from "./utils/registration/definition";
|
||||
import {
|
||||
createScopedRegistry,
|
||||
scopedCreationScope,
|
||||
scopedRegistrySupport,
|
||||
scopedShadowRootInit,
|
||||
} from "./utils/registration/scoped-registry";
|
||||
|
||||
export type { ElementDefinition } from "./utils/registration/definition";
|
||||
|
||||
/**
|
||||
* Creates a registry with the given elements, for `attachScopedShadow`:
|
||||
* definitions from `scoped` entry points, e.g. `[hacCard]`.
|
||||
* Create it once, outside the class, so all instances of a card share it.
|
||||
*
|
||||
* Without scoped registry support (native or polyfill), the elements are
|
||||
* registered in the global registry instead, unless their tag name is already
|
||||
* taken there, and the global registry is returned.
|
||||
*/
|
||||
export const createScopedElementRegistry = (
|
||||
elements: readonly ElementDefinition[]
|
||||
): CustomElementRegistry => {
|
||||
// Checked as unknown: Array.isArray would narrow the list to any[]
|
||||
if (!Array.isArray(elements as unknown)) {
|
||||
throw new TypeError(
|
||||
"@home-assistant/components: pass the elements to register, e.g. [hacCard]"
|
||||
);
|
||||
}
|
||||
const registry = createScopedRegistry() ?? customElements;
|
||||
for (const { tagName, element } of elements) {
|
||||
define(tagName, element, registry);
|
||||
}
|
||||
return registry;
|
||||
};
|
||||
|
||||
const shadowRootInit = (
|
||||
init: ShadowRootInit,
|
||||
registry: CustomElementRegistry
|
||||
): ShadowRootInit =>
|
||||
registry === customElements ? init : scopedShadowRootInit(init, registry);
|
||||
|
||||
const registries = new WeakMap<ShadowRoot, CustomElementRegistry>();
|
||||
|
||||
/**
|
||||
* Attaches a shadow root that uses `registry` for custom elements in it.
|
||||
*
|
||||
* Content added with `innerHTML` or `insertAdjacentHTML` uses the registry.
|
||||
* Create single elements with `createScopedElement`; `document.createElement`
|
||||
* would use the global registry.
|
||||
*
|
||||
* Light DOM content, like slotted elements, keeps using the registry of the
|
||||
* tree it is written in.
|
||||
*/
|
||||
export const attachScopedShadow = (
|
||||
host: HTMLElement,
|
||||
init: ShadowRootInit,
|
||||
registry: CustomElementRegistry
|
||||
): ShadowRoot => {
|
||||
const root = host.attachShadow(shadowRootInit(init, registry));
|
||||
registries.set(root, registry);
|
||||
return root;
|
||||
};
|
||||
|
||||
/** Creates an element from the registry of a shadow root. */
|
||||
export const createScopedElement = <K extends keyof HTMLElementTagNameMap>(
|
||||
root: ShadowRoot,
|
||||
tagName: K
|
||||
): HTMLElementTagNameMap[K] => {
|
||||
const registry = registries.get(root);
|
||||
if (!registry || registry === customElements) {
|
||||
return document.createElement(tagName);
|
||||
}
|
||||
if (scopedRegistrySupport() === "polyfill") {
|
||||
// The polyfill adds createElement to shadow roots
|
||||
return (
|
||||
root as unknown as {
|
||||
createElement(tagName: K): HTMLElementTagNameMap[K];
|
||||
}
|
||||
).createElement(tagName);
|
||||
}
|
||||
return (
|
||||
document.createElement as (
|
||||
tagName: K,
|
||||
options: { customElementRegistry: CustomElementRegistry }
|
||||
) => HTMLElementTagNameMap[K]
|
||||
)(tagName, { customElementRegistry: registry });
|
||||
};
|
||||
|
||||
type LitElementConstructor = abstract new (...args: any[]) => LitElement;
|
||||
|
||||
/**
|
||||
* Renders a Lit element into a shadow root with its own custom element
|
||||
* registry, containing `elements`:
|
||||
*
|
||||
* ```ts
|
||||
* class MyCard extends ScopedElementsMixin(LitElement, [hacCard]) {}
|
||||
* ```
|
||||
*
|
||||
* See `createScopedElementRegistry` and `attachScopedShadow` for the details.
|
||||
*/
|
||||
export const ScopedElementsMixin = <T extends LitElementConstructor>(
|
||||
superClass: T,
|
||||
elements: readonly ElementDefinition[]
|
||||
) => {
|
||||
// Created on first use, so defining the class has no side effects
|
||||
let registry: CustomElementRegistry | undefined;
|
||||
const getRegistry = () => {
|
||||
registry ??= createScopedElementRegistry(elements);
|
||||
return registry;
|
||||
};
|
||||
|
||||
abstract class ScopedElementsHost extends superClass {
|
||||
public attachShadow(init: ShadowRootInit): ShadowRoot {
|
||||
const root = super.attachShadow(shadowRootInit(init, getRegistry()));
|
||||
registries.set(root, getRegistry());
|
||||
return root;
|
||||
}
|
||||
|
||||
protected createRenderRoot() {
|
||||
const root = super.createRenderRoot();
|
||||
const scoped = getRegistry();
|
||||
if (scoped !== customElements && root instanceof ShadowRoot) {
|
||||
this.renderOptions.creationScope = scopedCreationScope(root, scoped);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
}
|
||||
// Typed as the base class: the overrides add no public API
|
||||
return ScopedElementsHost as unknown as T;
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
/** Whether the slot of a `slotchange` event has elements assigned. */
|
||||
export const hasAssignedElements = (ev: Event): boolean =>
|
||||
(ev.target as HTMLSlotElement).assignedElements().length > 0;
|
||||
|
||||
/**
|
||||
* Whether the slot of a `slotchange` event has content assigned: elements or
|
||||
* text. Whitespace between tags is not content.
|
||||
*/
|
||||
export const hasAssignedContent = (ev: Event): boolean =>
|
||||
(ev.target as HTMLSlotElement)
|
||||
.assignedNodes()
|
||||
.some(
|
||||
(node) =>
|
||||
node.nodeType === Node.ELEMENT_NODE || Boolean(node.textContent?.trim())
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Registers a custom element unless the tag name is already taken in the
|
||||
* registry.
|
||||
*
|
||||
* Home Assistant and custom cards can each ship a copy of this library, so
|
||||
* registering the same tag name twice must not throw. The first registration
|
||||
* wins.
|
||||
*/
|
||||
export const define = (
|
||||
tagName: string,
|
||||
elementClass: CustomElementConstructor,
|
||||
registry: CustomElementRegistry = customElements
|
||||
): void => {
|
||||
if (!registry.get(tagName)) {
|
||||
registry.define(tagName, elementClass);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* An element to register: its tag name and its class. The `scoped` entry
|
||||
* point of an element exports one, e.g. `hacCard`.
|
||||
*/
|
||||
export interface ElementDefinition<
|
||||
E extends CustomElementConstructor = CustomElementConstructor,
|
||||
> {
|
||||
readonly tagName: string;
|
||||
readonly element: E;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Scoped custom element registries come in two flavors: the standard API
|
||||
* (Chrome 146+, Safari 26) and the older API of
|
||||
* `@webcomponents/scoped-custom-element-registry`, which Home Assistant loads
|
||||
* and which replaces the native implementation when present.
|
||||
*/
|
||||
export type ScopedRegistrySupport = "polyfill" | "native" | "none";
|
||||
|
||||
let support: ScopedRegistrySupport | undefined;
|
||||
|
||||
export const scopedRegistrySupport = (): ScopedRegistrySupport => {
|
||||
if (support) {
|
||||
return support;
|
||||
}
|
||||
if ("CustomElementRegistryPolyfill" in globalThis) {
|
||||
support = "polyfill";
|
||||
} else {
|
||||
try {
|
||||
new CustomElementRegistry();
|
||||
support = "native";
|
||||
} catch (_err) {
|
||||
support = "none";
|
||||
}
|
||||
}
|
||||
return support;
|
||||
};
|
||||
|
||||
/** A new scoped registry, or `undefined` if the browser has no support. */
|
||||
export const createScopedRegistry = (): CustomElementRegistry | undefined =>
|
||||
scopedRegistrySupport() === "none" ? undefined : new CustomElementRegistry();
|
||||
|
||||
/** Shadow root options that make the shadow root use `registry`. */
|
||||
export const scopedShadowRootInit = (
|
||||
init: ShadowRootInit,
|
||||
registry: CustomElementRegistry
|
||||
): ShadowRootInit =>
|
||||
scopedRegistrySupport() === "polyfill"
|
||||
? ({ ...init, registry } as ShadowRootInit)
|
||||
: ({ ...init, customElementRegistry: registry } as ShadowRootInit);
|
||||
|
||||
interface CreationScope {
|
||||
importNode(node: Node, deep?: boolean): Node;
|
||||
}
|
||||
|
||||
/**
|
||||
* The object Lit should create template content with, so custom elements in
|
||||
* it are created from the scoped registry (Lit's `creationScope`).
|
||||
*/
|
||||
export const scopedCreationScope = (
|
||||
root: ShadowRoot,
|
||||
registry: CustomElementRegistry
|
||||
): CreationScope => {
|
||||
if (scopedRegistrySupport() === "polyfill") {
|
||||
// The polyfill adds importNode to shadow roots
|
||||
return root as unknown as CreationScope;
|
||||
}
|
||||
// Standard API: the registry is passed to importNode
|
||||
return {
|
||||
importNode: (node, deep) =>
|
||||
(
|
||||
document.importNode as (
|
||||
node: Node,
|
||||
options: { selfOnly: boolean; customElementRegistry: unknown }
|
||||
) => Node
|
||||
)(node, { selfOnly: !deep, customElementRegistry: registry }),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { define } from "../src/utils/registration/define";
|
||||
|
||||
// Home Assistant and custom cards can each ship a copy of the library, so a
|
||||
// second registration of the same tag must be ignored instead of throwing.
|
||||
describe("define", () => {
|
||||
it("registers an element that is not registered yet", () => {
|
||||
class First extends HTMLElement {}
|
||||
define("hac-test-first", First);
|
||||
expect(customElements.get("hac-test-first")).toBe(First);
|
||||
});
|
||||
|
||||
it("keeps the first registration of a tag name", () => {
|
||||
class Original extends HTMLElement {}
|
||||
class Duplicate extends HTMLElement {}
|
||||
define("hac-test-duplicate", Original);
|
||||
expect(() => define("hac-test-duplicate", Duplicate)).not.toThrow();
|
||||
expect(customElements.get("hac-test-duplicate")).toBe(Original);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
hasAssignedContent,
|
||||
hasAssignedElements,
|
||||
} from "../src/utils/element/slot";
|
||||
|
||||
// Components hide wrappers of empty slots, e.g. the padding of an empty card.
|
||||
// Whitespace between tags must not count as content.
|
||||
const slotEvent = (light: string, name?: string) => {
|
||||
const host = document.createElement("div");
|
||||
host.innerHTML = light;
|
||||
const slot = document.createElement("slot");
|
||||
if (name) {
|
||||
slot.name = name;
|
||||
}
|
||||
host.attachShadow({ mode: "open" }).append(slot);
|
||||
return { target: slot } as unknown as Event;
|
||||
};
|
||||
|
||||
describe("hasAssignedContent", () => {
|
||||
it("ignores whitespace", () => {
|
||||
expect(hasAssignedContent(slotEvent("\n \n"))).toBe(false);
|
||||
});
|
||||
|
||||
it("counts text", () => {
|
||||
expect(hasAssignedContent(slotEvent(" Hello "))).toBe(true);
|
||||
});
|
||||
|
||||
it("counts elements", () => {
|
||||
expect(hasAssignedContent(slotEvent("\n <p></p>\n"))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasAssignedElements", () => {
|
||||
it("only counts elements assigned to the slot", () => {
|
||||
const light = '<span slot="icon"></span> text';
|
||||
expect(hasAssignedElements(slotEvent(light, "icon"))).toBe(true);
|
||||
expect(hasAssignedElements(slotEvent(light, "actions"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2021",
|
||||
"lib": ["ES2021", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noImplicitReturns": true,
|
||||
"isolatedModules": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": true,
|
||||
"rootDir": "src",
|
||||
"outDir": "dist"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
Generated
+1361
-702
File diff suppressed because it is too large.
Load diff
@@ -1,3 +1,7 @@
|
||||
packages:
|
||||
- "."
|
||||
- "packages/*"
|
||||
|
||||
savePrefix: ""
|
||||
autoInstallPeers: false
|
||||
|
||||
@@ -19,6 +23,7 @@ trustPolicyExclude:
|
||||
allowBuilds:
|
||||
"@tsparticles/engine": false
|
||||
core-js: false
|
||||
rs-module-lexer: false
|
||||
unrs-resolver: false
|
||||
|
||||
overrides:
|
||||
|
||||
@@ -3,6 +3,12 @@ import { ref } from "lit/directives/ref";
|
||||
|
||||
const MAX_ROWS = 2;
|
||||
|
||||
// A narrow list, as on a phone or a half width card, fits about one item per
|
||||
// row, so two rows hide most of the legend. 450px is about the widest list a
|
||||
// phone viewport gives.
|
||||
const NARROW_MAX_ROWS = 3;
|
||||
const NARROW_WIDTH = 450;
|
||||
|
||||
// How many items fit in maxRows of a wrapping row, leaving room for the
|
||||
// "more" item after them when not all of them fit.
|
||||
export const fitInRows = (
|
||||
@@ -34,9 +40,10 @@ export const fitInRows = (
|
||||
return widths.length;
|
||||
};
|
||||
|
||||
// Fits the items of a wrapping legend list into two rows. The list keeps its
|
||||
// "more" item rendered with the legend-more class, and items past the fit
|
||||
// stay rendered out of the flow, so both can always be measured.
|
||||
// Fits the items of a wrapping legend list into two rows, three when it is
|
||||
// narrow. The list keeps its "more" item rendered with the legend-more class,
|
||||
// and items past the fit stay rendered out of the flow, so both can always be
|
||||
// measured.
|
||||
export class LegendFitController {
|
||||
// Items to show while collapsed, undefined until the list is measured
|
||||
public fit?: number;
|
||||
@@ -118,7 +125,7 @@ export class LegendFitController {
|
||||
more?.getBoundingClientRect().width ?? 0,
|
||||
rowWidth,
|
||||
parseFloat(getComputedStyle(list).columnGap) || 0,
|
||||
MAX_ROWS
|
||||
rowWidth < NARROW_WIDTH ? NARROW_MAX_ROWS : MAX_ROWS
|
||||
);
|
||||
if (fit !== this.fit) {
|
||||
this.fit = fit;
|
||||
|
||||
+13
-2
@@ -16,6 +16,13 @@ declare global {
|
||||
export interface NavigateOptions {
|
||||
replace?: boolean;
|
||||
data?: Record<string, unknown>;
|
||||
/**
|
||||
* Leave open dialogs open. For a replace that only canonicalizes the current
|
||||
* URL, like a router filling in its default page: a dialog restored from the
|
||||
* URL, such as a more-info deep link, may already be open at that point, and
|
||||
* the entry keeps its state so back still closes it.
|
||||
*/
|
||||
keepDialogs?: boolean;
|
||||
}
|
||||
|
||||
// max time to wait for dialogs to close before navigating
|
||||
@@ -196,7 +203,8 @@ const buildHistoryState = (
|
||||
};
|
||||
|
||||
const performNavigation = async (path: string, options?: NavigateOptions) => {
|
||||
const canProceed = await ensureDialogsClosed(Date.now());
|
||||
const keepDialogs = options?.keepDialogs || false;
|
||||
const canProceed = await (keepDialogs || ensureDialogsClosed(Date.now()));
|
||||
if (!canProceed) {
|
||||
return false;
|
||||
}
|
||||
@@ -215,7 +223,10 @@ const performNavigation = async (path: string, options?: NavigateOptions) => {
|
||||
|
||||
const { history } = mainWindow;
|
||||
|
||||
if (replace) {
|
||||
if (replace && keepDialogs) {
|
||||
// Same entry under its canonical URL: its state, dialog included, stays.
|
||||
history.replaceState(history.state, "", path);
|
||||
} else if (replace) {
|
||||
// A replaced entry keeps its predecessor, so it keeps `from`.
|
||||
const { root, from } = history.state ?? {};
|
||||
const data = root ? { root: true } : options?.data;
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { join } from "lit/directives/join";
|
||||
import { keyed } from "lit/directives/keyed";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
@@ -124,16 +125,16 @@ export interface DataTableRowData {
|
||||
|
||||
export type SortableColumnContainer = Record<string, ClonedDataTableColumnData>;
|
||||
|
||||
// Slot for the actions at the end of a group's header, they don't toggle the
|
||||
// group. Put `ha-icon-button`s with a label in it. They get the rows' icon
|
||||
// Renders the actions at the end of a group's header, they don't toggle the
|
||||
// group. Return `ha-icon-button`s with a label. They get the rows' icon
|
||||
// colour and size by default, which `--data-table-group-actions-color`,
|
||||
// `--data-table-group-actions-button-size` and
|
||||
// `--data-table-group-actions-icon-size` change for all of them; style a
|
||||
// button itself for its own colour or size.
|
||||
export const GROUP_ACTIONS_SLOT_PREFIX = "group-actions-";
|
||||
|
||||
export const groupActionsSlot = (group: string) =>
|
||||
`${GROUP_ACTIONS_SLOT_PREFIX}${group}`;
|
||||
// button itself for its own colour or size. Not a slot per group, as WebKit
|
||||
// is slow to add and remove slots while the rows scroll.
|
||||
export type DataTableGroupActions = (
|
||||
group: string
|
||||
) => TemplateResult | typeof nothing;
|
||||
|
||||
const UNDEFINED_GROUP_KEY = "zzzzz_undefined";
|
||||
|
||||
@@ -197,6 +198,9 @@ export class HaDataTable extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public groupOrder?: string[];
|
||||
|
||||
@property({ attribute: false })
|
||||
public renderGroupActions?: DataTableGroupActions;
|
||||
|
||||
@property({ attribute: false }) public sortColumn?: string;
|
||||
|
||||
@property({ attribute: false }) public sortDirection: SortingDirection = null;
|
||||
@@ -506,7 +510,8 @@ export class HaDataTable extends LitElement {
|
||||
this.groupOrder,
|
||||
this._collapsedGroups,
|
||||
this.sortColumn,
|
||||
this.sortDirection
|
||||
this.sortDirection,
|
||||
this.renderGroupActions
|
||||
)
|
||||
: [];
|
||||
|
||||
@@ -759,8 +764,6 @@ export class HaDataTable extends LitElement {
|
||||
`
|
||||
: html`
|
||||
${
|
||||
// Rendered before the rows, so the group's actions slot
|
||||
// shows here and not in its scrolled out header row
|
||||
this.groupColumn &&
|
||||
!this.autoHeight &&
|
||||
this._stickyGroup !== undefined
|
||||
@@ -775,11 +778,15 @@ export class HaDataTable extends LitElement {
|
||||
.group=${this._stickyGroup}
|
||||
@click=${this._collapseStickyGroup}
|
||||
>
|
||||
${this._renderGroupHeader(
|
||||
${keyed(
|
||||
this._stickyGroup,
|
||||
this._collapsedGroups.includes(this._stickyGroup),
|
||||
this._i18n?.localize,
|
||||
true
|
||||
this._renderGroupHeader(
|
||||
this._stickyGroup,
|
||||
this._collapsedGroups.includes(this._stickyGroup),
|
||||
this._i18n?.localize,
|
||||
this.renderGroupActions,
|
||||
true
|
||||
)
|
||||
)}
|
||||
</div>`
|
||||
: nothing
|
||||
@@ -803,7 +810,14 @@ export class HaDataTable extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private _keyFunction = (row: DataTableRowData) => row?.[this.id] || row;
|
||||
// Group headers are keyed by their group, so they keep their actions' state
|
||||
// when the data changes. The prefixes keep them apart from row ids.
|
||||
private _keyFunction = (row: DataTableRowData) =>
|
||||
row?.[this.id]
|
||||
? `row-${row[this.id]}`
|
||||
: row?.groupHeader !== undefined
|
||||
? `group-${row.groupHeader}`
|
||||
: row;
|
||||
|
||||
private _renderMainValue(value: unknown) {
|
||||
return this.clickable
|
||||
@@ -1063,7 +1077,8 @@ export class HaDataTable extends LitElement {
|
||||
groupOrder: string[] | undefined,
|
||||
collapsedGroups: string[],
|
||||
sortColumn: string | undefined,
|
||||
sortDirection: SortingDirection
|
||||
sortDirection: SortingDirection,
|
||||
renderGroupActions: DataTableGroupActions | undefined
|
||||
) => {
|
||||
if (appendRow || groupColumn) {
|
||||
let items = [...data];
|
||||
@@ -1122,7 +1137,8 @@ export class HaDataTable extends LitElement {
|
||||
content: this._renderGroupHeader(
|
||||
groupName,
|
||||
collapsedGroups.includes(groupName),
|
||||
localize
|
||||
localize,
|
||||
renderGroupActions
|
||||
),
|
||||
});
|
||||
if (!collapsedGroups.includes(groupName)) {
|
||||
@@ -1148,6 +1164,7 @@ export class HaDataTable extends LitElement {
|
||||
groupName: string,
|
||||
collapsed: boolean,
|
||||
localize: LocalizeFunc | undefined,
|
||||
renderGroupActions: DataTableGroupActions | undefined,
|
||||
sticky = false
|
||||
) {
|
||||
// The sticky copy's button and name are hidden from assistive technology,
|
||||
@@ -1183,7 +1200,7 @@ export class HaDataTable extends LitElement {
|
||||
}
|
||||
</span>
|
||||
<div class="group-actions" @click=${this._stopGroupToggle}>
|
||||
<slot name=${groupActionsSlot(groupName)}></slot>
|
||||
${renderGroupActions?.(groupName)}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
@@ -1264,7 +1281,8 @@ export class HaDataTable extends LitElement {
|
||||
this.groupOrder,
|
||||
this._collapsedGroups,
|
||||
this.sortColumn,
|
||||
this.sortDirection
|
||||
this.sortDirection,
|
||||
this.renderGroupActions
|
||||
);
|
||||
|
||||
if (
|
||||
@@ -1961,7 +1979,7 @@ export class HaDataTable extends LitElement {
|
||||
align-self: stretch;
|
||||
margin-top: -12px;
|
||||
margin-inline-start: auto;
|
||||
/* The rows' icon button size, inherited by the slotted ones */
|
||||
/* The rows' icon button size, inherited by the actions */
|
||||
--_button-size: var(--data-table-group-actions-button-size, 48px);
|
||||
--ha-icon-button-size: var(--_button-size);
|
||||
--mdc-icon-size: var(--data-table-group-actions-icon-size, 24px);
|
||||
@@ -1974,9 +1992,9 @@ export class HaDataTable extends LitElement {
|
||||
position: sticky;
|
||||
inset-inline-end: 0;
|
||||
cursor: default;
|
||||
/* Don't pass the group name's weight on to slotted menus */
|
||||
/* Don't pass the group name's weight on to the actions */
|
||||
font-weight: var(--ha-font-weight-normal);
|
||||
/* Inherited by the slotted icon buttons, like the rows' icon cells */
|
||||
/* Inherited by the actions, like the rows' icon cells */
|
||||
color: var(
|
||||
--data-table-group-actions-color,
|
||||
var(--secondary-text-color)
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import {
|
||||
AREA_CONTROLS_BUTTONS,
|
||||
getAreaControlEntities,
|
||||
getAreaEntityIds,
|
||||
type AreaControlDomain,
|
||||
} from "../data/area/area_controls";
|
||||
import {
|
||||
@@ -148,15 +149,20 @@ export class HaAreaControlsPicker extends LitElement {
|
||||
currentValue === id ||
|
||||
(excludeValues !== undefined && excludeValues.includes(id));
|
||||
|
||||
const areaEntities = getAreaEntityIds(
|
||||
registries.entities,
|
||||
registries.devices,
|
||||
areaId,
|
||||
excludeEntities
|
||||
);
|
||||
const controlEntities = getAreaControlEntities(
|
||||
areaEntities,
|
||||
states,
|
||||
registries.entities,
|
||||
registries.devices,
|
||||
registries.areas,
|
||||
registries.floors,
|
||||
AREA_CONTROL_DOMAINS,
|
||||
areaId,
|
||||
excludeEntities
|
||||
AREA_CONTROL_DOMAINS
|
||||
);
|
||||
|
||||
const items: (AreaControlPickerItem | string)[] = [];
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ensureArray } from "../../common/array/ensure-array";
|
||||
import type {
|
||||
HaFormCondition,
|
||||
HaFormDataContainer,
|
||||
@@ -87,26 +88,38 @@ export const combineVisible = (
|
||||
return conditions;
|
||||
};
|
||||
|
||||
const getConditionFields = (visible: HaFormVisible | undefined): string[] =>
|
||||
visible === undefined || typeof visible === "boolean"
|
||||
? []
|
||||
: ensureArray(visible).flatMap((condition) =>
|
||||
"condition" in condition
|
||||
? condition.conditions.flatMap((sub) => getConditionFields(sub))
|
||||
: [condition.field]
|
||||
);
|
||||
|
||||
// Hiding a field drops its value, which can flip another field's condition, so
|
||||
// resolve the set to a fixpoint. Fields are given in order as name and visible.
|
||||
// a field is evaluated after the fields its condition depends on.
|
||||
export const getHiddenFields = (
|
||||
fields: readonly (readonly [string, HaFormVisible | undefined])[],
|
||||
data: HaFormDataContainer | undefined
|
||||
): Set<string> => {
|
||||
const hidden = new Set<string>();
|
||||
const conditions = new Map(fields);
|
||||
const evalData: HaFormDataContainer = { ...(data ?? {}) };
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const [name, visible] of fields) {
|
||||
if (hidden.has(name) || isVisible(visible, evalData)) {
|
||||
continue;
|
||||
}
|
||||
const hidden = new Set<string>();
|
||||
const resolved = new Set<string>();
|
||||
const resolve = (name: string) => {
|
||||
if (resolved.has(name) || !conditions.has(name)) {
|
||||
return;
|
||||
}
|
||||
resolved.add(name);
|
||||
const visible = conditions.get(name);
|
||||
getConditionFields(visible).forEach(resolve);
|
||||
if (!isVisible(visible, evalData)) {
|
||||
hidden.add(name);
|
||||
delete evalData[name];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
};
|
||||
fields.forEach(([name]) => resolve(name));
|
||||
return hidden;
|
||||
};
|
||||
|
||||
|
||||
@@ -219,6 +219,7 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
|
||||
if (this._searchFieldElement) {
|
||||
this._searchFieldElement.value = value;
|
||||
}
|
||||
this._applySearch(value);
|
||||
}
|
||||
|
||||
protected get scrollableElement(): HTMLElement | null {
|
||||
@@ -691,7 +692,11 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
|
||||
|
||||
private _filterChanged = (ev: InputEvent) => {
|
||||
const textfield = ev.target as HaInputSearch;
|
||||
const searchString = (textfield.value ?? "").trim();
|
||||
this._applySearch(textfield.value ?? "");
|
||||
};
|
||||
|
||||
private _applySearch(value: string) {
|
||||
const searchString = value.trim();
|
||||
this._search = searchString;
|
||||
|
||||
if (this.sections?.length) {
|
||||
@@ -736,7 +741,7 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
|
||||
|
||||
this._resetSelectedItem();
|
||||
this._resetListScroll();
|
||||
};
|
||||
}
|
||||
|
||||
// Keep focus in the search field, so a focus change doesn't scroll the
|
||||
// list to the active row and make the click miss.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getEntityAreaId } from "../../common/entity/context/get_entity_context";
|
||||
import { generateEntityFilter } from "../../common/entity/entity_filter";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
|
||||
@@ -61,15 +62,26 @@ export const AREA_CONTROLS_BUTTONS: Record<
|
||||
"cover-window": coverButton("window"),
|
||||
};
|
||||
|
||||
export const getAreaEntityIds = (
|
||||
entities: HomeAssistant["entities"],
|
||||
devices: HomeAssistant["devices"],
|
||||
areaId: string,
|
||||
excludeEntities?: string[]
|
||||
): string[] =>
|
||||
Object.keys(entities).filter(
|
||||
(entityId) =>
|
||||
getEntityAreaId(entityId, entities, devices) === areaId &&
|
||||
!excludeEntities?.includes(entityId)
|
||||
);
|
||||
|
||||
export const getAreaControlEntities = (
|
||||
areaEntities: string[],
|
||||
states: HomeAssistant["states"],
|
||||
entities: HomeAssistant["entities"],
|
||||
devices: HomeAssistant["devices"],
|
||||
areas: HomeAssistant["areas"],
|
||||
floors: HomeAssistant["floors"],
|
||||
controls: readonly AreaControlDomain[],
|
||||
areaId: string,
|
||||
excludeEntities: string[] | undefined
|
||||
controls: readonly AreaControlDomain[]
|
||||
): Record<AreaControlDomain, string[]> =>
|
||||
controls.reduce(
|
||||
(acc, control) => {
|
||||
@@ -81,15 +93,12 @@ export const getAreaControlEntities = (
|
||||
areas,
|
||||
floors,
|
||||
{
|
||||
area: areaId,
|
||||
entity_category: "none",
|
||||
...controlButton.filter,
|
||||
}
|
||||
);
|
||||
|
||||
acc[control] = Object.keys(entities).filter(
|
||||
(entityId) => filter(entityId) && !excludeEntities?.includes(entityId)
|
||||
);
|
||||
acc[control] = areaEntities.filter(filter);
|
||||
return acc;
|
||||
},
|
||||
{} as Record<AreaControlDomain, string[]>
|
||||
|
||||
+102
-18
@@ -252,12 +252,14 @@ export interface EnergyPreferences {
|
||||
energy_sources: EnergySource[];
|
||||
device_consumption: DeviceConsumptionEnergyPreference[];
|
||||
device_consumption_water: DeviceConsumptionEnergyPreference[];
|
||||
device_consumption_gas: DeviceConsumptionEnergyPreference[];
|
||||
}
|
||||
|
||||
export const EMPTY_PREFERENCES: EnergyPreferences = {
|
||||
energy_sources: [],
|
||||
device_consumption: [],
|
||||
device_consumption_water: [],
|
||||
device_consumption_gas: [],
|
||||
};
|
||||
|
||||
export interface EnergyInfo {
|
||||
@@ -275,6 +277,7 @@ export interface EnergyPreferencesValidation {
|
||||
energy_sources: EnergyValidationIssue[][];
|
||||
device_consumption: EnergyValidationIssue[][];
|
||||
device_consumption_water: EnergyValidationIssue[][];
|
||||
device_consumption_gas: EnergyValidationIssue[][];
|
||||
}
|
||||
|
||||
export const getEnergyInfo = (callWS: HomeAssistant["callWS"]) =>
|
||||
@@ -507,6 +510,11 @@ export const getReferencedStatisticIds = (
|
||||
...prefs.device_consumption_water.map((d) => d.stat_consumption)
|
||||
);
|
||||
}
|
||||
if (!(includeTypes && !includeTypes.includes("gas"))) {
|
||||
statIDs.push(
|
||||
...prefs.device_consumption_gas.map((d) => d.stat_consumption)
|
||||
);
|
||||
}
|
||||
|
||||
return statIDs;
|
||||
};
|
||||
@@ -543,6 +551,7 @@ export const getReferencedStatisticIdsPower = (
|
||||
}
|
||||
statIDs.push(...prefs.device_consumption.map((d) => d.stat_rate));
|
||||
statIDs.push(...prefs.device_consumption_water.map((d) => d.stat_rate));
|
||||
statIDs.push(...prefs.device_consumption_gas.map((d) => d.stat_rate));
|
||||
|
||||
return statIDs.filter(Boolean) as string[];
|
||||
};
|
||||
@@ -651,9 +660,16 @@ const getEnergyData = async (
|
||||
const gasIsOtherEnergy =
|
||||
ENERGY_UNITS.includes(gasUnit as any) && gasUnit !== "kWh";
|
||||
const gasEnergyStatIds = gasIsOtherEnergy
|
||||
? (energySourcesByType(prefs).gas ?? []).map(
|
||||
(source) => source.stat_energy_from
|
||||
)
|
||||
? [
|
||||
...new Set([
|
||||
...(energySourcesByType(prefs).gas ?? []).map(
|
||||
(source) => source.stat_energy_from
|
||||
),
|
||||
...prefs.device_consumption_gas.map(
|
||||
(device) => device.stat_consumption
|
||||
),
|
||||
]),
|
||||
]
|
||||
: [];
|
||||
const gasEnergyUnits: StatisticsUnitConfiguration = {
|
||||
energy: gasIsOtherEnergy
|
||||
@@ -1474,13 +1490,18 @@ export type EnergyGasUnitClass = (typeof energyGasUnitClass)[number];
|
||||
export const getEnergyGasUnitClass = (
|
||||
prefs: EnergyPreferences,
|
||||
excludeSource?: string,
|
||||
statisticsMetaData: Record<string, StatisticsMetaData> = {}
|
||||
statisticsMetaData: Record<string, StatisticsMetaData> = {},
|
||||
excludeFrom?: "source" | "device"
|
||||
): EnergyGasUnitClass | undefined => {
|
||||
for (const source of prefs.energy_sources) {
|
||||
if (source.type !== "gas") {
|
||||
continue;
|
||||
}
|
||||
if (excludeSource && excludeSource === source.stat_energy_from) {
|
||||
if (
|
||||
excludeSource &&
|
||||
excludeSource === source.stat_energy_from &&
|
||||
excludeFrom !== "device"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const statisticIdWithMeta = statisticsMetaData[source.stat_energy_from];
|
||||
@@ -1492,6 +1513,19 @@ export const getEnergyGasUnitClass = (
|
||||
return statisticIdWithMeta.unit_class as EnergyGasUnitClass;
|
||||
}
|
||||
}
|
||||
for (const device of prefs.device_consumption_gas) {
|
||||
if (
|
||||
excludeSource &&
|
||||
excludeSource === device.stat_consumption &&
|
||||
excludeFrom !== "source"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const unitClass = statisticsMetaData[device.stat_consumption]?.unit_class;
|
||||
if (energyGasUnitClass.includes(unitClass as EnergyGasUnitClass)) {
|
||||
return unitClass as EnergyGasUnitClass;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
@@ -1501,15 +1535,15 @@ const getEnergyGasUnit = (
|
||||
prefs: EnergyPreferences,
|
||||
statisticsMetaData: Record<string, StatisticsMetaData> = {}
|
||||
): string => {
|
||||
const units = prefs.energy_sources
|
||||
.filter((s) => s.type === "gas")
|
||||
.map((s) =>
|
||||
getDisplayUnit(
|
||||
states,
|
||||
s.stat_energy_from,
|
||||
statisticsMetaData[s.stat_energy_from]
|
||||
)
|
||||
);
|
||||
const gasStatIds = [
|
||||
...prefs.energy_sources.flatMap((s) =>
|
||||
s.type === "gas" ? [s.stat_energy_from] : []
|
||||
),
|
||||
...prefs.device_consumption_gas.map((d) => d.stat_consumption),
|
||||
];
|
||||
const units = gasStatIds.map((id) =>
|
||||
getDisplayUnit(states, id, statisticsMetaData[id])
|
||||
);
|
||||
|
||||
const unitClass = getEnergyGasUnitClass(prefs, undefined, statisticsMetaData);
|
||||
if (unitClass === "energy") {
|
||||
@@ -1535,10 +1569,7 @@ const getEnergyGasUnit = (
|
||||
return [];
|
||||
}),
|
||||
]);
|
||||
const isSharedWithKWh = prefs.energy_sources.some(
|
||||
(source) =>
|
||||
source.type === "gas" && kWhStatIds.has(source.stat_energy_from)
|
||||
);
|
||||
const isSharedWithKWh = gasStatIds.some((id) => kWhStatIds.has(id));
|
||||
const first = units[0];
|
||||
if (
|
||||
!isSharedWithKWh &&
|
||||
@@ -2200,6 +2231,48 @@ export const formatFlowRateShort = (
|
||||
});
|
||||
};
|
||||
|
||||
export type WaterGasResource = "water" | "gas";
|
||||
|
||||
export const getWaterGasDevicesKey = (resource: WaterGasResource) =>
|
||||
`device_consumption_${resource}` as const;
|
||||
|
||||
export const getWaterGasDevices = (
|
||||
prefs: EnergyPreferences,
|
||||
resource: WaterGasResource
|
||||
): DeviceConsumptionEnergyPreference[] =>
|
||||
prefs[getWaterGasDevicesKey(resource)];
|
||||
|
||||
export const getFlowRateUnit = (
|
||||
resource: WaterGasResource,
|
||||
prefs: EnergyPreferences,
|
||||
states: HomeAssistant["states"]
|
||||
): string | undefined => {
|
||||
const ids = [
|
||||
...prefs.energy_sources.flatMap((s) =>
|
||||
s.type === resource && s.stat_rate ? [s.stat_rate] : []
|
||||
),
|
||||
...getWaterGasDevices(prefs, resource).flatMap((d) =>
|
||||
d.stat_rate ? [d.stat_rate] : []
|
||||
),
|
||||
];
|
||||
for (const id of ids) {
|
||||
const unit = states[id]?.attributes.unit_of_measurement;
|
||||
if (unit) {
|
||||
return unit;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const getFlowRateInUnit = (
|
||||
stateObj: HassEntity | undefined,
|
||||
unit: string
|
||||
): number | undefined => {
|
||||
const value = getFlowRateFromState(stateObj);
|
||||
const factor = FLOW_RATE_TO_LMIN[unit];
|
||||
return value === undefined || factor === undefined ? value : value / factor;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get current power value from entity state, normalized to watts (W)
|
||||
* @param stateObj - The entity state object to get power value from
|
||||
@@ -2280,6 +2353,7 @@ export const downloadEnergyData = (
|
||||
const energy_sources = energyData.prefs.energy_sources;
|
||||
const device_consumption = energyData.prefs.device_consumption;
|
||||
const device_consumption_water = energyData.prefs.device_consumption_water;
|
||||
const device_consumption_gas = energyData.prefs.device_consumption_gas;
|
||||
const stats = state.stats;
|
||||
|
||||
interface CsvRow {
|
||||
@@ -2460,6 +2534,16 @@ export const downloadEnergyData = (
|
||||
printCategory("device_consumption_water", waterDevices, state.waterUnit);
|
||||
}
|
||||
|
||||
if (device_consumption_gas) {
|
||||
const gasDevices: string[] = [];
|
||||
device_consumption_gas.forEach((source) => {
|
||||
source = source as DeviceConsumptionEnergyPreference;
|
||||
gasDevices.push(source.stat_consumption);
|
||||
});
|
||||
|
||||
printCategory("device_consumption_gas", gasDevices, state.gasUnit);
|
||||
}
|
||||
|
||||
const { summedData } = getSummedData(state);
|
||||
const { consumption } = computeConsumptionData(summedData, undefined);
|
||||
|
||||
|
||||
@@ -390,3 +390,32 @@ export const getAutomaticEntityIds = (
|
||||
type: "config/entity_registry/get_automatic_entity_ids",
|
||||
entity_ids,
|
||||
});
|
||||
|
||||
/**
|
||||
* Set the area of entities and regenerate their entity IDs, which can include
|
||||
* the area. Returns the entity ID of each entity after the change.
|
||||
*/
|
||||
export const updateEntitiesArea = async (
|
||||
hass: HomeAssistant,
|
||||
entityIds: string[],
|
||||
areaId: string
|
||||
): Promise<Record<string, string>> => {
|
||||
await Promise.all(
|
||||
entityIds.map((entityId) =>
|
||||
updateEntityRegistryEntry(hass, entityId, { area_id: areaId })
|
||||
)
|
||||
);
|
||||
const newEntityIds = await getAutomaticEntityIds(hass, entityIds);
|
||||
const result: Record<string, string> = {};
|
||||
for (const entityId of entityIds) {
|
||||
const newEntityId = newEntityIds[entityId];
|
||||
if (newEntityId) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await updateEntityRegistryEntry(hass, entityId, {
|
||||
new_entity_id: newEntityId,
|
||||
});
|
||||
}
|
||||
result[entityId] = newEntityId || entityId;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
+2
-1
@@ -19,7 +19,8 @@ export interface ESPHomeZWaveProxyCapabilities {
|
||||
export interface ESPHomeSerialProxy {
|
||||
name: string;
|
||||
port_type: ESPHomeSerialPortType | null;
|
||||
url: string;
|
||||
// `null` when no device is present (e.g. unpopulated USB port)
|
||||
url: string | null;
|
||||
}
|
||||
|
||||
export interface ESPHomeDeviceCapabilities {
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ export const voiceAssistants = {
|
||||
},
|
||||
"cloud.google_assistant": {
|
||||
domain: "google_assistant",
|
||||
name: "Google Assistant",
|
||||
name: "Google Home",
|
||||
},
|
||||
} as const;
|
||||
|
||||
|
||||
@@ -481,6 +481,7 @@ class DataEntryFlowDialog extends DirtyStateProviderMixin<
|
||||
.flowConfig=${this._params.flowConfig}
|
||||
.step=${this._step}
|
||||
.hass=${this.hass}
|
||||
.manifest=${this._params.manifest}
|
||||
.navigateToResult=${
|
||||
this._params.navigateToResult ?? false
|
||||
}
|
||||
@@ -838,6 +839,9 @@ class DataEntryFlowDialog extends DirtyStateProviderMixin<
|
||||
return [
|
||||
haStyleDialog,
|
||||
css`
|
||||
ha-dialog {
|
||||
--ha-dialog-header-title-height: auto;
|
||||
}
|
||||
.dialog-title {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
|
||||
@@ -20,13 +20,18 @@ import type { DeviceRegistryEntry } from "../../data/device/device_registry";
|
||||
import { updateDeviceRegistryEntry } from "../../data/device/device_registry";
|
||||
import {
|
||||
getAutomaticEntityIds,
|
||||
getExtendedEntityRegistryEntries,
|
||||
updateEntitiesArea,
|
||||
updateEntityRegistryEntry,
|
||||
type EntityRegistryDisplayEntry,
|
||||
type ExtEntityRegistryEntry,
|
||||
} from "../../data/entity/entity_registry";
|
||||
import { domainToName } from "../../data/integration";
|
||||
import { domainToName, type IntegrationManifest } from "../../data/integration";
|
||||
import { findRelated } from "../../data/search";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../../types";
|
||||
import { brandsUrl } from "../../util/brands-url";
|
||||
import { showAlertDialog } from "../generic/show-dialog-box";
|
||||
import { showMoreInfoDialog } from "../more-info/show-ha-more-info-dialog";
|
||||
import { showVoiceAssistantSetupDialog } from "../voice-assistant-setup/show-voice-assistant-setup-dialog";
|
||||
import type { FlowConfig } from "./show-dialog-data-entry-flow";
|
||||
import { configFlowContentStyles } from "./styles";
|
||||
@@ -35,6 +40,28 @@ interface DeviceTarget {
|
||||
device: string;
|
||||
}
|
||||
|
||||
interface HelperResult {
|
||||
deviceId?: string;
|
||||
entityId?: string;
|
||||
}
|
||||
|
||||
const computeHelperResult = (
|
||||
entities: ExtEntityRegistryEntry[]
|
||||
): HelperResult | undefined => {
|
||||
const deviceIds = [
|
||||
...new Set(
|
||||
entities.flatMap((entity) => (entity.device_id ? [entity.device_id] : []))
|
||||
),
|
||||
];
|
||||
if (deviceIds.length === 1) {
|
||||
return { deviceId: deviceIds[0] };
|
||||
}
|
||||
if (!deviceIds.length && entities.length === 1) {
|
||||
return { entityId: entities[0].entity_id };
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
@customElement("step-flow-create-entry")
|
||||
class StepFlowCreateEntry extends LitElement {
|
||||
@property({ attribute: false }) public flowConfig!: FlowConfig;
|
||||
@@ -46,10 +73,18 @@ class StepFlowCreateEntry extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public devices!: DeviceRegistryEntry[];
|
||||
|
||||
@property({ attribute: false }) public manifest?: IntegrationManifest | null;
|
||||
|
||||
private _domains: Record<string, string> = {};
|
||||
|
||||
public navigateToResult = false;
|
||||
|
||||
private _helperEntitiesLookup?: Promise<ExtEntityRegistryEntry[]>;
|
||||
|
||||
@state() private _helperEntities?: ExtEntityRegistryEntry[];
|
||||
|
||||
@state() private _helperArea?: string;
|
||||
|
||||
@state() private _deviceUpdate: Record<
|
||||
string,
|
||||
{ name?: string; area?: string }
|
||||
@@ -73,6 +108,18 @@ class StepFlowCreateEntry extends LitElement {
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProps);
|
||||
this._loadDomains();
|
||||
if (
|
||||
this.flowConfig.flowType === "config_flow" &&
|
||||
this.step.result &&
|
||||
this.manifest?.integration_type === "helper"
|
||||
) {
|
||||
this._helperEntitiesLookup = this._findHelperEntities(
|
||||
this.step.result.entry_id
|
||||
);
|
||||
this._helperEntitiesLookup.then((entities) => {
|
||||
this._helperEntities = entities;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>) {
|
||||
@@ -133,11 +180,23 @@ class StepFlowCreateEntry extends LitElement {
|
||||
? nothing
|
||||
: this.devices.length === 0
|
||||
? html`<p>
|
||||
${localize(
|
||||
"ui.panel.config.integrations.config_flow.created_config",
|
||||
{ name: this.step.title }
|
||||
)}
|
||||
</p>`
|
||||
${localize(
|
||||
"ui.panel.config.integrations.config_flow.created_config",
|
||||
{ name: html`<b>${this.step.title}</b>` }
|
||||
)}
|
||||
</p>
|
||||
${
|
||||
this._entitiesWithoutDevice(this._helperEntities).length
|
||||
? html`<ha-area-picker
|
||||
.value=${this._helperArea}
|
||||
.disabled=${this._loading}
|
||||
.helper=${localize(
|
||||
"ui.panel.config.integrations.config_flow.helper_area"
|
||||
)}
|
||||
@value-changed=${this._helperAreaPicked}
|
||||
></ha-area-picker>`
|
||||
: nothing
|
||||
}`
|
||||
: html`
|
||||
<div class="devices">
|
||||
${this.devices.map(
|
||||
@@ -214,9 +273,11 @@ class StepFlowCreateEntry extends LitElement {
|
||||
|
||||
protected updated(changedProps: PropertyValues): void {
|
||||
super.updated(changedProps);
|
||||
if (changedProps.has("_deviceUpdate")) {
|
||||
if (changedProps.has("_deviceUpdate") || changedProps.has("_helperArea")) {
|
||||
fireEvent(this, "flow-step-footer-state-changed", {
|
||||
hasPendingUpdates: Object.keys(this._deviceUpdate).length > 0,
|
||||
hasPendingUpdates:
|
||||
Object.keys(this._deviceUpdate).length > 0 ||
|
||||
this._helperArea !== undefined,
|
||||
});
|
||||
}
|
||||
if (changedProps.has("_loading")) {
|
||||
@@ -226,6 +287,11 @@ class StepFlowCreateEntry extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
private _entitiesWithoutDevice = memoizeOne(
|
||||
(entities?: ExtEntityRegistryEntry[]): ExtEntityRegistryEntry[] =>
|
||||
(entities ?? []).filter((entity) => !entity.device_id)
|
||||
);
|
||||
|
||||
private async _loadDomains() {
|
||||
const entries = await getConfigEntries(this.hass);
|
||||
this._domains = Object.fromEntries(
|
||||
@@ -290,16 +356,95 @@ class StepFlowCreateEntry extends LitElement {
|
||||
await Promise.allSettled(entityUpdates);
|
||||
}
|
||||
|
||||
fireEvent(this, "flow-update", { step: undefined });
|
||||
if (this.step.result && this.navigateToResult) {
|
||||
if (this.devices.length === 1) {
|
||||
navigate(`/config/devices/device/${this.devices[0].id}`);
|
||||
} else {
|
||||
navigate(
|
||||
`/config/integrations/integration/${this.step.result.domain}#config_entry=${this.step.result.entry_id}`
|
||||
);
|
||||
}
|
||||
// Helpers link their entities to an existing device instead of creating one
|
||||
let helperEntities =
|
||||
this._helperEntitiesLookup && !this.devices.length
|
||||
? await this._helperEntitiesLookup
|
||||
: [];
|
||||
if (this._helperArea) {
|
||||
helperEntities = await this._saveHelperArea(
|
||||
helperEntities,
|
||||
this._helperArea
|
||||
);
|
||||
}
|
||||
|
||||
const entry = this.navigateToResult ? this.step.result : undefined;
|
||||
const helperResult = entry
|
||||
? computeHelperResult(helperEntities)
|
||||
: undefined;
|
||||
|
||||
// The dialog was closed while waiting
|
||||
if (!this.isConnected) {
|
||||
return;
|
||||
}
|
||||
fireEvent(this, "flow-update", { step: undefined });
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
const deviceId =
|
||||
this.devices.length === 1 ? this.devices[0].id : helperResult?.deviceId;
|
||||
if (deviceId) {
|
||||
navigate(`/config/devices/device/${deviceId}`);
|
||||
} else if (helperResult?.entityId) {
|
||||
showMoreInfoDialog(this, { entityId: helperResult.entityId });
|
||||
} else {
|
||||
navigate(
|
||||
`/config/integrations/integration/${entry.domain}#config_entry=${entry.entry_id}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async _findHelperEntities(
|
||||
entryId: string
|
||||
): Promise<ExtEntityRegistryEntry[]> {
|
||||
try {
|
||||
const { entity: entityIds = [] } = await findRelated(
|
||||
this.hass,
|
||||
"config_entry",
|
||||
entryId
|
||||
);
|
||||
if (!entityIds.length) {
|
||||
return [];
|
||||
}
|
||||
return Object.values(
|
||||
await getExtendedEntityRegistryEntries(this.hass, entityIds)
|
||||
).filter(
|
||||
(entity): entity is ExtEntityRegistryEntry =>
|
||||
entity?.config_entry_id === entryId
|
||||
);
|
||||
} catch (_err) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private async _saveHelperArea(
|
||||
entities: ExtEntityRegistryEntry[],
|
||||
areaId: string
|
||||
): Promise<ExtEntityRegistryEntry[]> {
|
||||
try {
|
||||
const newEntityIds = await updateEntitiesArea(
|
||||
this.hass,
|
||||
this._entitiesWithoutDevice(entities).map((entity) => entity.entity_id),
|
||||
areaId
|
||||
);
|
||||
return entities.map((entity) =>
|
||||
entity.entity_id in newEntityIds
|
||||
? { ...entity, entity_id: newEntityIds[entity.entity_id] }
|
||||
: entity
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
showAlertDialog(this, {
|
||||
text: this.hass.localize(
|
||||
"ui.panel.config.integrations.config_flow.error_saving_entity",
|
||||
{ error: (err as { message?: string })?.message ?? "Unknown error" }
|
||||
),
|
||||
});
|
||||
return entities;
|
||||
}
|
||||
}
|
||||
|
||||
private _helperAreaPicked(ev: ValueChangedEvent<string | undefined>): void {
|
||||
this._helperArea = ev.detail.value || undefined;
|
||||
}
|
||||
|
||||
public async finish(): Promise<void> {
|
||||
|
||||
@@ -690,7 +690,7 @@ class DialogESPHomeDeviceSetup extends DialogMixin<ESPHomeDeviceSetupDialogParam
|
||||
* is always in the scan, so a missing or absent port means it is offline.
|
||||
* Without the usb integration nothing is scanned, so a missing port says nothing.
|
||||
*/
|
||||
private _serialPortUsage(url: string) {
|
||||
private _serialPortUsage(url: string | null) {
|
||||
if (!this._serialPorts) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -375,21 +375,16 @@ export class HaVoiceAssistantSetupStepSuccess extends LitElement {
|
||||
margin-top: 24px;
|
||||
}
|
||||
.rows {
|
||||
gap: var(--ha-space-4);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: var(--ha-space-4) var(--ha-space-1);
|
||||
align-items: center;
|
||||
}
|
||||
.row > *:first-child {
|
||||
flex: 1;
|
||||
margin-right: 4px;
|
||||
.row {
|
||||
display: contents;
|
||||
}
|
||||
.row ha-button {
|
||||
width: 82px;
|
||||
.row > :only-child {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
ha-select {
|
||||
|
||||
@@ -2,6 +2,7 @@ import type {
|
||||
HassEntity,
|
||||
HassEntityAttributeBase,
|
||||
} from "home-assistant-js-websocket";
|
||||
import type { EntityRegistryEntry } from "../../data/entity/entity_registry";
|
||||
|
||||
/** Base attributes type that all entities share */
|
||||
export type EntityAttributes = HassEntityAttributeBase & Record<string, any>;
|
||||
@@ -17,6 +18,11 @@ export type EntityInput = Pick<
|
||||
device_id?: string;
|
||||
/** Integration that provides the entity, defaults to "demo" */
|
||||
platform?: string;
|
||||
/**
|
||||
* Options of the entity in the mocked entity registry, such as timer
|
||||
* presets or favorite positions
|
||||
*/
|
||||
options?: EntityRegistryEntry["options"];
|
||||
/** When the state last changed, a random recent time by default */
|
||||
last_changed?: string;
|
||||
};
|
||||
|
||||
@@ -104,6 +104,7 @@ export class HassRouterPage extends ReactiveElement {
|
||||
const queryParams = window.location.search;
|
||||
navigate(`${route.prefix}/${defaultPage}${queryParams}`, {
|
||||
replace: true,
|
||||
keepDialogs: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -134,6 +135,7 @@ export class HassRouterPage extends ReactiveElement {
|
||||
if (route) {
|
||||
navigate(`${route.prefix}/${result}${location.search}`, {
|
||||
replace: true,
|
||||
keepDialogs: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,9 +27,10 @@ import {
|
||||
dataTableQueryStateFromUrl,
|
||||
} from "../common/url/data-table-query-params";
|
||||
import "../components/chips/ha-assist-chip";
|
||||
import { GROUP_ACTIONS_SLOT_PREFIX } from "../components/data-table/ha-data-table";
|
||||
import "../components/data-table/ha-data-table";
|
||||
import type {
|
||||
DataTableColumnContainer,
|
||||
DataTableGroupActions,
|
||||
DataTableRowData,
|
||||
HaDataTable,
|
||||
SortingDirection,
|
||||
@@ -216,6 +217,9 @@ export class HaTabsSubpageDataTable extends KeyboardShortcutMixin(LitElement) {
|
||||
|
||||
@property({ attribute: false }) public groupOrder?: string[];
|
||||
|
||||
@property({ attribute: false })
|
||||
public renderGroupActions?: DataTableGroupActions;
|
||||
|
||||
@property({ attribute: false }) public columnOrder?: string[];
|
||||
|
||||
@property({ attribute: false }) public hiddenColumns?: string[];
|
||||
@@ -627,13 +631,11 @@ export class HaTabsSubpageDataTable extends KeyboardShortcutMixin(LitElement) {
|
||||
.sortDirection=${this._sortDirection}
|
||||
.groupColumn=${this._groupColumn}
|
||||
.groupOrder=${this.groupOrder}
|
||||
.renderGroupActions=${this.renderGroupActions}
|
||||
.initialCollapsedGroups=${this.initialCollapsedGroups}
|
||||
.columnOrder=${this.columnOrder}
|
||||
.hiddenColumns=${this.hiddenColumns}
|
||||
>
|
||||
${this._groupActionsSlots.map(
|
||||
(slot) => html`<slot name=${slot} slot=${slot}></slot>`
|
||||
)}
|
||||
${
|
||||
!this.narrow
|
||||
? html`
|
||||
@@ -849,46 +851,6 @@ export class HaTabsSubpageDataTable extends KeyboardShortcutMixin(LitElement) {
|
||||
this._setGroupColumn(group);
|
||||
}
|
||||
|
||||
// Slots of the group actions the page supplies, passed through to the table
|
||||
@state() private _groupActionsSlots: string[] = [];
|
||||
|
||||
private _groupActionsObserver = new MutationObserver(() =>
|
||||
this._updateGroupActionsSlots()
|
||||
);
|
||||
|
||||
public connectedCallback(): void {
|
||||
super.connectedCallback();
|
||||
this._updateGroupActionsSlots();
|
||||
// Subtree, so slot changes on the page's children are seen too
|
||||
this._groupActionsObserver.observe(this, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributeFilter: ["slot"],
|
||||
});
|
||||
}
|
||||
|
||||
public disconnectedCallback(): void {
|
||||
super.disconnectedCallback();
|
||||
this._groupActionsObserver.disconnect();
|
||||
}
|
||||
|
||||
private _updateGroupActionsSlots() {
|
||||
const slots = [
|
||||
...new Set(
|
||||
Array.from(this.children, (child) => child.slot).filter((slot) =>
|
||||
slot.startsWith(GROUP_ACTIONS_SLOT_PREFIX)
|
||||
)
|
||||
),
|
||||
];
|
||||
|
||||
if (
|
||||
slots.length !== this._groupActionsSlots.length ||
|
||||
slots.some((slot, index) => slot !== this._groupActionsSlots[index])
|
||||
) {
|
||||
this._groupActionsSlots = slots;
|
||||
}
|
||||
}
|
||||
|
||||
private _setGroupColumn(columnId: string, link = false) {
|
||||
this._groupColumn = columnId;
|
||||
fireEvent(this, "grouping-changed", { value: columnId, link });
|
||||
|
||||
@@ -189,7 +189,7 @@ class PartialPanelResolver extends HassRouterPage {
|
||||
const { pathname, search, hash } = mainWindow.location;
|
||||
navigate(
|
||||
`${pathname.replace(/^\/hacs/, "/marketplace")}${search}${hash}`,
|
||||
{ replace: true }
|
||||
{ replace: true, keepDialogs: true }
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -237,7 +237,11 @@ class HaPanelApp extends LitElement {
|
||||
} catch (err: any) {
|
||||
await this._showErrorAndNavigateHome(
|
||||
addonSlug,
|
||||
extractApiErrorMessage(err)
|
||||
err?.code === "unauthorized"
|
||||
? this.hass.localize("ui.panel.app.error_app_unauthorized")
|
||||
: this.hass.localize("ui.panel.app.error_loading_app", {
|
||||
error: extractApiErrorMessage(err),
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -317,13 +321,15 @@ class HaPanelApp extends LitElement {
|
||||
|
||||
try {
|
||||
session = await createSessionPromise;
|
||||
} catch (_err: any) {
|
||||
} catch (err: any) {
|
||||
if (this._sessionKeepAlive) {
|
||||
clearInterval(this._sessionKeepAlive);
|
||||
}
|
||||
await this._showErrorAndNavigateHome(
|
||||
addon.name,
|
||||
this.hass.localize("ui.panel.app.error_creating_session")
|
||||
this.hass.localize("ui.panel.app.error_creating_session", {
|
||||
error: extractApiErrorMessage(err),
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
mdiScriptText,
|
||||
mdiShape,
|
||||
mdiTools,
|
||||
mdiTransitConnectionVariant,
|
||||
} from "@mdi/js";
|
||||
import { startOfYesterday } from "date-fns";
|
||||
import type { HassEntity } from "home-assistant-js-websocket/dist/types";
|
||||
@@ -19,6 +20,7 @@ import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import { transform } from "../../../common/decorators/transform";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../../common/dom/fire_event";
|
||||
import { computeDeviceNameDisplay } from "../../../common/entity/compute_device_name";
|
||||
import { computeDomain } from "../../../common/entity/compute_domain";
|
||||
@@ -34,9 +36,11 @@ import "../../../components/ha-card";
|
||||
import "../../../components/ha-dropdown";
|
||||
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
|
||||
import "../../../components/ha-dropdown-item";
|
||||
import "../../../components/ha-domain-icon";
|
||||
import "../../../components/ha-icon-button";
|
||||
import "../../../components/ha-icon-button-next";
|
||||
import "../../../components/ha-icon-next";
|
||||
import "../../../components/ha-state-icon";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import "../../../components/ha-tooltip";
|
||||
import "../../../components/item/ha-list-item-base";
|
||||
@@ -49,7 +53,13 @@ import {
|
||||
updateAreaRegistryEntry,
|
||||
} from "../../../data/area/area_registry";
|
||||
import type { AutomationEntity } from "../../../data/automation";
|
||||
import { fireRelatedContext, fullEntitiesContext } from "../../../data/context";
|
||||
import type { ConfigEntry } from "../../../data/config_entries";
|
||||
import {
|
||||
brandsAccessTokenContext,
|
||||
configEntriesContext,
|
||||
fireRelatedContext,
|
||||
fullEntitiesContext,
|
||||
} from "../../../data/context";
|
||||
import type { DeviceRegistryEntry } from "../../../data/device/device_registry";
|
||||
import { sortDeviceRegistryByName } from "../../../data/device/device_registry";
|
||||
import type { EntityRegistryEntry } from "../../../data/entity/entity_registry";
|
||||
@@ -68,6 +78,7 @@ import "../../../layouts/hass-error-screen";
|
||||
import "../../../layouts/hass-subpage";
|
||||
import { haStyle } from "../../../resources/styles";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
import { brandsUrl } from "../../../util/brands-url";
|
||||
import "../../logbook/ha-logbook";
|
||||
import { isHelperDomain } from "../helpers/const";
|
||||
import {
|
||||
@@ -149,6 +160,24 @@ class HaConfigAreaPage extends LitElement {
|
||||
@consume({ context: fullEntitiesContext, subscribe: true })
|
||||
_entityReg: EntityRegistryEntry[] = [];
|
||||
|
||||
// Integration domain per config entry ID, to show the brand icon of a device
|
||||
@state()
|
||||
@consume({ context: configEntriesContext, subscribe: true })
|
||||
@transform<ConfigEntry[], Record<string, string>>({
|
||||
transformer: (entries) =>
|
||||
entries
|
||||
? Object.fromEntries(
|
||||
entries.map((entry) => [entry.entry_id, entry.domain])
|
||||
)
|
||||
: undefined,
|
||||
})
|
||||
private _configEntryDomains?: Record<string, string>;
|
||||
|
||||
@state()
|
||||
@consume({ context: brandsAccessTokenContext, subscribe: true })
|
||||
// @ts-ignore re-render trigger only, its value is never read
|
||||
private _brandsAccessToken?: string;
|
||||
|
||||
@state() private _related?: RelatedResult;
|
||||
|
||||
private _logbookTime = { recent: 86400 };
|
||||
@@ -387,6 +416,7 @@ class HaConfigAreaPage extends LitElement {
|
||||
.href=${`/config/devices/device/${device.id}`}
|
||||
.headline=${device.name}
|
||||
>
|
||||
${this._renderDeviceIcon(device)}
|
||||
<ha-icon-next slot="end"></ha-icon-next>
|
||||
</ha-list-item-button>
|
||||
`
|
||||
@@ -419,6 +449,7 @@ class HaConfigAreaPage extends LitElement {
|
||||
.entity=${entity}
|
||||
.headline=${entity.name ?? undefined}
|
||||
>
|
||||
${this._renderEntityIcon(entity)}
|
||||
<ha-icon-next slot="end"></ha-icon-next>
|
||||
</ha-list-item-button>
|
||||
`
|
||||
@@ -794,14 +825,73 @@ class HaConfigAreaPage extends LitElement {
|
||||
return { groupedEntities, relatedEntities };
|
||||
}
|
||||
|
||||
private _renderDeviceIcon(device: DeviceRegistryEntry) {
|
||||
const entryIds = device.primary_config_entry
|
||||
? [device.primary_config_entry, ...device.config_entries]
|
||||
: device.config_entries;
|
||||
const domain = entryIds
|
||||
.map((entryId) => this._configEntryDomains?.[entryId])
|
||||
.find(Boolean);
|
||||
|
||||
if (!domain) {
|
||||
return html`<ha-svg-icon
|
||||
slot="start"
|
||||
.path=${
|
||||
device.entry_type === "service"
|
||||
? mdiTransitConnectionVariant
|
||||
: mdiDevices
|
||||
}
|
||||
></ha-svg-icon>`;
|
||||
}
|
||||
|
||||
return html`<img
|
||||
slot="start"
|
||||
alt=""
|
||||
crossorigin="anonymous"
|
||||
referrerpolicy="no-referrer"
|
||||
src=${brandsUrl(
|
||||
{
|
||||
domain,
|
||||
type: "icon",
|
||||
darkOptimized: this.hass.themes?.darkMode,
|
||||
},
|
||||
this.hass.auth.data.hassUrl
|
||||
)}
|
||||
@error=${this._onImageError}
|
||||
@load=${this._onImageLoad}
|
||||
/>`;
|
||||
}
|
||||
|
||||
private _renderEntityIcon(entity: EntityRegistryEntry) {
|
||||
const stateObj = this.hass.states[entity.entity_id];
|
||||
return stateObj
|
||||
? html`<ha-state-icon slot="start" .stateObj=${stateObj}></ha-state-icon>`
|
||||
: html`<ha-domain-icon
|
||||
slot="start"
|
||||
.domain=${computeDomain(entity.entity_id)}
|
||||
.icon=${entity.icon ?? undefined}
|
||||
></ha-domain-icon>`;
|
||||
}
|
||||
|
||||
// Keep the space of a brand icon that failed to load so the rows stay aligned
|
||||
private _onImageError(ev: HASSDomCurrentTargetEvent<HTMLImageElement>) {
|
||||
ev.currentTarget.style.visibility = "hidden";
|
||||
}
|
||||
|
||||
private _onImageLoad(ev: HASSDomCurrentTargetEvent<HTMLImageElement>) {
|
||||
ev.currentTarget.style.visibility = "";
|
||||
}
|
||||
|
||||
private _renderScene(name: string, entityState: SceneEntity) {
|
||||
return entityState.attributes.id
|
||||
? this._renderLink(
|
||||
name,
|
||||
entityState,
|
||||
`/config/scene/edit/${entityState.attributes.id}`
|
||||
)
|
||||
: this._renderNotEditable(
|
||||
name,
|
||||
entityState,
|
||||
`scene-${slugify(entityState.entity_id)}`
|
||||
);
|
||||
}
|
||||
@@ -810,22 +900,30 @@ class HaConfigAreaPage extends LitElement {
|
||||
return entityState.attributes.id
|
||||
? this._renderLink(
|
||||
name,
|
||||
entityState,
|
||||
`/config/automation/edit/${encodeURIComponent(entityState.attributes.id)}`
|
||||
)
|
||||
: this._renderNotEditable(
|
||||
name,
|
||||
entityState,
|
||||
`automation-${slugify(entityState.entity_id)}`
|
||||
);
|
||||
}
|
||||
|
||||
private _renderLink(name: string, href: string) {
|
||||
private _renderLink(name: string, entityState: HassEntity, href: string) {
|
||||
return html`<ha-list-item-button .href=${href} .headline=${name}>
|
||||
<ha-state-icon slot="start" .stateObj=${entityState}></ha-state-icon>
|
||||
<ha-icon-next slot="end"></ha-icon-next>
|
||||
</ha-list-item-button>`;
|
||||
}
|
||||
|
||||
private _renderNotEditable(name: string, id: string) {
|
||||
private _renderNotEditable(
|
||||
name: string,
|
||||
entityState: HassEntity,
|
||||
id: string
|
||||
) {
|
||||
return html`<ha-list-item-base id=${id} .headline=${name}>
|
||||
<ha-state-icon slot="start" .stateObj=${entityState}></ha-state-icon>
|
||||
<ha-icon-next slot="end"></ha-icon-next>
|
||||
</ha-list-item-base>
|
||||
<ha-tooltip .for=${id} .distance=${-4}>
|
||||
@@ -841,7 +939,7 @@ class HaConfigAreaPage extends LitElement {
|
||||
if (entry) {
|
||||
url = `/config/script/edit/${entry.unique_id}`;
|
||||
}
|
||||
return this._renderLink(name, url);
|
||||
return this._renderLink(name, entityState, url);
|
||||
}
|
||||
|
||||
private async _findRelated() {
|
||||
@@ -1017,6 +1115,11 @@ class HaConfigAreaPage extends LitElement {
|
||||
ha-list-item-button ha-icon-next {
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
img[slot="start"] {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
object-fit: contain;
|
||||
}
|
||||
ha-card > *:first-child {
|
||||
margin-top: -16px;
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ import { documentationUrl } from "../../../util/documentation-url";
|
||||
import { turnOnOffEntity } from "../../lovelace/common/entity/turn-on-off-entity";
|
||||
import { showAreaRegistryDetailDialog } from "../areas/show-dialog-area-registry-detail";
|
||||
import { showAssignCategoryDialog } from "../category/show-dialog-assign-category";
|
||||
import { renderCategoryGroupActions } from "../category/render-category-group-actions";
|
||||
import { categoryGroupActions } from "../category/category-group-actions";
|
||||
import { showCategoryRegistryDetailDialog } from "../category/show-dialog-category-registry-detail";
|
||||
import {
|
||||
getAreaTableColumn,
|
||||
@@ -537,6 +537,12 @@ class HaAutomationPicker extends SubscribeMixin(LitElement) {
|
||||
}
|
||||
.columns=${this._columns(this.narrow, this.hass.localize, automations)}
|
||||
.initialGroupColumn=${this._tableSettings.grouping}
|
||||
.renderGroupActions=${this._groupActions(
|
||||
"automation",
|
||||
this._categories,
|
||||
this._tableSettings.grouping,
|
||||
this._categoryDeleted
|
||||
)}
|
||||
.initialCollapsedGroups=${this._activeCollapsed}
|
||||
.initialSorting=${this._tableSettings.sorting}
|
||||
.columnOrder=${this._activeColumnOrder}
|
||||
@@ -565,12 +571,6 @@ class HaAutomationPicker extends SubscribeMixin(LitElement) {
|
||||
.path=${mdiHelpCircleOutline}
|
||||
@click=${this._showHelp}
|
||||
></ha-icon-button>
|
||||
${renderCategoryGroupActions(
|
||||
"automation",
|
||||
this._categories,
|
||||
this._tableSettings.grouping,
|
||||
this._categoryDeleted
|
||||
)}
|
||||
<ha-filter-floor-areas
|
||||
.type=${"automation"}
|
||||
.value=${this._filters["ha-filter-floor-areas"]?.value}
|
||||
@@ -941,6 +941,8 @@ class HaAutomationPicker extends SubscribeMixin(LitElement) {
|
||||
});
|
||||
};
|
||||
|
||||
private _groupActions = memoizeOne(categoryGroupActions);
|
||||
|
||||
private _categoryDeleted = (categoryId: string) => {
|
||||
const value = this._filters["ha-filter-categories"]?.value;
|
||||
|
||||
|
||||
+14
-16
@@ -1,6 +1,5 @@
|
||||
import { html, nothing } from "lit";
|
||||
import { repeat } from "lit/directives/repeat";
|
||||
import { groupActionsSlot } from "../../../components/data-table/ha-data-table";
|
||||
import type { DataTableGroupActions } from "../../../components/data-table/ha-data-table";
|
||||
import type { CategoryRegistryEntry } from "../../../data/category_registry";
|
||||
import "./ha-category-group-actions";
|
||||
|
||||
@@ -8,22 +7,21 @@ import "./ha-category-group-actions";
|
||||
// group headers of a table grouped by category, which names its groups after
|
||||
// the categories. Other groupings can have groups with the same names.
|
||||
// onDeleted lets the page take a deleted category out of its filter.
|
||||
export const renderCategoryGroupActions = (
|
||||
export const categoryGroupActions = (
|
||||
scope: string,
|
||||
categories: CategoryRegistryEntry[] | undefined,
|
||||
grouping: string | undefined,
|
||||
onDeleted: (categoryId: string) => void
|
||||
) =>
|
||||
): DataTableGroupActions | undefined =>
|
||||
grouping === "category"
|
||||
? repeat(
|
||||
categories ?? [],
|
||||
(category) => category.category_id,
|
||||
(category) =>
|
||||
html`<ha-category-group-actions
|
||||
slot=${groupActionsSlot(category.name)}
|
||||
.category=${category}
|
||||
.scope=${scope}
|
||||
.onDeleted=${onDeleted}
|
||||
></ha-category-group-actions>`
|
||||
)
|
||||
: nothing;
|
||||
? (group) => {
|
||||
const category = categories?.find((cat) => cat.name === group);
|
||||
return category
|
||||
? html`<ha-category-group-actions
|
||||
.category=${category}
|
||||
.scope=${scope}
|
||||
.onDeleted=${onDeleted}
|
||||
></ha-category-group-actions>`
|
||||
: nothing;
|
||||
}
|
||||
: undefined;
|
||||
@@ -311,6 +311,9 @@ export class CloudRemotePref extends LitElement {
|
||||
ha-list-base {
|
||||
--ha-row-item-padding-inline: 0;
|
||||
}
|
||||
ha-list-item-base::part(supporting-text) {
|
||||
white-space: normal;
|
||||
}
|
||||
ha-tip {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
|
||||
@@ -95,6 +95,7 @@ import {
|
||||
showAlertDialog,
|
||||
showConfirmationDialog,
|
||||
} from "../../../dialogs/generic/show-dialog-box";
|
||||
import { showMoreInfoDialog } from "../../../dialogs/more-info/show-ha-more-info-dialog";
|
||||
import { showVoiceAssistantSetupDialog } from "../../../dialogs/voice-assistant-setup/show-voice-assistant-setup-dialog";
|
||||
import "../../../layouts/hass-error-screen";
|
||||
import "../../../layouts/hass-subpage";
|
||||
@@ -994,7 +995,13 @@ export class HaConfigDevicePage extends LitElement {
|
||||
(batteryDomain === "binary_sensor" ||
|
||||
!Number.isNaN(Number(battery.state)))
|
||||
? html`
|
||||
<div class="battery">
|
||||
<button
|
||||
class="battery"
|
||||
aria-label=${`${this.hass.formatEntityName(
|
||||
battery
|
||||
)} ${this.hass.formatEntityState(battery)}`}
|
||||
@click=${this._showBatteryMoreInfo}
|
||||
>
|
||||
${
|
||||
batteryDomain === "sensor"
|
||||
? this.hass.formatEntityState(battery)
|
||||
@@ -1004,7 +1011,7 @@ export class HaConfigDevicePage extends LitElement {
|
||||
.batteryStateObj=${battery}
|
||||
.batteryChargingStateObj=${batteryChargingState}
|
||||
></ha-battery-icon>
|
||||
</div>
|
||||
</button>
|
||||
`
|
||||
: ""
|
||||
}
|
||||
@@ -1387,6 +1394,15 @@ export class HaConfigDevicePage extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
private _showBatteryMoreInfo() {
|
||||
const batteryEntity = this._batteryEntity(
|
||||
this._entities(this.deviceId, this._entityReg, this.hass.devices)
|
||||
);
|
||||
if (batteryEntity) {
|
||||
showMoreInfoDialog(this, { entityId: batteryEntity.entity_id });
|
||||
}
|
||||
}
|
||||
|
||||
private _computeEntityName(
|
||||
entity: EntityRegistryEntry,
|
||||
devices: HomeAssistant["devices"]
|
||||
@@ -1756,6 +1772,19 @@ export class HaConfigDevicePage extends LitElement {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
white-space: nowrap;
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
border-radius: var(--ha-border-radius-sm);
|
||||
}
|
||||
|
||||
.battery:focus-visible {
|
||||
outline: 2px solid var(--primary-color);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.column > *:not(:first-child) {
|
||||
|
||||
@@ -18,6 +18,7 @@ import { consume } from "../../../common/decorators/consume";
|
||||
import { storage } from "../../../common/decorators/storage";
|
||||
import type { HASSDomEvent } from "../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import { computeAreaName } from "../../../common/entity/compute_area_name";
|
||||
import { computeDeviceNameDisplay } from "../../../common/entity/compute_device_name";
|
||||
import { computeFloorName } from "../../../common/entity/compute_floor_name";
|
||||
import { computeStateDomain } from "../../../common/entity/compute_state_domain";
|
||||
@@ -28,13 +29,13 @@ import {
|
||||
} from "../../../common/integrations/protocolIntegrationPicked";
|
||||
import { navigate } from "../../../common/navigate";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import { deepEqual } from "../../../common/util/deep-equal";
|
||||
import {
|
||||
devicesFilterQueryParamConfig,
|
||||
devicesFilterQueryParams,
|
||||
devicesFilterQueryString,
|
||||
devicesLinkFromUrl,
|
||||
} from "../../../common/url/devices-query-params";
|
||||
import { deepEqual } from "../../../common/util/deep-equal";
|
||||
import {
|
||||
hasRejectedItems,
|
||||
rejectedItems,
|
||||
@@ -47,8 +48,6 @@ import type {
|
||||
import "../../../components/data-table/ha-data-table-labels";
|
||||
import "../../../components/entity/ha-battery-icon";
|
||||
import "../../../components/ha-alert";
|
||||
import "../../../components/skeleton/ha-skeleton-icon";
|
||||
import "../../../components/skeleton/ha-skeleton-text";
|
||||
import "../../../components/ha-button";
|
||||
import "../../../components/ha-dropdown";
|
||||
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
|
||||
@@ -58,6 +57,8 @@ import "../../../components/ha-filter-integrations";
|
||||
import "../../../components/ha-filter-labels";
|
||||
import "../../../components/ha-filter-states";
|
||||
import "../../../components/ha-icon-button";
|
||||
import "../../../components/skeleton/ha-skeleton-icon";
|
||||
import "../../../components/skeleton/ha-skeleton-text";
|
||||
import { createAreaRegistryEntry } from "../../../data/area/area_registry";
|
||||
import type { ConfigEntry, SubEntry } from "../../../data/config_entries";
|
||||
import { getSubEntries, sortConfigEntries } from "../../../data/config_entries";
|
||||
@@ -67,7 +68,6 @@ import {
|
||||
deserializeFilters,
|
||||
serializeFilters,
|
||||
} from "../../../data/data_table_filters";
|
||||
import { computeDeviceAreaLabel } from "../../../data/device/device_picker";
|
||||
import type {
|
||||
DeviceEntityLookup,
|
||||
DeviceRegistryEntry,
|
||||
@@ -451,31 +451,19 @@ export class HaConfigDeviceDashboard extends LitElement {
|
||||
const parentDevice = device.parent_device_id
|
||||
? this.hass.devices[device.parent_device_id]
|
||||
: undefined;
|
||||
const viaDevice = device.via_device_id
|
||||
? this.hass.devices[device.via_device_id]
|
||||
: undefined;
|
||||
// The device that identifies this device's family: its parent for a
|
||||
// child device, itself for a device that has children.
|
||||
const familyParentDevice =
|
||||
parentDevice ??
|
||||
(deviceIdsWithChildren.has(device.id) ? device : undefined);
|
||||
|
||||
const { areaName } = computeDeviceAreaLabel(
|
||||
device,
|
||||
this.hass.areas,
|
||||
this.hass.devices,
|
||||
this.hass.localize,
|
||||
this.hass.language,
|
||||
this.hass.translationMetadata
|
||||
);
|
||||
const area = getDeviceArea(device, areas, this.hass.devices);
|
||||
const areaName = area ? computeAreaName(area) : undefined;
|
||||
|
||||
const floorArea =
|
||||
getDeviceArea(device, areas, this.hass.devices) ??
|
||||
(device.via_device_id && this.hass.devices[device.via_device_id]
|
||||
? getDeviceArea(
|
||||
this.hass.devices[device.via_device_id],
|
||||
areas,
|
||||
this.hass.devices
|
||||
)
|
||||
: undefined);
|
||||
const floorId = floorArea?.floor_id;
|
||||
const floorId = area?.floor_id;
|
||||
const floorName =
|
||||
floorId && this.hass.floors?.[floorId]
|
||||
? computeFloorName(this.hass.floors[floorId])
|
||||
@@ -511,6 +499,9 @@ export class HaConfigDeviceDashboard extends LitElement {
|
||||
parent_device_name: parentDevice
|
||||
? computeDeviceNameDisplay(parentDevice, this.hass.localize)
|
||||
: "",
|
||||
via_device_name: viaDevice
|
||||
? computeDeviceNameDisplay(viaDevice, this.hass.localize)
|
||||
: undefined,
|
||||
// Grouping key that keeps a device with its family: children group
|
||||
// under their parent's name, a parent groups under its own name, and
|
||||
// standalone devices stay ungrouped. The name is always computed from
|
||||
@@ -634,6 +625,15 @@ export class HaConfigDeviceDashboard extends LitElement {
|
||||
minWidth: "120px",
|
||||
template: (device) => device.parent_device_name || "",
|
||||
},
|
||||
via_device_name: {
|
||||
title: localize("ui.panel.config.devices.data_table.connected_via"),
|
||||
sortable: true,
|
||||
filterable: true,
|
||||
groupable: true,
|
||||
urlName: "via",
|
||||
defaultHidden: true,
|
||||
minWidth: "120px",
|
||||
},
|
||||
manufacturer: {
|
||||
title: localize("ui.panel.config.devices.data_table.manufacturer"),
|
||||
sortable: true,
|
||||
|
||||
+95
-67
@@ -1,10 +1,11 @@
|
||||
import {
|
||||
mdiAlertCircle,
|
||||
mdiDelete,
|
||||
mdiWater,
|
||||
mdiDragHorizontalVariant,
|
||||
mdiFire,
|
||||
mdiPencil,
|
||||
mdiPlus,
|
||||
mdiWater,
|
||||
} from "@mdi/js";
|
||||
import type { CSSResultGroup, TemplateResult } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
@@ -24,9 +25,13 @@ import type {
|
||||
EnergyPreferences,
|
||||
EnergyPreferencesValidation,
|
||||
EnergyValidationIssue,
|
||||
WaterGasResource,
|
||||
} from "../../../../data/energy";
|
||||
import {
|
||||
computeEnergyLabel,
|
||||
getEnergyGasUnitClass,
|
||||
getWaterGasDevices,
|
||||
getWaterGasDevicesKey,
|
||||
saveEnergyPreferences,
|
||||
} from "../../../../data/energy";
|
||||
import type { StatisticsMetaData } from "../../../../data/recorder";
|
||||
@@ -37,14 +42,22 @@ import {
|
||||
import { haStyle } from "../../../../resources/styles";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import { documentationUrl } from "../../../../util/documentation-url";
|
||||
import { showEnergySettingsDeviceWaterDialog } from "../dialogs/show-dialogs-energy";
|
||||
import { showEnergySettingsDeviceWaterGasDialog } from "../dialogs/show-dialogs-energy";
|
||||
import "./ha-energy-validation-result";
|
||||
import { energyCardStyles } from "./styles";
|
||||
import type { LocalizeKeys } from "../../../../common/translations/localize";
|
||||
|
||||
@customElement("ha-energy-device-settings-water")
|
||||
export class EnergyDeviceSettingsWater extends LitElement {
|
||||
const ICONS: Record<WaterGasResource, string> = {
|
||||
water: mdiWater,
|
||||
gas: mdiFire,
|
||||
};
|
||||
|
||||
@customElement("ha-energy-device-settings-water-gas")
|
||||
export class EnergyDeviceSettingsWaterGas extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public resource!: WaterGasResource;
|
||||
|
||||
@property({ attribute: false })
|
||||
public preferences!: EnergyPreferences;
|
||||
|
||||
@@ -54,34 +67,51 @@ export class EnergyDeviceSettingsWater extends LitElement {
|
||||
@property({ attribute: false })
|
||||
public validationResult?: EnergyPreferencesValidation;
|
||||
|
||||
private get _devices(): DeviceConsumptionEnergyPreference[] {
|
||||
return getWaterGasDevices(this.preferences, this.resource);
|
||||
}
|
||||
|
||||
private _withDevices(
|
||||
devices: DeviceConsumptionEnergyPreference[]
|
||||
): EnergyPreferences {
|
||||
return {
|
||||
...this.preferences,
|
||||
[getWaterGasDevicesKey(this.resource)]: devices,
|
||||
} as EnergyPreferences;
|
||||
}
|
||||
|
||||
private _t(key: string): string {
|
||||
return this.hass.localize(
|
||||
`ui.panel.config.energy.device_consumption_${this.resource}.${key}` as LocalizeKeys
|
||||
);
|
||||
}
|
||||
|
||||
protected render(): TemplateResult {
|
||||
const devices = this._devices;
|
||||
const validation =
|
||||
this.validationResult?.[getWaterGasDevicesKey(this.resource)];
|
||||
|
||||
return html`
|
||||
<ha-card>
|
||||
<h1 class="card-header">
|
||||
<ha-svg-icon .path=${mdiWater}></ha-svg-icon>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.title"
|
||||
)}
|
||||
<ha-svg-icon .path=${ICONS[this.resource]}></ha-svg-icon>
|
||||
${this._t("title")}
|
||||
</h1>
|
||||
|
||||
<div class="card-content">
|
||||
<p>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.sub"
|
||||
)}
|
||||
${this._t("sub")}
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
href=${documentationUrl(
|
||||
this.hass,
|
||||
"/docs/energy/water/#individual-devices"
|
||||
`/docs/energy/${this.resource}/#individual-${this.resource}-devices`
|
||||
)}
|
||||
>${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.learn_more"
|
||||
)}</a
|
||||
>${this._t("learn_more")}</a
|
||||
>
|
||||
</p>
|
||||
${this.validationResult?.device_consumption_water.map(
|
||||
${validation?.map(
|
||||
(result) => html`
|
||||
<ha-energy-validation-result
|
||||
.hass=${this.hass}
|
||||
@@ -90,7 +120,7 @@ export class EnergyDeviceSettingsWater extends LitElement {
|
||||
`
|
||||
)}
|
||||
${
|
||||
this.preferences.device_consumption_water.length > 0
|
||||
devices.length > 0
|
||||
? html`
|
||||
<div class="items-container">
|
||||
<ha-sortable
|
||||
@@ -99,7 +129,7 @@ export class EnergyDeviceSettingsWater extends LitElement {
|
||||
>
|
||||
<div class="devices">
|
||||
${repeat(
|
||||
this.preferences.device_consumption_water,
|
||||
devices,
|
||||
(device) => device.stat_consumption,
|
||||
(device, index) => html`
|
||||
<div class="row" .device=${device}>
|
||||
@@ -110,9 +140,7 @@ export class EnergyDeviceSettingsWater extends LitElement {
|
||||
</div>
|
||||
${this._renderName(device)}
|
||||
${this._renderIssueIndicator(
|
||||
this.validationResult?.device_consumption_water[
|
||||
index
|
||||
],
|
||||
validation?.[index],
|
||||
index
|
||||
)}
|
||||
<ha-icon-button
|
||||
@@ -138,9 +166,7 @@ export class EnergyDeviceSettingsWater extends LitElement {
|
||||
<div class="row">
|
||||
<ha-button @click=${this._addDevice} appearance="filled" size="s">
|
||||
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon
|
||||
>${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.add_device"
|
||||
)}</ha-button
|
||||
>${this._t("add_device")}</ha-button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
@@ -203,64 +229,69 @@ export class EnergyDeviceSettingsWater extends LitElement {
|
||||
private _itemMoved(ev: CustomEvent): void {
|
||||
ev.stopPropagation();
|
||||
const { oldIndex, newIndex } = ev.detail;
|
||||
const devices = this.preferences.device_consumption_water.concat();
|
||||
const devices = this._devices.concat();
|
||||
const device = devices.splice(oldIndex, 1)[0];
|
||||
devices.splice(newIndex, 0, device);
|
||||
|
||||
const newPrefs = {
|
||||
...this.preferences,
|
||||
device_consumption_water: devices,
|
||||
};
|
||||
const newPrefs = this._withDevices(devices);
|
||||
fireEvent(this, "value-changed", { value: newPrefs });
|
||||
this._savePreferences(newPrefs);
|
||||
}
|
||||
|
||||
private _allowedUnitClass(excludeSource?: string) {
|
||||
return this.resource === "gas"
|
||||
? getEnergyGasUnitClass(
|
||||
this.preferences,
|
||||
excludeSource,
|
||||
this.statsMetadata,
|
||||
"device"
|
||||
)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
private _editDevice(ev) {
|
||||
const origDevice: DeviceConsumptionEnergyPreference =
|
||||
ev.currentTarget.closest(".row").device;
|
||||
showEnergySettingsDeviceWaterDialog(this, {
|
||||
showEnergySettingsDeviceWaterGasDialog(this, {
|
||||
resource: this.resource,
|
||||
statsMetadata: this.statsMetadata,
|
||||
device: { ...origDevice },
|
||||
device_consumptions: this.preferences
|
||||
.device_consumption_water as DeviceConsumptionEnergyPreference[],
|
||||
allowedUnitClass: this._allowedUnitClass(origDevice.stat_consumption),
|
||||
device_consumptions: this._devices,
|
||||
saveCallback: async (newDevice) => {
|
||||
const newPrefs = {
|
||||
...this.preferences,
|
||||
device_consumption_water:
|
||||
this.preferences.device_consumption_water.map((d) =>
|
||||
d === origDevice ? newDevice : d
|
||||
),
|
||||
};
|
||||
this._sanitizeParents(newPrefs);
|
||||
await this._savePreferences(newPrefs);
|
||||
const newPrefs = this._withDevices(
|
||||
this._devices.map((d) => (d === origDevice ? newDevice : d))
|
||||
);
|
||||
await this._savePreferences(this._sanitizeParents(newPrefs));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private _addDevice() {
|
||||
showEnergySettingsDeviceWaterDialog(this, {
|
||||
showEnergySettingsDeviceWaterGasDialog(this, {
|
||||
resource: this.resource,
|
||||
statsMetadata: this.statsMetadata,
|
||||
device_consumptions: this.preferences
|
||||
.device_consumption_water as DeviceConsumptionEnergyPreference[],
|
||||
allowedUnitClass: this._allowedUnitClass(),
|
||||
device_consumptions: this._devices,
|
||||
saveCallback: async (device) => {
|
||||
await this._savePreferences({
|
||||
...this.preferences,
|
||||
device_consumption_water:
|
||||
this.preferences.device_consumption_water.concat(device),
|
||||
});
|
||||
await this._savePreferences(
|
||||
this._withDevices(this._devices.concat(device))
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private _sanitizeParents(prefs: EnergyPreferences) {
|
||||
const statIds = prefs.device_consumption_water.map(
|
||||
(d) => d.stat_consumption
|
||||
);
|
||||
prefs.device_consumption_water.forEach((d) => {
|
||||
if (d.included_in_stat && !statIds.includes(d.included_in_stat)) {
|
||||
delete d.included_in_stat;
|
||||
}
|
||||
});
|
||||
private _sanitizeParents(prefs: EnergyPreferences): EnergyPreferences {
|
||||
const devices = getWaterGasDevices(prefs, this.resource);
|
||||
const statIds = devices.map((d) => d.stat_consumption);
|
||||
return {
|
||||
...prefs,
|
||||
[getWaterGasDevicesKey(this.resource)]: devices.map((d) =>
|
||||
d.included_in_stat && !statIds.includes(d.included_in_stat)
|
||||
? { ...d, included_in_stat: undefined }
|
||||
: d
|
||||
),
|
||||
} as EnergyPreferences;
|
||||
}
|
||||
|
||||
private async _deleteDevice(ev) {
|
||||
@@ -276,14 +307,11 @@ export class EnergyDeviceSettingsWater extends LitElement {
|
||||
}
|
||||
|
||||
try {
|
||||
const newPrefs = {
|
||||
...this.preferences,
|
||||
device_consumption_water:
|
||||
this.preferences.device_consumption_water.filter(
|
||||
(device) => device !== deviceToDelete
|
||||
),
|
||||
};
|
||||
this._sanitizeParents(newPrefs);
|
||||
const newPrefs = this._sanitizeParents(
|
||||
this._withDevices(
|
||||
this._devices.filter((device) => device !== deviceToDelete)
|
||||
)
|
||||
);
|
||||
await this._savePreferences(newPrefs);
|
||||
} catch (err: any) {
|
||||
showAlertDialog(this, { title: `Failed to save config: ${err.message}` });
|
||||
@@ -330,6 +358,6 @@ export class EnergyDeviceSettingsWater extends LitElement {
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-energy-device-settings-water": EnergyDeviceSettingsWater;
|
||||
"ha-energy-device-settings-water-gas": EnergyDeviceSettingsWaterGas;
|
||||
}
|
||||
}
|
||||
@@ -151,7 +151,8 @@ export class EnergyGasSettings extends LitElement {
|
||||
allowedGasUnitClass: getEnergyGasUnitClass(
|
||||
this.preferences,
|
||||
undefined,
|
||||
this.statsMetadata
|
||||
this.statsMetadata,
|
||||
"source"
|
||||
),
|
||||
gas_sources: this.preferences.energy_sources.filter(
|
||||
(src) => src.type === "gas"
|
||||
@@ -175,7 +176,8 @@ export class EnergyGasSettings extends LitElement {
|
||||
allowedGasUnitClass: getEnergyGasUnitClass(
|
||||
this.preferences,
|
||||
origSource.stat_energy_from,
|
||||
this.statsMetadata
|
||||
this.statsMetadata,
|
||||
"source"
|
||||
),
|
||||
gas_sources: this.preferences.energy_sources.filter(
|
||||
(src) => src.type === "gas"
|
||||
|
||||
+93
-55
@@ -10,7 +10,10 @@ import "../../../../components/ha-dialog-footer";
|
||||
import "../../../../components/input/ha-input";
|
||||
import "./ha-energy-upstream-device-picker";
|
||||
import type { HaInput } from "../../../../components/input/ha-input";
|
||||
import type { DeviceConsumptionEnergyPreference } from "../../../../data/energy";
|
||||
import type {
|
||||
DeviceConsumptionEnergyPreference,
|
||||
WaterGasResource,
|
||||
} from "../../../../data/energy";
|
||||
import {
|
||||
computeEnergyLabel,
|
||||
energyStatisticHelpUrl,
|
||||
@@ -26,22 +29,22 @@ import { haStyleDialog } from "../../../../resources/styles";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
|
||||
import type { IntegralUnits } from "./energy-integral";
|
||||
import { confirmIntegrals, integralUnits } from "./energy-integral";
|
||||
import type { EnergySettingsDeviceWaterDialogParams } from "./show-dialogs-energy";
|
||||
import type { EnergySettingsDeviceWaterGasDialogParams } from "./show-dialogs-energy";
|
||||
import type { LocalizeKeys } from "../../../../common/translations/localize";
|
||||
|
||||
const volumeUnitClasses = ["volume"];
|
||||
const flowRateUnitClasses = ["volume_flow_rate"];
|
||||
|
||||
// Without a water sensor, saving offers to create one from the flow rate sensor
|
||||
// Without a consumption sensor, saving offers to create one from the flow rate sensor
|
||||
type DeviceConsumptionDraft = Partial<DeviceConsumptionEnergyPreference>;
|
||||
|
||||
@customElement("dialog-energy-device-settings-water")
|
||||
export class DialogEnergyDeviceSettingsWater
|
||||
@customElement("dialog-energy-device-settings-water-gas")
|
||||
export class DialogEnergyDeviceSettingsWaterGas
|
||||
extends DirtyStateProviderMixin<DeviceConsumptionDraft | null>()(LitElement)
|
||||
implements HassDialog<EnergySettingsDeviceWaterDialogParams>
|
||||
implements HassDialog<EnergySettingsDeviceWaterGasDialogParams>
|
||||
{
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@state() private _params?: EnergySettingsDeviceWaterDialogParams;
|
||||
@state() private _params?: EnergySettingsDeviceWaterGasDialogParams;
|
||||
|
||||
@state() private _open = false;
|
||||
|
||||
@@ -49,6 +52,8 @@ export class DialogEnergyDeviceSettingsWater
|
||||
|
||||
@state() private _volume_units?: string[];
|
||||
|
||||
@state() private _energy_units?: string[];
|
||||
|
||||
@state() private _flow_rate_units?: string[];
|
||||
|
||||
@state() private _error?: string;
|
||||
@@ -62,7 +67,7 @@ export class DialogEnergyDeviceSettingsWater
|
||||
private _possibleParents: DeviceConsumptionEnergyPreference[] = [];
|
||||
|
||||
public async showDialog(
|
||||
params: EnergySettingsDeviceWaterDialogParams
|
||||
params: EnergySettingsDeviceWaterGasDialogParams
|
||||
): Promise<void> {
|
||||
this._params = params;
|
||||
this._device = this._params.device;
|
||||
@@ -70,8 +75,13 @@ export class DialogEnergyDeviceSettingsWater
|
||||
this._saving = false;
|
||||
this._computePossibleParents();
|
||||
this._volume_units = (
|
||||
await getSensorDeviceClassConvertibleUnits(this.hass, "water")
|
||||
await getSensorDeviceClassConvertibleUnits(this.hass, params.resource)
|
||||
).units;
|
||||
this._energy_units =
|
||||
params.resource === "gas"
|
||||
? (await getSensorDeviceClassConvertibleUnits(this.hass, "energy"))
|
||||
.units
|
||||
: [];
|
||||
this._flow_rate_units = (
|
||||
await getSensorDeviceClassConvertibleUnits(this.hass, "volume_flow_rate")
|
||||
).units;
|
||||
@@ -86,6 +96,38 @@ export class DialogEnergyDeviceSettingsWater
|
||||
this._initDirtyTracking({ type: "deep" }, this._device ?? null);
|
||||
}
|
||||
|
||||
private get _resource(): WaterGasResource {
|
||||
return this._params!.resource;
|
||||
}
|
||||
|
||||
private _t(key: string, params?: Record<string, string>): string {
|
||||
return this.hass.localize(
|
||||
`ui.panel.config.energy.device_consumption_${this._resource}.dialog.${key}` as LocalizeKeys,
|
||||
params as any
|
||||
);
|
||||
}
|
||||
|
||||
private get _unitClasses(): string[] {
|
||||
if (this._params?.allowedUnitClass) {
|
||||
return [this._params.allowedUnitClass];
|
||||
}
|
||||
return this._resource === "gas" ? ["volume", "energy"] : ["volume"];
|
||||
}
|
||||
|
||||
private get _deviceClasses(): string[] | undefined {
|
||||
if (this._resource === "water") {
|
||||
return undefined;
|
||||
}
|
||||
switch (this._params?.allowedUnitClass) {
|
||||
case "volume":
|
||||
return ["gas"];
|
||||
case "energy":
|
||||
return ["energy"];
|
||||
default:
|
||||
return ["gas", "energy"];
|
||||
}
|
||||
}
|
||||
|
||||
private _computePossibleParents() {
|
||||
if (!this._device || !this._params) {
|
||||
this._possibleParents = [];
|
||||
@@ -101,7 +143,7 @@ export class DialogEnergyDeviceSettingsWater
|
||||
}
|
||||
});
|
||||
}
|
||||
// Saving without a water sensor can reuse the original one
|
||||
// Saving without a consumption sensor can reuse the original one
|
||||
const stat =
|
||||
this._device.stat_consumption ?? this._params.device?.stat_consumption;
|
||||
if (stat) {
|
||||
@@ -134,7 +176,15 @@ export class DialogEnergyDeviceSettingsWater
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const pickableUnit = this._volume_units?.join(", ") || "";
|
||||
const resource = this._resource;
|
||||
const pickableUnit = [
|
||||
...(this._params.allowedUnitClass === "energy"
|
||||
? []
|
||||
: this._volume_units || []),
|
||||
...(this._params.allowedUnitClass === "volume"
|
||||
? []
|
||||
: this._energy_units || []),
|
||||
].join(", ");
|
||||
|
||||
const labelStatistic =
|
||||
this._device?.stat_consumption ?? this._device?.stat_rate;
|
||||
@@ -142,9 +192,7 @@ export class DialogEnergyDeviceSettingsWater
|
||||
return html`
|
||||
<ha-dialog
|
||||
.open=${this._open}
|
||||
header-title=${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.dialog.header"
|
||||
)}
|
||||
header-title=${this._t("header")}
|
||||
.preventScrimClose=${this.isDirtyState}
|
||||
@closed=${this._dialogClosed}
|
||||
>
|
||||
@@ -152,42 +200,33 @@ export class DialogEnergyDeviceSettingsWater
|
||||
|
||||
<ha-statistic-picker
|
||||
.helpMissingEntityUrl=${energyStatisticHelpUrl}
|
||||
.includeUnitClass=${volumeUnitClasses}
|
||||
.includeUnitClass=${this._unitClasses}
|
||||
.includeDeviceClass=${this._deviceClasses}
|
||||
.value=${this._device?.stat_consumption}
|
||||
.label=${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.dialog.device_consumption_water"
|
||||
)}
|
||||
.label=${this._t(`device_consumption_${resource}`)}
|
||||
.excludeStatistics=${this._excludeList}
|
||||
@value-changed=${this._statisticChanged}
|
||||
.disabled=${this._saving}
|
||||
.helper=${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.dialog.selected_stat_intro",
|
||||
{ unit: pickableUnit }
|
||||
)}
|
||||
.helper=${this._t("selected_stat_intro", { unit: pickableUnit })}
|
||||
autofocus
|
||||
></ha-statistic-picker>
|
||||
|
||||
<ha-statistic-picker
|
||||
.includeUnitClass=${flowRateUnitClasses}
|
||||
.value=${this._device?.stat_rate}
|
||||
.label=${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.dialog.device_consumption_water_flow_rate"
|
||||
)}
|
||||
.label=${this._t(`device_consumption_${resource}_flow_rate`)}
|
||||
.excludeStatistics=${this._excludeListFlowRate}
|
||||
@value-changed=${this._flowRateStatisticChanged}
|
||||
.disabled=${this._saving}
|
||||
.invalid=${!!this._flowRateError()}
|
||||
.errorMessage=${this._flowRateError()}
|
||||
.helper=${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.dialog.selected_stat_intro",
|
||||
{ unit: this._flow_rate_units?.join(", ") || "" }
|
||||
)}
|
||||
.helper=${this._t("selected_stat_intro", {
|
||||
unit: this._flow_rate_units?.join(", ") || "",
|
||||
})}
|
||||
></ha-statistic-picker>
|
||||
|
||||
<ha-input
|
||||
.label=${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.dialog.display_name"
|
||||
)}
|
||||
.label=${this._t("display_name")}
|
||||
type="text"
|
||||
.disabled=${!this._device || this._saving}
|
||||
.value=${this._device?.name || ""}
|
||||
@@ -207,18 +246,12 @@ export class DialogEnergyDeviceSettingsWater
|
||||
|
||||
<ha-energy-upstream-device-picker
|
||||
.hass=${this.hass}
|
||||
.label=${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.dialog.included_in_device"
|
||||
)}
|
||||
.helper=${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.dialog.included_in_device_helper"
|
||||
)}
|
||||
.label=${this._t("included_in_device")}
|
||||
.helper=${this._t("included_in_device_helper")}
|
||||
.value=${this._device?.included_in_stat}
|
||||
.possibleParents=${this._possibleParents}
|
||||
.statsMetadata=${this._params.statsMetadata}
|
||||
.emptyLabel=${this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.dialog.no_upstream_devices"
|
||||
)}
|
||||
.emptyLabel=${this._t("no_upstream_devices")}
|
||||
.disabled=${!this._device || this._saving}
|
||||
@value-changed=${this._parentChanged}
|
||||
></ha-energy-upstream-device-picker>
|
||||
@@ -258,7 +291,7 @@ export class DialogEnergyDeviceSettingsWater
|
||||
this._device =
|
||||
device.stat_consumption || device.stat_rate ? device : undefined;
|
||||
this._computePossibleParents();
|
||||
// The new water sensor can rule out the picked upstream device
|
||||
// The new consumption sensor can rule out the picked upstream device
|
||||
if (
|
||||
device.included_in_stat &&
|
||||
!this._possibleParents.some(
|
||||
@@ -332,14 +365,20 @@ export class DialogEnergyDeviceSettingsWater
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.dialog.flow_rate_no_volume"
|
||||
return this._t(
|
||||
this._params?.allowedUnitClass === "energy"
|
||||
? "flow_rate_energy_sources"
|
||||
: "flow_rate_no_volume"
|
||||
);
|
||||
}
|
||||
|
||||
private _integralUnits(): IntegralUnits | undefined {
|
||||
const statRate = this._device?.stat_rate;
|
||||
if (!statRate || !this._volume_units) {
|
||||
if (
|
||||
!statRate ||
|
||||
!this._volume_units ||
|
||||
this._params?.allowedUnitClass === "energy"
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return integralUnits(
|
||||
@@ -358,7 +397,7 @@ export class DialogEnergyDeviceSettingsWater
|
||||
this._saving = true;
|
||||
try {
|
||||
const statConsumption =
|
||||
draft.stat_consumption ?? (await this._waterFromFlowRate(draft));
|
||||
draft.stat_consumption ?? (await this._volumeFromFlowRate(draft));
|
||||
if (!statConsumption) {
|
||||
return;
|
||||
}
|
||||
@@ -383,7 +422,7 @@ export class DialogEnergyDeviceSettingsWater
|
||||
}
|
||||
}
|
||||
|
||||
private async _waterFromFlowRate(
|
||||
private async _volumeFromFlowRate(
|
||||
draft: DeviceConsumptionDraft
|
||||
): Promise<string | undefined> {
|
||||
const statRate = draft.stat_rate!;
|
||||
@@ -391,8 +430,9 @@ export class DialogEnergyDeviceSettingsWater
|
||||
if (!units) {
|
||||
return undefined;
|
||||
}
|
||||
const resource = this._resource;
|
||||
const sensors = await confirmIntegrals(this, this.hass, {
|
||||
deviceClass: "water",
|
||||
deviceClass: resource,
|
||||
states: this.hass.states,
|
||||
entities: this.hass.entities,
|
||||
requests: [
|
||||
@@ -400,7 +440,7 @@ export class DialogEnergyDeviceSettingsWater
|
||||
rate: statRate,
|
||||
units,
|
||||
name: this.hass.localize(
|
||||
"ui.panel.config.energy.integral.water.sensor_name",
|
||||
`ui.panel.config.energy.integral.${resource}.sensor_name` as LocalizeKeys,
|
||||
{
|
||||
name: computeEnergyLabel(
|
||||
this.hass.states,
|
||||
@@ -409,13 +449,11 @@ export class DialogEnergyDeviceSettingsWater
|
||||
this._params?.statsMetadata?.[statRate],
|
||||
draft.name
|
||||
),
|
||||
}
|
||||
} as any
|
||||
),
|
||||
},
|
||||
],
|
||||
intro: this.hass.localize(
|
||||
"ui.panel.config.energy.device_consumption_water.dialog.water_sensor_needed"
|
||||
),
|
||||
intro: this._t(`${resource}_sensor_needed`),
|
||||
exclude: this._excludeList,
|
||||
statsMetadata: this._params?.statsMetadata,
|
||||
});
|
||||
@@ -448,6 +486,6 @@ export class DialogEnergyDeviceSettingsWater
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"dialog-energy-device-settings-water": DialogEnergyDeviceSettingsWater;
|
||||
"dialog-energy-device-settings-water-gas": DialogEnergyDeviceSettingsWaterGas;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
SolarSourceTypeEnergyPreference,
|
||||
WaterSourceTypeEnergyPreference,
|
||||
HomeSourceTypeEnergyPreference,
|
||||
WaterGasResource,
|
||||
} from "../../../../data/energy";
|
||||
import type { StatisticsMetaData } from "../../../../data/recorder";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
@@ -63,10 +64,12 @@ export interface EnergySettingsDeviceDialogParams {
|
||||
saveCallback: (device: DeviceConsumptionEnergyPreference) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface EnergySettingsDeviceWaterDialogParams {
|
||||
export interface EnergySettingsDeviceWaterGasDialogParams {
|
||||
resource: WaterGasResource;
|
||||
device?: DeviceConsumptionEnergyPreference;
|
||||
device_consumptions: DeviceConsumptionEnergyPreference[];
|
||||
statsMetadata?: Record<string, StatisticsMetaData>;
|
||||
allowedUnitClass?: EnergyGasUnitClass;
|
||||
saveCallback: (device: DeviceConsumptionEnergyPreference) => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -136,14 +139,14 @@ export const showEnergySettingsWaterDialog = (
|
||||
});
|
||||
};
|
||||
|
||||
export const showEnergySettingsDeviceWaterDialog = (
|
||||
export const showEnergySettingsDeviceWaterGasDialog = (
|
||||
element: HTMLElement,
|
||||
dialogParams: EnergySettingsDeviceWaterDialogParams
|
||||
dialogParams: EnergySettingsDeviceWaterGasDialogParams
|
||||
): void => {
|
||||
fireEvent(element, "show-dialog", {
|
||||
dialogTag: "dialog-energy-device-settings-water",
|
||||
dialogImport: () => import("./dialog-energy-device-settings-water"),
|
||||
dialogParams: dialogParams,
|
||||
dialogTag: "dialog-energy-device-settings-water-gas",
|
||||
dialogImport: () => import("./dialog-energy-device-settings-water-gas"),
|
||||
dialogParams,
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ import { haStyle } from "../../../resources/styles";
|
||||
import type { HomeAssistant, Route } from "../../../types";
|
||||
import "../../../components/ha-alert";
|
||||
import "./components/ha-energy-device-settings";
|
||||
import "./components/ha-energy-device-settings-water";
|
||||
import "./components/ha-energy-device-settings-water-gas";
|
||||
import "./components/ha-energy-grid-settings";
|
||||
import "./components/ha-energy-solar-settings";
|
||||
import "./components/ha-energy-home-settings";
|
||||
@@ -46,6 +46,7 @@ const INITIAL_CONFIG: EnergyPreferences = {
|
||||
energy_sources: [],
|
||||
device_consumption: [],
|
||||
device_consumption_water: [],
|
||||
device_consumption_gas: [],
|
||||
};
|
||||
|
||||
const TABS: PageNavigation[] = [
|
||||
@@ -202,6 +203,14 @@ class HaConfigEnergy extends LitElement {
|
||||
.validationResult=${this._validationResult}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-gas-settings>
|
||||
<ha-energy-device-settings-water-gas
|
||||
.hass=${this.hass}
|
||||
.resource=${"gas"}
|
||||
.preferences=${this._preferences!}
|
||||
.statsMetadata=${this._statsMetadata}
|
||||
.validationResult=${this._validationResult}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-device-settings-water-gas>
|
||||
`;
|
||||
case "water":
|
||||
return html`
|
||||
@@ -212,13 +221,14 @@ class HaConfigEnergy extends LitElement {
|
||||
.validationResult=${this._validationResult}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-water-settings>
|
||||
<ha-energy-device-settings-water
|
||||
<ha-energy-device-settings-water-gas
|
||||
.hass=${this.hass}
|
||||
.resource=${"water"}
|
||||
.preferences=${this._preferences!}
|
||||
.statsMetadata=${this._statsMetadata}
|
||||
.validationResult=${this._validationResult}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-device-settings-water>
|
||||
></ha-energy-device-settings-water-gas>
|
||||
`;
|
||||
default:
|
||||
return nothing;
|
||||
@@ -343,7 +353,7 @@ class HaConfigEnergy extends LitElement {
|
||||
ha-energy-gas-settings,
|
||||
ha-energy-water-settings,
|
||||
ha-energy-device-settings,
|
||||
ha-energy-device-settings-water {
|
||||
ha-energy-device-settings-water-gas {
|
||||
display: block;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
@@ -1742,7 +1742,7 @@ ${rejected
|
||||
}
|
||||
}
|
||||
|
||||
// Alexa and Google Assistant can't be exposed to from the UI when they
|
||||
// Alexa and Google Home can't be exposed to from the UI when they
|
||||
// are configured manually in YAML, same as on the voice assistants expose page
|
||||
private _exposableAssistants = memoize(
|
||||
(cloudStatus: CloudStatus | undefined, hass: HomeAssistant) =>
|
||||
|
||||
@@ -38,3 +38,54 @@ export type Helper =
|
||||
type HelperWithoutId<T> = T extends { id: string } ? Omit<T, "id"> : never;
|
||||
|
||||
export type HelperFormItem = HelperWithoutId<Helper>;
|
||||
|
||||
export const HELPER_CATEGORIES = [
|
||||
"input",
|
||||
"time",
|
||||
"calculation",
|
||||
"other",
|
||||
] as const;
|
||||
|
||||
export type HelperCategory = (typeof HELPER_CATEGORIES)[number];
|
||||
|
||||
// Helper integrations have no category or short description in their
|
||||
// manifest, so the ones shipped with Home Assistant are listed here. Any other
|
||||
// helper falls into "other" and has no description.
|
||||
const HELPER_DOMAIN_CATEGORIES = {
|
||||
input_boolean: "input",
|
||||
input_button: "input",
|
||||
input_datetime: "input",
|
||||
input_number: "input",
|
||||
input_select: "input",
|
||||
input_text: "input",
|
||||
counter: "input",
|
||||
schedule: "time",
|
||||
timer: "time",
|
||||
tod: "time",
|
||||
history_stats: "time",
|
||||
derivative: "calculation",
|
||||
filter: "calculation",
|
||||
integration: "calculation",
|
||||
min_max: "calculation",
|
||||
mold_indicator: "calculation",
|
||||
random: "calculation",
|
||||
statistics: "calculation",
|
||||
threshold: "calculation",
|
||||
trend: "calculation",
|
||||
template: "calculation",
|
||||
utility_meter: "calculation",
|
||||
generic_hygrostat: "other",
|
||||
generic_thermostat: "other",
|
||||
group: "other",
|
||||
otp: "other",
|
||||
switch_as_x: "other",
|
||||
} as const satisfies Record<string, HelperCategory>;
|
||||
|
||||
export type KnownHelperDomain = keyof typeof HELPER_DOMAIN_CATEGORIES;
|
||||
|
||||
export const isKnownHelperDomain = (
|
||||
domain: string
|
||||
): domain is KnownHelperDomain => domain in HELPER_DOMAIN_CATEGORIES;
|
||||
|
||||
export const getHelperCategory = (domain: string): HelperCategory =>
|
||||
isKnownHelperDomain(domain) ? HELPER_DOMAIN_CATEGORIES[domain] : "other";
|
||||
@@ -1,33 +1,41 @@
|
||||
import { mdiAlertOutline } from "@mdi/js";
|
||||
import type { CSSResultGroup, TemplateResult } from "lit";
|
||||
import Fuse from "fuse.js";
|
||||
import type { HassConfig } from "home-assistant-js-websocket";
|
||||
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
|
||||
import { dynamicElement } from "../../../common/dom/dynamic-element-directive";
|
||||
import type {
|
||||
HASSDomCurrentTargetEvent,
|
||||
HASSDomEvent,
|
||||
HASSDomTargetEvent,
|
||||
} from "../../../common/dom/fire_event";
|
||||
import type { HASSDomEvent } from "../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import { stopPropagation } from "../../../common/dom/stop_propagation";
|
||||
import { stringCompare } from "../../../common/string/compare";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-area-picker";
|
||||
import "../../../components/ha-button";
|
||||
import "../../../components/ha-combo-box-item";
|
||||
import "../../../components/ha-dialog";
|
||||
import "../../../components/ha-dialog-footer";
|
||||
import "../../../components/ha-domain-icon";
|
||||
import "../../../components/ha-icon-next";
|
||||
import "../../../components/ha-picker-combo-box";
|
||||
import type {
|
||||
HaPickerComboBox,
|
||||
PickerComboBoxIndexSelectedDetail,
|
||||
PickerComboBoxItem,
|
||||
} from "../../../components/ha-picker-combo-box";
|
||||
import "../../../components/ha-spinner";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import "../../../components/ha-tooltip";
|
||||
import "../../../components/input/ha-input-search";
|
||||
import type { HaInputSearch } from "../../../components/input/ha-input-search";
|
||||
import "../../../components/item/ha-list-item-option";
|
||||
import type { HaListItemOption } from "../../../components/item/ha-list-item-option";
|
||||
import "../../../components/list/ha-list-selectable";
|
||||
import type { HaListSelectable } from "../../../components/list/ha-list-selectable";
|
||||
import { DirtyStateProviderMixin } from "../../../mixins/dirty-state-provider-mixin";
|
||||
import { getConfigFlowHandlers } from "../../../data/config_flow";
|
||||
import { createCounter } from "../../../data/counter";
|
||||
import {
|
||||
fetchEntityRegistry,
|
||||
getExtendedEntityRegistryEntry,
|
||||
updateEntitiesArea,
|
||||
type EntityRegistryEntry,
|
||||
} from "../../../data/entity/entity_registry";
|
||||
import { createInputBoolean } from "../../../data/input_boolean";
|
||||
import { createInputButton } from "../../../data/input_button";
|
||||
import { createInputDateTime } from "../../../data/input_datetime";
|
||||
@@ -43,11 +51,26 @@ import { createSchedule } from "../../../data/schedule";
|
||||
import { createTimer } from "../../../data/timer";
|
||||
import { showConfigFlowDialog } from "../../../dialogs/config-flow/show-dialog-config-flow";
|
||||
import { showAlertDialog } from "../../../dialogs/generic/show-dialog-box";
|
||||
import { haStyleDialog, haStyleScrollbar } from "../../../resources/styles";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
import { brandsUrl } from "../../../util/brands-url";
|
||||
import type { Helper, HelperDomain, HelperFormItem } from "./const";
|
||||
import { isHelperDomain } from "./const";
|
||||
import { showMoreInfoDialog } from "../../../dialogs/more-info/show-ha-more-info-dialog";
|
||||
import { DirtyStateProviderMixin } from "../../../mixins/dirty-state-provider-mixin";
|
||||
import {
|
||||
multiTermSortedSearch,
|
||||
type FuseWeightedKey,
|
||||
} from "../../../resources/fuseMultiTerm";
|
||||
import { haStyleDialog } from "../../../resources/styles";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../../../types";
|
||||
import type {
|
||||
Helper,
|
||||
HelperCategory,
|
||||
HelperDomain,
|
||||
HelperFormItem,
|
||||
} from "./const";
|
||||
import {
|
||||
getHelperCategory,
|
||||
HELPER_CATEGORIES,
|
||||
isHelperDomain,
|
||||
isKnownHelperDomain,
|
||||
} from "./const";
|
||||
import type { ShowDialogHelperDetailParams } from "./show-dialog-helper-detail";
|
||||
|
||||
type HelperCreators = Record<
|
||||
@@ -108,16 +131,32 @@ const HELPERS: HelperCreators = {
|
||||
},
|
||||
};
|
||||
|
||||
interface HelperPickerItem extends PickerComboBoxItem {
|
||||
category: HelperCategory;
|
||||
loaded: boolean;
|
||||
}
|
||||
|
||||
const HELPER_SEARCH_KEYS: FuseWeightedKey[] = [
|
||||
{ name: "primary", weight: 10 },
|
||||
{ name: "search_labels.aliases", weight: 8 },
|
||||
{ name: "id", weight: 4 },
|
||||
{ name: "secondary", weight: 2 },
|
||||
];
|
||||
|
||||
@customElement("dialog-helper-detail")
|
||||
export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
HelperFormItem | undefined
|
||||
{ item?: HelperFormItem; area?: string } | undefined
|
||||
>()(LitElement) {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@state() private _item?: HelperFormItem;
|
||||
|
||||
@state() private _area?: string;
|
||||
|
||||
@state() private _open = false;
|
||||
|
||||
@state() private _shown = false;
|
||||
|
||||
@state() private _domain?: string;
|
||||
|
||||
@state() private _error?: string;
|
||||
@@ -128,15 +167,17 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
|
||||
@state() private _loading = false;
|
||||
|
||||
@state() private _filter?: string;
|
||||
private _category?: HelperCategory;
|
||||
|
||||
@query("ha-input-search")
|
||||
private _searchInput?: HTMLElement & { updateComplete?: Promise<unknown> };
|
||||
private _search?: string;
|
||||
|
||||
@query("ha-picker-combo-box") private _comboBox?: HaPickerComboBox;
|
||||
|
||||
private _pendingConfigFlow?: {
|
||||
startFlowHandler: string;
|
||||
manifest: IntegrationManifest;
|
||||
dialogClosedCallback?: ShowDialogHelperDetailParams["dialogClosedCallback"];
|
||||
navigateToResult?: boolean;
|
||||
};
|
||||
|
||||
private _params?: ShowDialogHelperDetailParams;
|
||||
@@ -145,11 +186,17 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
this._params = params;
|
||||
this._domain = params.domain;
|
||||
this._item = params.item;
|
||||
this._area = undefined;
|
||||
this._category = undefined;
|
||||
this._search = undefined;
|
||||
if (this._domain && this._domain in HELPERS) {
|
||||
this._loading = true;
|
||||
try {
|
||||
await HELPERS[this._domain].import();
|
||||
this._initDirtyTracking({ type: "deep" }, undefined);
|
||||
this._initDirtyTracking(
|
||||
{ type: "deep" },
|
||||
{ item: this._item, area: undefined }
|
||||
);
|
||||
} finally {
|
||||
this._loading = false;
|
||||
}
|
||||
@@ -163,19 +210,41 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
this._helperFlows = flows;
|
||||
|
||||
await this.updateComplete;
|
||||
await this._focusSearchInput();
|
||||
this._comboBox?.refreshItems();
|
||||
this._focusPicker();
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues<this>): void {
|
||||
super.updated(changedProps);
|
||||
const oldHass = changedProps.get("hass");
|
||||
if (
|
||||
oldHass &&
|
||||
(oldHass.localize !== this.hass.localize ||
|
||||
oldHass.config !== this.hass.config)
|
||||
) {
|
||||
this._comboBox?.refreshItems();
|
||||
}
|
||||
}
|
||||
|
||||
public closeDialog(): void {
|
||||
this._open = false;
|
||||
}
|
||||
|
||||
private _dialogShown(ev: Event): void {
|
||||
if (ev.eventPhase !== Event.AT_TARGET) {
|
||||
return;
|
||||
}
|
||||
this._shown = true;
|
||||
}
|
||||
|
||||
private _dialogClosed(): void {
|
||||
this._open = false;
|
||||
this._shown = false;
|
||||
this._error = undefined;
|
||||
this._domain = undefined;
|
||||
this._params = undefined;
|
||||
this._filter = undefined;
|
||||
this._category = undefined;
|
||||
this._search = undefined;
|
||||
fireEvent(this, "dialog-closed", { dialog: this.localName });
|
||||
|
||||
if (this._pendingConfigFlow) {
|
||||
@@ -185,6 +254,7 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
startFlowHandler: pendingConfigFlow.startFlowHandler,
|
||||
manifest: pendingConfigFlow.manifest,
|
||||
dialogClosedCallback: pendingConfigFlow.dialogClosedCallback,
|
||||
navigateToResult: pendingConfigFlow.navigateToResult,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -195,6 +265,7 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
}
|
||||
let content: TemplateResult;
|
||||
let footer: TemplateResult | typeof nothing = nothing;
|
||||
let showPicker = false;
|
||||
|
||||
if (this._domain && !this._loading) {
|
||||
content = html`
|
||||
@@ -206,6 +277,11 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
new: true,
|
||||
autofocus: true,
|
||||
})}
|
||||
<ha-area-picker
|
||||
.value=${this._area}
|
||||
.disabled=${this._submitting}
|
||||
@value-changed=${this._areaChanged}
|
||||
></ha-area-picker>
|
||||
</div>
|
||||
`;
|
||||
footer = html`
|
||||
@@ -234,78 +310,34 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
} else if (this._loading || this._helperFlows === undefined) {
|
||||
content = html`<ha-spinner></ha-spinner>`;
|
||||
} else {
|
||||
const items = this._filterHelpers(
|
||||
HELPERS,
|
||||
this._helperFlows,
|
||||
this._filter
|
||||
);
|
||||
|
||||
showPicker = true;
|
||||
content = html`
|
||||
<ha-input-search
|
||||
appearance="outlined"
|
||||
<ha-picker-combo-box
|
||||
autofocus
|
||||
.value=${this._filter}
|
||||
@input=${this._filterChanged}
|
||||
.placeholder=${this.hass.localize(
|
||||
mode="dialog"
|
||||
.shown=${this._shown}
|
||||
no-sort
|
||||
.label=${this.hass.localize(
|
||||
"ui.panel.config.integrations.search_helper"
|
||||
)}
|
||||
></ha-input-search>
|
||||
<ha-list-selectable
|
||||
controlled
|
||||
aria-label=${this.hass.localize(
|
||||
"ui.panel.config.helpers.dialog.create_helper"
|
||||
.getItems=${this._getItems}
|
||||
.rowRenderer=${this._renderHelperRow}
|
||||
.sections=${this._getSections(
|
||||
this._helperFlows,
|
||||
this.hass.localize,
|
||||
this.hass.config,
|
||||
this.hass.locale.language
|
||||
)}
|
||||
@ha-list-item-selected=${this._domainPicked}
|
||||
>
|
||||
${items.map(([domain, label]) => {
|
||||
// Only OG helpers need to be loaded prior adding one
|
||||
const isLoaded =
|
||||
!(domain in HELPERS) ||
|
||||
isComponentLoaded(this.hass.config, domain);
|
||||
|
||||
return html`
|
||||
<ha-list-item-option appearance="line" .value=${domain}>
|
||||
<img
|
||||
slot="start"
|
||||
loading="lazy"
|
||||
alt=""
|
||||
src=${brandsUrl(
|
||||
{
|
||||
domain,
|
||||
type: "icon",
|
||||
darkOptimized: this.hass.themes?.darkMode,
|
||||
},
|
||||
this.hass.auth.data.hassUrl
|
||||
)}
|
||||
crossorigin="anonymous"
|
||||
referrerpolicy="no-referrer"
|
||||
/>
|
||||
<span slot="headline">${label}</span>
|
||||
${
|
||||
isLoaded
|
||||
? html`<ha-icon-next slot="end"></ha-icon-next>`
|
||||
: html`<ha-svg-icon
|
||||
slot="end"
|
||||
.id="icon-${domain}"
|
||||
path=${mdiAlertOutline}
|
||||
@click=${stopPropagation}
|
||||
></ha-svg-icon>
|
||||
<ha-tooltip slot="end" .for="icon-${domain}">
|
||||
${this.hass.localize(
|
||||
"ui.dialogs.helper_settings.platform_not_loaded",
|
||||
{ platform: domain }
|
||||
)}
|
||||
</ha-tooltip>`
|
||||
}
|
||||
</ha-list-item-option>
|
||||
`;
|
||||
})}
|
||||
</ha-list-selectable>
|
||||
.selectedSection=${this._category}
|
||||
@index-selected=${this._helperPicked}
|
||||
></ha-picker-combo-box>
|
||||
`;
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-dialog
|
||||
class=${showPicker ? "picker" : ""}
|
||||
.flexContent=${showPicker}
|
||||
.open=${this._open}
|
||||
.preventScrimClose=${this.isDirtyState}
|
||||
header-title=${
|
||||
@@ -325,6 +357,7 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
)
|
||||
: this.hass.localize("ui.panel.config.helpers.dialog.create_helper")
|
||||
}
|
||||
@after-show=${this._dialogShown}
|
||||
@closed=${this._dialogClosed}
|
||||
>
|
||||
${content} ${footer}
|
||||
@@ -332,76 +365,190 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
`;
|
||||
}
|
||||
|
||||
private _filterHelpers = memoizeOne(
|
||||
private _getHelperItems = memoizeOne(
|
||||
(
|
||||
predefinedHelpers: HelperCreators,
|
||||
flowHelpers?: string[],
|
||||
filter?: string
|
||||
) => {
|
||||
const items: [string, string][] = [];
|
||||
|
||||
for (const helper of Object.keys(
|
||||
predefinedHelpers
|
||||
) as (keyof typeof predefinedHelpers)[]) {
|
||||
items.push([
|
||||
helper,
|
||||
this.hass.localize(`ui.panel.config.helpers.types.${helper}`) ||
|
||||
helper,
|
||||
]);
|
||||
}
|
||||
|
||||
if (flowHelpers) {
|
||||
for (const domain of flowHelpers) {
|
||||
items.push([domain, domainToName(this.hass.localize, domain)]);
|
||||
}
|
||||
}
|
||||
|
||||
return items
|
||||
.filter(([domain, label]) => {
|
||||
if (filter) {
|
||||
const lowerFilter = filter.toLowerCase();
|
||||
return (
|
||||
label.toLowerCase().includes(lowerFilter) ||
|
||||
domain.toLowerCase().includes(lowerFilter) ||
|
||||
(predefinedHelpers[domain as HelperDomain]?.alias || []).some(
|
||||
(alias) => alias.toLowerCase().includes(lowerFilter)
|
||||
)
|
||||
);
|
||||
}
|
||||
return true;
|
||||
flowHelpers: string[],
|
||||
localize: LocalizeFunc,
|
||||
config: HassConfig,
|
||||
language: string
|
||||
): HelperPickerItem[] => {
|
||||
const domains = [
|
||||
...(Object.keys(HELPERS) as HelperDomain[]),
|
||||
...flowHelpers,
|
||||
];
|
||||
return domains
|
||||
.map((domain) => {
|
||||
const helperDomain = isHelperDomain(domain) ? domain : undefined;
|
||||
return {
|
||||
id: domain,
|
||||
primary:
|
||||
(helperDomain &&
|
||||
localize(`ui.panel.config.helpers.types.${helperDomain}`)) ||
|
||||
domainToName(localize, domain),
|
||||
secondary: isKnownHelperDomain(domain)
|
||||
? localize(
|
||||
`ui.panel.config.helpers.dialog.descriptions.${domain}`
|
||||
)
|
||||
: undefined,
|
||||
category: getHelperCategory(domain),
|
||||
// Only OG helpers need to be loaded prior adding one
|
||||
loaded: !helperDomain || isComponentLoaded(config, domain),
|
||||
search_labels: {
|
||||
aliases: helperDomain
|
||||
? (HELPERS[helperDomain].alias?.join(" ") ?? null)
|
||||
: null,
|
||||
},
|
||||
};
|
||||
})
|
||||
.sort((a, b) => stringCompare(a[1], b[1], this.hass.locale.language));
|
||||
.sort((a, b) => stringCompare(a.primary, b.primary, language));
|
||||
}
|
||||
);
|
||||
|
||||
private async _filterChanged(e: HASSDomTargetEvent<HaInputSearch>) {
|
||||
this._filter = e.target.value;
|
||||
}
|
||||
// Only offer the categories that have helpers.
|
||||
private _getSections = memoizeOne(
|
||||
(
|
||||
flowHelpers: string[],
|
||||
localize: LocalizeFunc,
|
||||
config: HassConfig,
|
||||
language: string
|
||||
) => {
|
||||
const items = this._getHelperItems(
|
||||
flowHelpers,
|
||||
localize,
|
||||
config,
|
||||
language
|
||||
);
|
||||
return HELPER_CATEGORIES.filter((category) =>
|
||||
items.some((item) => item.category === category)
|
||||
).map((category) => ({
|
||||
id: category,
|
||||
label: localize(
|
||||
`ui.panel.config.helpers.dialog.categories.${category}`
|
||||
),
|
||||
}));
|
||||
}
|
||||
);
|
||||
|
||||
private _fuseIndex = memoizeOne((items: HelperPickerItem[]) =>
|
||||
Fuse.createIndex(HELPER_SEARCH_KEYS, items)
|
||||
);
|
||||
|
||||
private _getItems = (
|
||||
search?: string,
|
||||
section?: string
|
||||
): (HelperPickerItem | string)[] => {
|
||||
this._category = section as HelperCategory | undefined;
|
||||
this._search = search;
|
||||
const allItems = this._getHelperItems(
|
||||
this._helperFlows ?? [],
|
||||
this.hass.localize,
|
||||
this.hass.config,
|
||||
this.hass.locale.language
|
||||
);
|
||||
const items = search
|
||||
? multiTermSortedSearch(
|
||||
allItems,
|
||||
search,
|
||||
(item) => item.id,
|
||||
this._fuseIndex(allItems)
|
||||
)
|
||||
: allItems;
|
||||
|
||||
if (this._category) {
|
||||
return items.filter((item) => item.category === this._category);
|
||||
}
|
||||
|
||||
// Group by category, keeping the search order within each one.
|
||||
return HELPER_CATEGORIES.flatMap((category) => {
|
||||
const categoryItems = items.filter((item) => item.category === category);
|
||||
return categoryItems.length
|
||||
? [
|
||||
this.hass.localize(
|
||||
`ui.panel.config.helpers.dialog.categories.${category}`
|
||||
),
|
||||
...categoryItems,
|
||||
]
|
||||
: [];
|
||||
});
|
||||
};
|
||||
|
||||
private _renderHelperRow = (item: PickerComboBoxItem) => {
|
||||
const { id: domain, primary, secondary, loaded } = item as HelperPickerItem;
|
||||
return html`
|
||||
<ha-combo-box-item>
|
||||
<ha-domain-icon
|
||||
slot="start"
|
||||
style="margin: var(--ha-space-1);"
|
||||
.domain=${domain}
|
||||
brand-fallback
|
||||
></ha-domain-icon>
|
||||
<span slot="headline">${primary}</span>
|
||||
${
|
||||
secondary
|
||||
? html`<span slot="supporting-text">${secondary}</span>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
loaded
|
||||
? html`<ha-icon-next slot="end"></ha-icon-next>`
|
||||
: html`<ha-svg-icon
|
||||
slot="end"
|
||||
.id="icon-${domain}"
|
||||
.path=${mdiAlertOutline}
|
||||
@click=${stopPropagation}
|
||||
></ha-svg-icon>
|
||||
<ha-tooltip slot="end" .for="icon-${domain}">
|
||||
${this.hass.localize(
|
||||
"ui.dialogs.helper_settings.platform_not_loaded",
|
||||
{ platform: domain }
|
||||
)}
|
||||
</ha-tooltip>`
|
||||
}
|
||||
</ha-combo-box-item>
|
||||
`;
|
||||
};
|
||||
|
||||
private _valueChanged(ev: CustomEvent): void {
|
||||
this._item = ev.detail.value;
|
||||
this._updateDirtyState(this._item);
|
||||
this._updateDirtyState({ item: this._item, area: this._area });
|
||||
}
|
||||
|
||||
private async _createItem(): Promise<void> {
|
||||
if (!this._domain || !this._item) {
|
||||
return;
|
||||
}
|
||||
const domain = this._domain;
|
||||
const params = this._params;
|
||||
const area = this._area;
|
||||
this._submitting = true;
|
||||
this._error = "";
|
||||
try {
|
||||
const createdEntity = await HELPERS[this._domain].create(
|
||||
this.hass,
|
||||
this._item
|
||||
);
|
||||
if (this._params?.dialogClosedCallback && createdEntity.id) {
|
||||
this._params.dialogClosedCallback({
|
||||
const createdEntity = await HELPERS[domain].create(this.hass, this._item);
|
||||
// The dialog was closed or reopened while waiting
|
||||
if (this._params !== params) {
|
||||
return;
|
||||
}
|
||||
let entityId: string | undefined;
|
||||
if (createdEntity.id && (area || params?.navigateToResult)) {
|
||||
entityId = await this._findEntityId(domain, createdEntity.id);
|
||||
if (area) {
|
||||
entityId = await this._saveArea(entityId, area);
|
||||
}
|
||||
if (this._params !== params) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (params?.dialogClosedCallback && createdEntity.id) {
|
||||
params.dialogClosedCallback({
|
||||
flowFinished: true,
|
||||
entityId: `${this._domain}.${createdEntity.id}`,
|
||||
entityId: entityId ?? `${domain}.${createdEntity.id}`,
|
||||
});
|
||||
}
|
||||
this._markDirtyStateClean();
|
||||
this.closeDialog();
|
||||
if (params?.navigateToResult && entityId) {
|
||||
showMoreInfoDialog(this, { entityId });
|
||||
}
|
||||
} catch (err: any) {
|
||||
this._error = err.message || "Unknown error";
|
||||
} finally {
|
||||
@@ -409,18 +556,63 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
}
|
||||
}
|
||||
|
||||
private async _domainPicked(
|
||||
ev: HASSDomEvent<number> & HASSDomCurrentTargetEvent<HaListSelectable>
|
||||
): Promise<void> {
|
||||
const domain = (
|
||||
ev.currentTarget.items[ev.detail] as HaListItemOption | undefined
|
||||
)?.value;
|
||||
if (!domain) {
|
||||
return;
|
||||
private async _findEntityId(
|
||||
domain: string,
|
||||
uniqueId: string
|
||||
): Promise<string | undefined> {
|
||||
const isCreated = (entry: EntityRegistryEntry) =>
|
||||
entry.platform === domain && entry.unique_id === uniqueId;
|
||||
try {
|
||||
// The entity ID usually matches the helper ID, unless it was taken
|
||||
const entry = await getExtendedEntityRegistryEntry(
|
||||
this.hass,
|
||||
`${domain}.${uniqueId}`
|
||||
).catch(() => undefined);
|
||||
if (entry && isCreated(entry)) {
|
||||
return entry.entity_id;
|
||||
}
|
||||
return (await fetchEntityRegistry(this.hass.connection)).find(isCreated)
|
||||
?.entity_id;
|
||||
} catch (_err) {
|
||||
return undefined;
|
||||
}
|
||||
const isLoaded =
|
||||
!(domain in HELPERS) || isComponentLoaded(this.hass.config, domain);
|
||||
if (!isLoaded) {
|
||||
}
|
||||
|
||||
private async _saveArea(
|
||||
entityId: string | undefined,
|
||||
areaId: string
|
||||
): Promise<string | undefined> {
|
||||
let error = "Entity not found";
|
||||
if (entityId) {
|
||||
try {
|
||||
return (await updateEntitiesArea(this.hass, [entityId], areaId))[
|
||||
entityId
|
||||
];
|
||||
} catch (err: unknown) {
|
||||
error = (err as { message?: string })?.message ?? "Unknown error";
|
||||
}
|
||||
}
|
||||
showAlertDialog(this, {
|
||||
text: this.hass.localize(
|
||||
"ui.panel.config.integrations.config_flow.error_saving_entity",
|
||||
{ error }
|
||||
),
|
||||
});
|
||||
return entityId;
|
||||
}
|
||||
|
||||
private _areaChanged(ev: ValueChangedEvent<string | undefined>): void {
|
||||
ev.stopPropagation();
|
||||
this._area = ev.detail.value || undefined;
|
||||
this._updateDirtyState({ item: this._item, area: this._area });
|
||||
}
|
||||
|
||||
private async _helperPicked(
|
||||
ev: HASSDomEvent<PickerComboBoxIndexSelectedDetail>
|
||||
): Promise<void> {
|
||||
ev.stopPropagation();
|
||||
const { id: domain, loaded } = ev.detail.item as HelperPickerItem;
|
||||
if (!loaded) {
|
||||
showAlertDialog(this, {
|
||||
text: this.hass.localize(
|
||||
"ui.dialogs.helper_settings.platform_not_loaded",
|
||||
@@ -435,7 +627,10 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
try {
|
||||
await HELPERS[domain].import();
|
||||
this._domain = domain;
|
||||
this._initDirtyTracking({ type: "deep" }, undefined);
|
||||
this._initDirtyTracking(
|
||||
{ type: "deep" },
|
||||
{ item: this._item, area: undefined }
|
||||
);
|
||||
} finally {
|
||||
this._loading = false;
|
||||
}
|
||||
@@ -444,68 +639,49 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
|
||||
startFlowHandler: domain,
|
||||
manifest: await fetchIntegrationManifest(this.hass, domain),
|
||||
dialogClosedCallback: this._params?.dialogClosedCallback,
|
||||
navigateToResult: this._params?.navigateToResult,
|
||||
};
|
||||
this.closeDialog();
|
||||
}
|
||||
}
|
||||
|
||||
private async _goBack() {
|
||||
const search = this._search;
|
||||
this._domain = undefined;
|
||||
this._item = undefined;
|
||||
this._area = undefined;
|
||||
this._error = undefined;
|
||||
await this.updateComplete;
|
||||
await this._focusSearchInput();
|
||||
await this._comboBox?.updateComplete;
|
||||
if (search) {
|
||||
this._comboBox?.setFieldValue(search);
|
||||
}
|
||||
this._focusPicker();
|
||||
}
|
||||
|
||||
private async _focusSearchInput() {
|
||||
const searchInput = this._searchInput;
|
||||
|
||||
if (!searchInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
await searchInput.updateComplete;
|
||||
searchInput.focus();
|
||||
private async _focusPicker() {
|
||||
await this._comboBox?.updateComplete;
|
||||
this._comboBox?.focus();
|
||||
}
|
||||
|
||||
static get styles(): CSSResultGroup {
|
||||
return [
|
||||
haStyleScrollbar,
|
||||
haStyleDialog,
|
||||
css`
|
||||
ha-dialog {
|
||||
--dialog-content-padding: 0;
|
||||
}
|
||||
ha-icon-next {
|
||||
width: var(--ha-space-6);
|
||||
}
|
||||
ha-list-item-option img {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
object-fit: contain;
|
||||
}
|
||||
ha-tooltip {
|
||||
pointer-events: auto;
|
||||
@media all and (min-width: 451px) and (min-height: 501px) {
|
||||
ha-dialog.picker {
|
||||
--ha-dialog-min-height: min(620px, 90vh);
|
||||
}
|
||||
}
|
||||
.form {
|
||||
padding: var(--ha-space-6);
|
||||
}
|
||||
ha-input-search {
|
||||
margin: 0 var(--ha-space-4) var(--ha-space-3);
|
||||
}
|
||||
ha-list-selectable::part(base) {
|
||||
height: calc(60vh - 184px);
|
||||
}
|
||||
@media all and (max-width: 450px), all and (max-height: 500px) {
|
||||
ha-list-selectable::part(base) {
|
||||
height: calc(
|
||||
100vh -
|
||||
184px - var(--safe-area-inset-top, 0px) - var(
|
||||
--safe-area-inset-bottom,
|
||||
0px
|
||||
)
|
||||
);
|
||||
}
|
||||
.form ha-area-picker {
|
||||
display: block;
|
||||
margin-top: var(--ha-space-4);
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -123,7 +123,7 @@ import { haStyle } from "../../../resources/styles";
|
||||
import type { HomeAssistant, Route } from "../../../types";
|
||||
import { fileDownload } from "../../../util/file_download";
|
||||
import { showAssignCategoryDialog } from "../category/show-dialog-assign-category";
|
||||
import { renderCategoryGroupActions } from "../category/render-category-group-actions";
|
||||
import { categoryGroupActions } from "../category/category-group-actions";
|
||||
import { showCategoryRegistryDetailDialog } from "../category/show-dialog-category-registry-detail";
|
||||
import {
|
||||
getAreaTableColumn,
|
||||
@@ -718,6 +718,12 @@ export class HaConfigHelpers extends SubscribeMixin(LitElement) {
|
||||
.columns=${this._columns(this.hass.localize, helpers)}
|
||||
.data=${helpers}
|
||||
.initialGroupColumn=${this._tableSettings.grouping}
|
||||
.renderGroupActions=${this._groupActions(
|
||||
"helpers",
|
||||
this._categories,
|
||||
this._tableSettings.grouping,
|
||||
this._categoryDeleted
|
||||
)}
|
||||
.initialCollapsedGroups=${this._activeCollapsed}
|
||||
.initialSorting=${this._tableSettings.sorting}
|
||||
.columnOrder=${this._activeColumnOrder}
|
||||
@@ -880,12 +886,6 @@ export class HaConfigHelpers extends SubscribeMixin(LitElement) {
|
||||
.hass=${this.hass}
|
||||
slot="toolbar-icon"
|
||||
></ha-integration-overflow-menu>
|
||||
${renderCategoryGroupActions(
|
||||
"helpers",
|
||||
this._categories,
|
||||
this._tableSettings.grouping,
|
||||
this._categoryDeleted
|
||||
)}
|
||||
<ha-button slot="fab" size="l" @click=${this._createHelper}>
|
||||
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
|
||||
${this.hass.localize("ui.panel.config.helpers.picker.create_helper")}
|
||||
@@ -931,6 +931,8 @@ export class HaConfigHelpers extends SubscribeMixin(LitElement) {
|
||||
this._applyFilters();
|
||||
}
|
||||
|
||||
private _groupActions = memoizeOne(categoryGroupActions);
|
||||
|
||||
private _categoryDeleted = (categoryId: string) => {
|
||||
const value = this._filters["ha-filter-categories"];
|
||||
|
||||
@@ -1300,6 +1302,7 @@ ${rejected
|
||||
if (isHelperDomain(domain)) {
|
||||
showHelperDetailDialog(this, {
|
||||
domain,
|
||||
navigateToResult: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -1343,6 +1346,7 @@ ${rejected
|
||||
showConfigFlowDialog(this, {
|
||||
startFlowHandler: domain,
|
||||
manifest: await fetchIntegrationManifest(this.hass, domain),
|
||||
navigateToResult: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1568,11 +1572,12 @@ ${rejected
|
||||
{ name: config.name }
|
||||
),
|
||||
},
|
||||
navigateToResult: true,
|
||||
});
|
||||
}
|
||||
|
||||
private _createHelper() {
|
||||
showHelperDetailDialog(this, {});
|
||||
showHelperDetailDialog(this, { navigateToResult: true });
|
||||
}
|
||||
|
||||
private _bulkCreateCategory = () => {
|
||||
|
||||
@@ -11,6 +11,7 @@ export interface ShowDialogHelperDetailParams {
|
||||
entryId?: string;
|
||||
entityId?: string;
|
||||
}) => void;
|
||||
navigateToResult?: boolean;
|
||||
}
|
||||
|
||||
export const showHelperDetailDialog = (
|
||||
|
||||
@@ -124,6 +124,7 @@ class AddIntegrationDialog extends LitElement {
|
||||
private _loadId = 0;
|
||||
|
||||
public async showDialog(params?: AddIntegrationDialogParams): Promise<void> {
|
||||
this._navigateToResult = params?.navigateToResult ?? false;
|
||||
const loadPromise = this._load(params?.integrationFilter);
|
||||
|
||||
if (params?.domain) {
|
||||
@@ -159,7 +160,6 @@ class AddIntegrationDialog extends LitElement {
|
||||
this._openedDirectly = !!(params?.brand || params?.domain);
|
||||
this._initialFilter = params?.initialFilter;
|
||||
this._integrationFilter = params?.integrationFilter;
|
||||
this._navigateToResult = params?.navigateToResult ?? false;
|
||||
this._narrow = matchMedia(
|
||||
"all and (max-width: 450px), all and (max-height: 500px)"
|
||||
).matches;
|
||||
|
||||
@@ -109,7 +109,7 @@ import { documentationUrl } from "../../../util/documentation-url";
|
||||
import { showToast } from "../../../util/toast";
|
||||
import { showAreaRegistryDetailDialog } from "../areas/show-dialog-area-registry-detail";
|
||||
import { showAssignCategoryDialog } from "../category/show-dialog-assign-category";
|
||||
import { renderCategoryGroupActions } from "../category/render-category-group-actions";
|
||||
import { categoryGroupActions } from "../category/category-group-actions";
|
||||
import { showCategoryRegistryDetailDialog } from "../category/show-dialog-category-registry-detail";
|
||||
import {
|
||||
getAreaTableColumn,
|
||||
@@ -535,6 +535,12 @@ class HaSceneDashboard extends SubscribeMixin(LitElement) {
|
||||
.columns=${this._columns(this.hass.localize, scenes)}
|
||||
id="entity_id"
|
||||
.initialGroupColumn=${this._tableSettings.grouping}
|
||||
.renderGroupActions=${this._groupActions(
|
||||
"scene",
|
||||
this._categories,
|
||||
this._tableSettings.grouping,
|
||||
this._categoryDeleted
|
||||
)}
|
||||
.initialCollapsedGroups=${this._activeCollapsed}
|
||||
.initialSorting=${this._tableSettings.sorting}
|
||||
.columnOrder=${this._activeColumnOrder}
|
||||
@@ -563,12 +569,6 @@ class HaSceneDashboard extends SubscribeMixin(LitElement) {
|
||||
.label=${this.hass.localize("ui.common.help")}
|
||||
.path=${mdiHelpCircleOutline}
|
||||
></ha-icon-button>
|
||||
${renderCategoryGroupActions(
|
||||
"scene",
|
||||
this._categories,
|
||||
this._tableSettings.grouping,
|
||||
this._categoryDeleted
|
||||
)}
|
||||
|
||||
<ha-filter-floor-areas
|
||||
.type=${"scene"}
|
||||
@@ -795,6 +795,8 @@ class HaSceneDashboard extends SubscribeMixin(LitElement) {
|
||||
});
|
||||
};
|
||||
|
||||
private _groupActions = memoizeOne(categoryGroupActions);
|
||||
|
||||
private _categoryDeleted = (categoryId: string) => {
|
||||
const value = this._filters["ha-filter-categories"]?.value;
|
||||
|
||||
|
||||
@@ -113,7 +113,7 @@ import { showToast } from "../../../util/toast";
|
||||
import { showAreaRegistryDetailDialog } from "../areas/show-dialog-area-registry-detail";
|
||||
import { showNewAutomationDialog } from "../automation/show-dialog-new-automation";
|
||||
import { showAssignCategoryDialog } from "../category/show-dialog-assign-category";
|
||||
import { renderCategoryGroupActions } from "../category/render-category-group-actions";
|
||||
import { categoryGroupActions } from "../category/category-group-actions";
|
||||
import { showCategoryRegistryDetailDialog } from "../category/show-dialog-category-registry-detail";
|
||||
import {
|
||||
getAreaTableColumn,
|
||||
@@ -453,6 +453,12 @@ class HaScriptPicker extends SubscribeMixin(LitElement) {
|
||||
)}
|
||||
has-filters
|
||||
.initialGroupColumn=${this._tableSettings.grouping}
|
||||
.renderGroupActions=${this._groupActions(
|
||||
"script",
|
||||
this._categories,
|
||||
this._tableSettings.grouping,
|
||||
this._categoryDeleted
|
||||
)}
|
||||
.initialCollapsedGroups=${this._activeCollapsed}
|
||||
.initialSorting=${this._tableSettings.sorting}
|
||||
.columnOrder=${this._activeColumnOrder}
|
||||
@@ -497,12 +503,6 @@ class HaScriptPicker extends SubscribeMixin(LitElement) {
|
||||
.path=${mdiHelpCircleOutline}
|
||||
@click=${this._showHelp}
|
||||
></ha-icon-button>
|
||||
${renderCategoryGroupActions(
|
||||
"script",
|
||||
this._categories,
|
||||
this._tableSettings.grouping,
|
||||
this._categoryDeleted
|
||||
)}
|
||||
<ha-filter-floor-areas
|
||||
.type=${"script"}
|
||||
.value=${this._filters["ha-filter-floor-areas"]?.value}
|
||||
@@ -739,6 +739,8 @@ class HaScriptPicker extends SubscribeMixin(LitElement) {
|
||||
});
|
||||
};
|
||||
|
||||
private _groupActions = memoizeOne(categoryGroupActions);
|
||||
|
||||
private _categoryDeleted = (categoryId: string) => {
|
||||
const value = this._filters["ha-filter-categories"]?.value;
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ export class EnergySetupWizard extends LitElement implements LovelaceCard {
|
||||
energy_sources: [],
|
||||
device_consumption: [],
|
||||
device_consumption_water: [],
|
||||
device_consumption_gas: [],
|
||||
};
|
||||
|
||||
public getCardSize() {
|
||||
|
||||
@@ -58,6 +58,9 @@ export const hasWaterSource = (prefs: EnergyPreferences): boolean =>
|
||||
export const hasWaterDevices = (prefs: EnergyPreferences): boolean =>
|
||||
(prefs.device_consumption_water?.length ?? 0) > 0;
|
||||
|
||||
export const hasGasDevices = (prefs: EnergyPreferences): boolean =>
|
||||
(prefs.device_consumption_gas?.length ?? 0) > 0;
|
||||
|
||||
export const hasDeviceConsumption = (prefs: EnergyPreferences): boolean =>
|
||||
prefs.device_consumption.length > 0;
|
||||
|
||||
@@ -78,6 +81,9 @@ export const hasPowerDevices = (prefs: EnergyPreferences): boolean =>
|
||||
export const hasWaterRateDevices = (prefs: EnergyPreferences): boolean =>
|
||||
(prefs.device_consumption_water ?? []).some((device) => device.stat_rate);
|
||||
|
||||
export const hasGasRateDevices = (prefs: EnergyPreferences): boolean =>
|
||||
prefs.device_consumption_gas.some((device) => device.stat_rate);
|
||||
|
||||
/** A water source exposing a live flow-rate statistic. */
|
||||
export const hasWaterRateSource = (prefs: EnergyPreferences): boolean =>
|
||||
prefs.energy_sources.some(
|
||||
@@ -96,7 +102,8 @@ export const hasNowViewContent = (prefs: EnergyPreferences): boolean =>
|
||||
hasPowerDevices(prefs) ||
|
||||
hasWaterRateSource(prefs) ||
|
||||
hasWaterRateDevices(prefs) ||
|
||||
hasGasRateSource(prefs);
|
||||
hasGasRateSource(prefs) ||
|
||||
hasGasRateDevices(prefs);
|
||||
|
||||
// --- Card catalog ----------------------------------------------------------
|
||||
|
||||
@@ -155,7 +162,7 @@ export const ENERGY_CARD_CATALOG: readonly EnergyCardCatalogEntry[] = [
|
||||
"overview",
|
||||
"energy-gas-graph",
|
||||
"ui.panel.energy.cards.energy_gas_graph_title",
|
||||
(p) => hasGasSource(p)
|
||||
(p) => hasGasSource(p) || hasGasDevices(p)
|
||||
),
|
||||
// One toggle gates the water row, which renders energy-water-graph (sources)
|
||||
// or, with only water devices, water-sankey.
|
||||
@@ -253,6 +260,9 @@ export const ENERGY_CARD_CATALOG: readonly EnergyCardCatalogEntry[] = [
|
||||
"ui.panel.energy.cards.energy_sources_table_title",
|
||||
(p) => hasGasSource(p)
|
||||
),
|
||||
entry("gas", "gas-sankey", "ui.panel.energy.cards.gas_sankey_title", (p) =>
|
||||
hasGasDevices(p)
|
||||
),
|
||||
|
||||
// --- Water ---
|
||||
entry(
|
||||
@@ -293,6 +303,12 @@ export const ENERGY_CARD_CATALOG: readonly EnergyCardCatalogEntry[] = [
|
||||
"ui.panel.energy.cards.water_flow_sankey_title",
|
||||
(p) => hasWaterRateDevices(p)
|
||||
),
|
||||
entry(
|
||||
"now",
|
||||
"gas-flow-sankey",
|
||||
"ui.panel.energy.cards.gas_flow_sankey_title",
|
||||
(p) => hasGasRateDevices(p)
|
||||
),
|
||||
];
|
||||
|
||||
// --- Lookup helpers --------------------------------------------------------
|
||||
|
||||
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user