mirror of
https://github.com/home-assistant/frontend.git
synced 2026-12-02 17:50:19 +00:00
Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e96bca7bc2 | ||
|
|
f666f4c5f0 | ||
|
|
fddf0437a7 | ||
|
|
d5880a2b1e | ||
|
|
f02cd4e686 | ||
|
|
08dafbc5dc | ||
|
|
a3c534c2dd | ||
|
|
cff3cb1eda | ||
|
|
2dd2a1f688 | ||
|
|
f6e282d3e7 | ||
|
|
3b6c3216c4 | ||
|
|
558fb6f139 | ||
|
|
20eea322ba | ||
|
|
512721959d | ||
|
|
8156895d6e | ||
|
|
0075426172 | ||
|
|
cde676487c | ||
|
|
7065084cfd | ||
|
|
ade37bc113 | ||
|
|
8d9b6134db | ||
|
|
15b78a94e1 | ||
|
|
70bdc89ba7 | ||
|
|
d1569f5801 |
No files matched your search
@@ -10,6 +10,7 @@ Use this skill for every loading state, following the [Loading pattern](https://
|
||||
## Pick The Indicator
|
||||
|
||||
- Use a skeleton from `src/components/skeleton/` (`ha-skeleton`, `ha-skeleton-text`, `ha-skeleton-icon`, `ha-skeleton-log`) when content loads into a layout you already know, such as table rows, tile text, or a log. It holds the layout, so nothing jumps when the content arrives.
|
||||
- Use `ha-skeleton-overlay` when the content renders before its data arrives, such as a card or badge, or when content reloads over what's already shown. See [Skeleton Overlay](#skeleton-overlay).
|
||||
- Use `ha-spinner` only when a whole area loads and its shape is unknown.
|
||||
- Use `ha-button` with `loading`, or `ha-progress-button`, for an action started from a button. Don't put a separate spinner next to it.
|
||||
|
||||
@@ -27,7 +28,7 @@ Wrap the indicator in `ha-fade-in` from `src/components/animation/ha-fade-in.ts`
|
||||
|
||||
- Fade a skeleton in straight away over about 300ms (`.duration=${300}`), as the data table does. It stands in for the content, so a delay would leave an empty gap.
|
||||
- Delay a spinner or progress bar, usually by `.delay=${500}`, so a load that finishes within that time never flashes it. Some slower areas, such as backups and updates, use `${1000}`.
|
||||
- Don't fade in the loaded content itself.
|
||||
- Don't add your own fade to loaded content. `ha-skeleton-overlay` fades each part in over `--ha-animation-duration-fast`, which reduced motion makes instant.
|
||||
|
||||
Give a skeleton group the `progressbar` role and a translated label, as `ha-spinner` has, rather than visible "Loading" text.
|
||||
|
||||
@@ -45,6 +46,24 @@ html`
|
||||
`;
|
||||
```
|
||||
|
||||
## Skeleton Overlay
|
||||
|
||||
`ha-skeleton-overlay` reads a skeleton from the content it wraps, so it can't drift from it: each text line, icon, image, control and drawing gets its own piece, and the real parts are hidden underneath until loading ends. Prefer it to drawing a skeleton by hand whenever the content can render before its data.
|
||||
|
||||
```ts
|
||||
html`
|
||||
<ha-skeleton-overlay .loading=${this._loading}>
|
||||
<my-content></my-content>
|
||||
</ha-skeleton-overlay>
|
||||
`;
|
||||
```
|
||||
|
||||
- Turn it on with `loading`, or fire `skeleton-loading` (`{ loading: true }`, later `{ loading: false }`) from inside the content. The event stops at the nearest overlay, so content doesn't need to know what wraps it.
|
||||
- Mark parts that shouldn't be read with `data-skeleton`: `none` leaves an element out and showing, `keep` leaves it showing but reads what's inside, and `text`, `round` or `block` force one piece of that kind. Skeletons the content draws itself are left alone.
|
||||
- Put your own skeleton in the `skeleton` slot to replace the reading altogether.
|
||||
- Call `refresh()` when the content changes without changing size.
|
||||
- It gives the skeleton the `progressbar` role and the translated label itself.
|
||||
|
||||
## Checking It
|
||||
|
||||
Check a loading state in the browser, not only by reading the code. These work on any setup: a dev server, the demo, or the gallery.
|
||||
@@ -71,5 +90,6 @@ Check a loading state in the browser, not only by reading the code. These work o
|
||||
};
|
||||
```
|
||||
|
||||
- **Compare the skeleton with the content.** It should take the same space, so nothing moves when the content arrives. Measure the wrapper's height while loading and once loaded (`element.getBoundingClientRect().height` in the console), or take a screenshot of each at the same size and flick between them. Look for pieces that are missing, extra or in the wrong place, and fix those with `data-skeleton`.
|
||||
- **Compare before and after.** Take screenshots of the same screen on `dev` and on your branch, at the same viewport size, both loading and loaded, and put them side by side. In a pull request, show both.
|
||||
- **Check every look.** Light and dark themes, a right-to-left language (the wave starts from the right), reduced motion (DevTools, Rendering, "Emulate CSS media feature prefers-reduced-motion": the wave stops), and a phone width (DevTools device toolbar).
|
||||
@@ -61,6 +61,6 @@ The badge component is a small component that displays a number or status inform
|
||||
**CSS Custom Properties**
|
||||
|
||||
- `--ha-badge-size` (default `36px`)
|
||||
- `--ha-badge-border-radius` (default `calc(var(--ha-badge-size, 36px) / 2)`)
|
||||
- `--ha-badge-border-radius` (default `calc(var(--ha-border-radius-lg) + 3px)`)
|
||||
- `--ha-badge-font-size` (default `var(--ha-font-size-s)`)
|
||||
- `--ha-badge-icon-size` (default `18px`)
|
||||
@@ -54,6 +54,29 @@ lorem | ipsum
|
||||
`,
|
||||
})
|
||||
),
|
||||
mdContentwithDefaults({
|
||||
content: `
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/markdown-rendering-brightgreen" alt="Centred badge">
|
||||
</p>
|
||||
|
||||
- [Installation](#installation)
|
||||
- [Configuration](#configuration)
|
||||
|
||||
## Installation
|
||||
|
||||
Install it from the Marketplace[^marketplace] and restart Home Assistant.[^restart]
|
||||
|
||||
## Configuration
|
||||
|
||||
Add the integration from the integrations page.
|
||||
|
||||
[Back to the top](#installation)
|
||||
|
||||
[^marketplace]: Settings > Marketplace.
|
||||
[^restart]: Only needed the first time.
|
||||
`,
|
||||
}),
|
||||
];
|
||||
|
||||
@customElement("demo-misc-ha-markdown")
|
||||
|
||||
@@ -110,6 +110,8 @@
|
||||
"lit-html": "3.3.3",
|
||||
"maplibre-gl": "6.20.0",
|
||||
"marked": "18.3.0",
|
||||
"marked-footnote": "1.4.0",
|
||||
"marked-gfm-heading-id": "4.1.4",
|
||||
"memoize-one": "7.0.0",
|
||||
"nanoid": "6.0.2",
|
||||
"node-vibrant": "4.0.4",
|
||||
|
||||
Generated
+50
-20
@@ -408,6 +408,12 @@ importers:
|
||||
marked:
|
||||
specifier: 18.3.0
|
||||
version: 18.3.0
|
||||
marked-footnote:
|
||||
specifier: 1.4.0
|
||||
version: 1.4.0([email protected])
|
||||
marked-gfm-heading-id:
|
||||
specifier: 4.1.4
|
||||
version: 4.1.4([email protected])
|
||||
memoize-one:
|
||||
specifier: 7.0.0
|
||||
version: 7.0.0
|
||||
@@ -717,13 +723,13 @@ importers:
|
||||
version: 8.74.0([email protected]([email protected]))([email protected])([email protected])([email protected])
|
||||
vite:
|
||||
specifier: 8.4.0
|
||||
version: 8.4.0(@types/[email protected])([email protected]0.0)([email protected])
|
||||
version: 8.4.0(@types/[email protected])([email protected]1.4)([email protected])
|
||||
vite-tsconfig-paths:
|
||||
specifier: 6.1.1
|
||||
version: 6.1.1([email protected])([email protected])([email protected](@types/[email protected])([email protected]0.0)([email protected]))
|
||||
version: 6.1.1([email protected])([email protected])([email protected](@types/[email protected])([email protected]1.4)([email protected]))
|
||||
vitest:
|
||||
specifier: 5.1.2
|
||||
version: 5.1.2(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected]0.0)([email protected]))
|
||||
version: 5.1.2(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected]1.4)([email protected]))
|
||||
webpack-stats-plugin:
|
||||
specifier: 1.1.3
|
||||
version: 1.1.3
|
||||
@@ -5386,6 +5392,9 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-2760b1vpJHNmLzZ/ubTtNnEx5WApN/PYWJvXvgS+tL1egTTthayFYIQQNi136FLEDcN/IyEY2EcGpIITD6eYUw==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==}
|
||||
|
||||
@@ -6213,6 +6222,16 @@ packages:
|
||||
resolution: {integrity: sha512-7manvqXeNoN0mKRzenYDopkb3VW9j7iag45RvopkOVFZ7c+La7CBWtK8eBS5bKrI6NyxqAIxPxIG1PMcotcY1w==}
|
||||
engines: {node: '>=16.14.0', npm: '>=8.1.0'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-fZTxAhI1TcLEs5UOjCfYfTHpyKGaWQevbxaGTEA68B51l7i87SctPFtHETYqPkEN0ka5opvy4Dy1l/yXVC+hmg==}
|
||||
peerDependencies:
|
||||
marked: '>=7.0.0'
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-CspnvVfHSkb/znqdPS4jUR8HtCjq3M/DnrsJCrfLBLvdrgbemmoINKpeWKQYkBiXAoBGejw0cV7xzqrPdup3WA==}
|
||||
peerDependencies:
|
||||
marked: '>=13 <19'
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-HR0m3bvu0jAPYiIvLUUQtdg1g6D247//lvcekpHO1WMvbwDlwSkZAX9Lw4F4YHE1T0HaaNve0tuAWuV1UJ6vtw==}
|
||||
engines: {node: '>= 18'}
|
||||
@@ -7483,8 +7502,8 @@ packages:
|
||||
uglify-js:
|
||||
optional: true
|
||||
|
||||
[email protected]0.0:
|
||||
resolution: {integrity: sha512-CN9BVxWhgS/hRxtUMjtC2uRWSTcSfQFHMDWma6sKKfIivCD91sM+FOPfvwoaRMqCSrUpe1nv3jDamd9eEQ4y+w==}
|
||||
[email protected]1.4:
|
||||
resolution: {integrity: sha512-VPi1CkDvCWLGUVIToctNBG+NdHbSXwOPjHJnQ3pdB0XknaldnI76wSkAFOGxV2ZdkzOP5d6gpQ5c58XvDghRvw==}
|
||||
engines: {node: '>=10'}
|
||||
hasBin: true
|
||||
|
||||
@@ -10789,7 +10808,7 @@ snapshots:
|
||||
dependencies:
|
||||
serialize-javascript: 7.1.4
|
||||
smob: 1.6.2
|
||||
terser: 5.50.0
|
||||
terser: 5.51.4
|
||||
optionalDependencies:
|
||||
rollup: 4.62.4
|
||||
|
||||
@@ -11816,7 +11835,7 @@ snapshots:
|
||||
obug: 3.0.0
|
||||
std-env: 4.3.0
|
||||
tinyrainbow: 3.2.0
|
||||
vitest: 5.1.2(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected]0.0)([email protected]))
|
||||
vitest: 5.1.2(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected]1.4)([email protected]))
|
||||
|
||||
'@vitest/[email protected]': {}
|
||||
|
||||
@@ -11824,14 +11843,14 @@ snapshots:
|
||||
dependencies:
|
||||
'@vitest/istanbul-lib-coverage': 2.1.1
|
||||
|
||||
'@vitest/[email protected]([email protected](@types/[email protected])([email protected]0.0)([email protected]))':
|
||||
'@vitest/[email protected]([email protected](@types/[email protected])([email protected]1.4)([email protected]))':
|
||||
dependencies:
|
||||
'@jridgewell/trace-mapping': 0.3.31
|
||||
'@vitest/spy': 5.1.2
|
||||
estree-walker: 3.0.3
|
||||
magic-string: 1.4.5
|
||||
optionalDependencies:
|
||||
vite: 8.4.0(@types/[email protected])([email protected]0.0)([email protected])
|
||||
vite: 8.4.0(@types/[email protected])([email protected]1.4)([email protected])
|
||||
|
||||
'@vitest/[email protected]': {}
|
||||
|
||||
@@ -13344,6 +13363,8 @@ snapshots:
|
||||
image-q: 4.0.0
|
||||
omggif: 1.0.10
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
@@ -13543,7 +13564,7 @@ snapshots:
|
||||
entities: 8.0.0
|
||||
lightningcss: 1.33.0
|
||||
svgo: 4.1.0
|
||||
terser: 5.50.0
|
||||
terser: 5.51.4
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -13553,7 +13574,7 @@ snapshots:
|
||||
entities: 4.5.0
|
||||
param-case: 3.0.4
|
||||
relateurl: 0.2.7
|
||||
terser: 5.50.0
|
||||
terser: 5.51.4
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -14245,6 +14266,15 @@ snapshots:
|
||||
- react
|
||||
- use-sync-external-store
|
||||
|
||||
[email protected]([email protected]):
|
||||
dependencies:
|
||||
marked: 18.3.0
|
||||
|
||||
[email protected]([email protected]):
|
||||
dependencies:
|
||||
github-slugger: 2.0.0
|
||||
marked: 18.3.0
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
@@ -15659,7 +15689,7 @@ snapshots:
|
||||
'@jridgewell/trace-mapping': 0.3.31
|
||||
jest-worker: 27.5.1
|
||||
schema-utils: 4.3.3
|
||||
terser: 5.50.0
|
||||
terser: 5.51.4
|
||||
optionalDependencies:
|
||||
clean-css: 5.3.3
|
||||
csso: 5.0.5
|
||||
@@ -15667,7 +15697,7 @@ snapshots:
|
||||
lightningcss: 1.33.0
|
||||
postcss: 8.5.33
|
||||
|
||||
[email protected]0.0:
|
||||
[email protected]1.4:
|
||||
dependencies:
|
||||
'@jridgewell/source-map': 0.3.11
|
||||
acorn: 8.18.0
|
||||
@@ -16035,17 +16065,17 @@ snapshots:
|
||||
- bare-abort-controller
|
||||
- react-native-b4a
|
||||
|
||||
[email protected]([email protected])([email protected])([email protected](@types/[email protected])([email protected]0.0)([email protected])):
|
||||
[email protected]([email protected])([email protected])([email protected](@types/[email protected])([email protected]1.4)([email protected])):
|
||||
dependencies:
|
||||
debug: 4.4.3([email protected])
|
||||
globrex: 0.1.2
|
||||
tsconfck: 3.1.6([email protected])
|
||||
vite: 8.4.0(@types/[email protected])([email protected]0.0)([email protected])
|
||||
vite: 8.4.0(@types/[email protected])([email protected]1.4)([email protected])
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
- typescript
|
||||
|
||||
[email protected](@types/[email protected])([email protected]0.0)([email protected]):
|
||||
[email protected](@types/[email protected])([email protected]1.4)([email protected]):
|
||||
dependencies:
|
||||
lightningcss: 1.33.0
|
||||
picomatch: 4.0.7
|
||||
@@ -16056,13 +16086,13 @@ snapshots:
|
||||
'@types/node': 24.19.4
|
||||
fsevents: 2.3.3
|
||||
napi-windows-process-start-time: 0.1.0
|
||||
terser: 5.50.0
|
||||
terser: 5.51.4
|
||||
yaml: 2.9.1
|
||||
|
||||
[email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected]0.0)([email protected])):
|
||||
[email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected]1.4)([email protected])):
|
||||
dependencies:
|
||||
'@types/chai': 5.2.3
|
||||
'@vitest/mocker': 5.1.2([email protected](@types/[email protected])([email protected]0.0)([email protected]))
|
||||
'@vitest/mocker': 5.1.2([email protected](@types/[email protected])([email protected]1.4)([email protected]))
|
||||
chai: 6.3.0
|
||||
es-module-lexer: 2.3.2
|
||||
expect-type: 1.4.0
|
||||
@@ -16073,7 +16103,7 @@ snapshots:
|
||||
tinybench: 6.2.3
|
||||
tinyexec: 1.4.0
|
||||
tinyglobby: 0.2.17
|
||||
vite: 8.4.0(@types/[email protected])([email protected]0.0)([email protected])
|
||||
vite: 8.4.0(@types/[email protected])([email protected]1.4)([email protected])
|
||||
why-is-node-running: 3.2.1
|
||||
optionalDependencies:
|
||||
'@types/node': 24.19.4
|
||||
|
||||
@@ -0,0 +1,623 @@
|
||||
/**
|
||||
* Read a skeleton from rendered content, such as a dashboard card: where its
|
||||
* text lines, icons, images, controls and drawings are, inside shadow roots
|
||||
* too. The content stays the source of truth for layout, so the skeleton
|
||||
* can't drift from it.
|
||||
*
|
||||
* Any element can say how it's read with a `data-skeleton` attribute:
|
||||
* - `text`, `round` or `block`: one piece of that kind, the size of the element
|
||||
* - `none`: left out and left showing, such as a card's own chrome
|
||||
* - `keep`: left showing, but what's inside it is still read
|
||||
*
|
||||
* Skeletons a component already draws itself (`ha-skeleton` and its
|
||||
* variants) are left out and left showing, as `none`.
|
||||
*/
|
||||
|
||||
export type SkeletonPieceKind = "text" | "round" | "block" | "shape" | "scrim";
|
||||
|
||||
type SkeletonOverride = "text" | "round" | "block" | "none" | "keep";
|
||||
|
||||
const OVERRIDES = new Set<string>(["text", "round", "block", "none", "keep"]);
|
||||
|
||||
const isOverride = (value: string | null): value is SkeletonOverride =>
|
||||
value !== null && OVERRIDES.has(value);
|
||||
|
||||
const skeletonOverride = (element: Element): SkeletonOverride | undefined => {
|
||||
if (element.localName.startsWith("ha-skeleton")) {
|
||||
return "none";
|
||||
}
|
||||
|
||||
const value = element.getAttribute("data-skeleton");
|
||||
|
||||
return isOverride(value) ? value : undefined;
|
||||
};
|
||||
|
||||
export interface SkeletonPiece {
|
||||
kind: SkeletonPieceKind;
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
radius?: string;
|
||||
/* An SVG mask for a drawing, such as a gauge arc */
|
||||
mask?: string;
|
||||
/* Where that mask sits in the piece, when something cuts the drawing short:
|
||||
still the drawing's whole size and place, with the piece only its part */
|
||||
maskBox?: { x: number; y: number; width: number; height: number };
|
||||
/* The part sits on a dark overlay, such as a picture card's name bar */
|
||||
onDark?: boolean;
|
||||
/* A see-through bar laid over a picture, kept as it is */
|
||||
background?: string;
|
||||
}
|
||||
|
||||
export interface ExtractedSkeleton {
|
||||
pieces: SkeletonPiece[];
|
||||
/* The elements the pieces stand in for, hidden while loading */
|
||||
parts: (HTMLElement | SVGElement)[];
|
||||
/* Elements holding text: hide only the text colour, as the same element
|
||||
often draws a frame, such as a badge's pill, that has to stay */
|
||||
textParts: HTMLElement[];
|
||||
}
|
||||
|
||||
const ROUND_TAGS = new Set([
|
||||
"ha-tile-icon",
|
||||
"ha-state-icon",
|
||||
"ha-svg-icon",
|
||||
"ha-icon",
|
||||
"state-badge",
|
||||
]);
|
||||
|
||||
const BLOCK_TAGS = new Set(["img", "video", "canvas", "ha-camera-stream"]);
|
||||
|
||||
/* A canvas to measure fonts with, made on first use */
|
||||
let measuringContext: CanvasRenderingContext2D | null | undefined;
|
||||
|
||||
const fontContext = (style: CSSStyleDeclaration, size: string) => {
|
||||
measuringContext ??= document.createElement("canvas").getContext("2d");
|
||||
|
||||
if (measuringContext) {
|
||||
measuringContext.font = `${style.fontStyle} ${style.fontWeight} ${size} ${style.fontFamily}`;
|
||||
}
|
||||
|
||||
return measuringContext;
|
||||
};
|
||||
|
||||
/**
|
||||
* Where a text bar goes on a line of this font: from the top of the
|
||||
* capitals down to the baseline, measured from the font itself.
|
||||
* `size` is the size as drawn, after any SVG scaling.
|
||||
*/
|
||||
const capitalBand = (style: CSSStyleDeclaration, size: number) => {
|
||||
const metrics = fontContext(style, `${size}px`)?.measureText("H");
|
||||
|
||||
// Missing before Chrome 87 and Firefox 116
|
||||
if (!metrics?.fontBoundingBoxAscent || !metrics.actualBoundingBoxAscent) {
|
||||
return { top: size * 0.2, height: size * 0.7 };
|
||||
}
|
||||
|
||||
return {
|
||||
// The line box holds the font's ascent, so the baseline sits that far down
|
||||
top: metrics.fontBoundingBoxAscent - metrics.actualBoundingBoxAscent,
|
||||
height: metrics.actualBoundingBoxAscent,
|
||||
};
|
||||
};
|
||||
|
||||
/* How wide "…" is in this font, the room cut-off text leaves at its end */
|
||||
const ellipsisWidth = (style: CSSStyleDeclaration) =>
|
||||
fontContext(style, style.fontSize)?.measureText("…").width ??
|
||||
parseFloat(style.fontSize);
|
||||
|
||||
/* The icon as drawn, not its box, which a line of text can crop */
|
||||
const findGlyph = (element: Element, depth = 4): Element | undefined => {
|
||||
if (depth === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
for (const child of [
|
||||
...(element.shadowRoot?.children ?? []),
|
||||
...element.children,
|
||||
]) {
|
||||
if (child instanceof SVGSVGElement) {
|
||||
return child;
|
||||
}
|
||||
|
||||
const found = findGlyph(child, depth - 1);
|
||||
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/* Near-white text or icons, as on a picture card's dark name bar */
|
||||
const isNearWhite = (color: string): boolean => {
|
||||
const channels = color
|
||||
.match(/[\d.]+/g)
|
||||
?.slice(0, 3)
|
||||
.map(Number);
|
||||
|
||||
return channels?.length === 3 && channels.every((channel) => channel >= 200);
|
||||
};
|
||||
|
||||
const isRendered = (style: CSSStyleDeclaration) =>
|
||||
style.display !== "none" && style.visibility !== "hidden";
|
||||
|
||||
const isSeeThrough = (color: string) => {
|
||||
const alpha = Number(color.match(/rgba\(.*,\s*([\d.]+)\)/)?.[1] ?? 1);
|
||||
|
||||
return alpha > 0 && alpha < 1;
|
||||
};
|
||||
|
||||
/* The first element, inside shadow roots too, that rounds its corners */
|
||||
const findRounded = (element: Element, depth = 4): Element | undefined => {
|
||||
if (depth === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const children = [
|
||||
...(element.shadowRoot?.children ?? []),
|
||||
...element.children,
|
||||
];
|
||||
|
||||
for (const child of children) {
|
||||
if (parseFloat(getComputedStyle(child).borderTopLeftRadius) > 0) {
|
||||
return child;
|
||||
}
|
||||
|
||||
const found = findRounded(child, depth - 1);
|
||||
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/* Join the pieces of one line of text, such as "Heat", "·" and "21 °C" */
|
||||
const mergeLines = (pieces: SkeletonPiece[]): SkeletonPiece[] => {
|
||||
const merged: SkeletonPiece[] = [];
|
||||
|
||||
for (const piece of pieces) {
|
||||
const previous = merged[merged.length - 1];
|
||||
|
||||
// Either side, so right-to-left lines join too
|
||||
const gap = previous
|
||||
? Math.max(
|
||||
piece.x - (previous.x + previous.width),
|
||||
previous.x - (piece.x + piece.width)
|
||||
)
|
||||
: Infinity;
|
||||
|
||||
const sameLine =
|
||||
previous?.kind === "text" &&
|
||||
piece.kind === "text" &&
|
||||
Math.abs(previous.y - piece.y) < 2 &&
|
||||
Math.abs(previous.height - piece.height) < 2 &&
|
||||
gap < 12;
|
||||
|
||||
if (sameLine) {
|
||||
const left = Math.min(previous.x, piece.x);
|
||||
|
||||
const right = Math.max(
|
||||
previous.x + previous.width,
|
||||
piece.x + piece.width
|
||||
);
|
||||
|
||||
previous.x = left;
|
||||
previous.width = right - left;
|
||||
continue;
|
||||
}
|
||||
|
||||
merged.push({ ...piece });
|
||||
}
|
||||
|
||||
return merged;
|
||||
};
|
||||
|
||||
const svgMask = (svg: SVGSVGElement, width: number, height: number) => {
|
||||
const clone = svg.cloneNode(true);
|
||||
|
||||
if (!(clone instanceof SVGSVGElement)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const originals = [svg, ...svg.querySelectorAll("*")];
|
||||
const copies = [clone, ...clone.querySelectorAll("*")];
|
||||
let drawnPaths = 0;
|
||||
|
||||
originals.forEach((original, index) => {
|
||||
const copy = copies[index];
|
||||
const style = getComputedStyle(original);
|
||||
|
||||
if (original.localName === "text" || !isRendered(style)) {
|
||||
copy.setAttribute("display", "none");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (original !== svg && original.localName !== "g") {
|
||||
drawnPaths++;
|
||||
}
|
||||
|
||||
copy.removeAttribute("class");
|
||||
copy.removeAttribute("style");
|
||||
copy.setAttribute("fill", style.fill === "none" ? "none" : "#000");
|
||||
copy.setAttribute("stroke", style.stroke === "none" ? "none" : "#000");
|
||||
copy.setAttribute("stroke-width", style.strokeWidth);
|
||||
copy.setAttribute("stroke-linecap", style.strokeLinecap);
|
||||
|
||||
// Keep what moves or cuts a shape, such as a gauge's needle and the
|
||||
// dashes that draw its value arc
|
||||
if (style.transform !== "none") {
|
||||
copy.setAttribute(
|
||||
"style",
|
||||
`transform: ${style.transform}; transform-origin: ${style.transformOrigin}; transform-box: ${style.transformBox}`
|
||||
);
|
||||
}
|
||||
|
||||
if (style.strokeDasharray !== "none") {
|
||||
copy.setAttribute("stroke-dasharray", style.strokeDasharray);
|
||||
copy.setAttribute("stroke-dashoffset", style.strokeDashoffset);
|
||||
}
|
||||
});
|
||||
|
||||
if (drawnPaths === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
clone.setAttribute("width", String(width));
|
||||
clone.setAttribute("height", String(height));
|
||||
|
||||
const markup = new XMLSerializer().serializeToString(clone);
|
||||
|
||||
return `url("data:image/svg+xml,${encodeURIComponent(markup)}")`;
|
||||
};
|
||||
|
||||
export const extractSkeleton = (
|
||||
root: Element,
|
||||
origin: DOMRect
|
||||
): ExtractedSkeleton => {
|
||||
const pieces: SkeletonPiece[] = [];
|
||||
const parts = new Set<HTMLElement | SVGElement>();
|
||||
const textParts = new Set<HTMLElement>();
|
||||
|
||||
/* The card's own background, the first solid one found */
|
||||
let surface: string | undefined;
|
||||
|
||||
const box = (rect: DOMRect) => ({
|
||||
x: rect.left - origin.left,
|
||||
y: rect.top - origin.top,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
});
|
||||
|
||||
/* Near-white content on a light card must sit on a dark bar */
|
||||
const onDark = (style: CSSStyleDeclaration) =>
|
||||
surface !== undefined && isNearWhite(surface) && isNearWhite(style.color);
|
||||
|
||||
/* An element that cuts off its overflow, such as a scrolling list, cuts the
|
||||
pieces read inside it too, as the overlay draws them on a layer of its
|
||||
own where that clip doesn't reach */
|
||||
const clipPieces = (from: number, rect: DOMRect) => {
|
||||
const bounds = box(rect);
|
||||
|
||||
const clipped = pieces.splice(from).flatMap((piece): SkeletonPiece[] => {
|
||||
const x = Math.max(piece.x, bounds.x);
|
||||
const y = Math.max(piece.y, bounds.y);
|
||||
const right = Math.min(piece.x + piece.width, bounds.x + bounds.width);
|
||||
const bottom = Math.min(piece.y + piece.height, bounds.y + bounds.height);
|
||||
|
||||
if (right <= x || bottom <= y) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const cut = { ...piece, x, y, width: right - x, height: bottom - y };
|
||||
|
||||
// A drawing's mask is made for its whole box, so it keeps that box
|
||||
if (piece.kind === "shape") {
|
||||
const mask = piece.maskBox ?? {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: piece.width,
|
||||
height: piece.height,
|
||||
};
|
||||
|
||||
return [
|
||||
{
|
||||
...cut,
|
||||
maskBox: {
|
||||
...mask,
|
||||
x: piece.x + mask.x - x,
|
||||
y: piece.y + mask.y - y,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return [cut];
|
||||
});
|
||||
|
||||
pieces.push(...clipped);
|
||||
};
|
||||
|
||||
const addText = (element: Element | ShadowRoot) => {
|
||||
const owner = element instanceof ShadowRoot ? element.host : element;
|
||||
|
||||
// Text cut short with an ellipsis reaches past its box, so clip to it.
|
||||
// An owner with no box of its own, such as one with display: contents,
|
||||
// cuts nothing off.
|
||||
const clip = owner.getBoundingClientRect();
|
||||
const clips = clip.width > 0 || clip.height > 0;
|
||||
|
||||
element.childNodes.forEach((node) => {
|
||||
if (!(node instanceof Text) || !node.textContent?.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Slotted text takes its font and colour from the slot it shows in,
|
||||
// so that's where it's measured and hidden
|
||||
const slot = node.assignedSlot;
|
||||
const hideTarget = slot ?? owner;
|
||||
const style = getComputedStyle(hideTarget);
|
||||
const band = capitalBand(style, parseFloat(style.fontSize));
|
||||
|
||||
if (hideTarget instanceof HTMLElement) {
|
||||
textParts.add(hideTarget);
|
||||
}
|
||||
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(node);
|
||||
|
||||
for (const rect of range.getClientRects()) {
|
||||
// Cut-off text ends in "…", on the right or, right to left, on the
|
||||
// left, so stop the bar where that starts
|
||||
const left =
|
||||
clips && rect.left < clip.left - 1
|
||||
? clip.left + ellipsisWidth(style)
|
||||
: rect.left;
|
||||
|
||||
const right =
|
||||
clips && rect.right > clip.right + 1
|
||||
? clip.right - ellipsisWidth(style)
|
||||
: rect.right;
|
||||
|
||||
if (right <= left) {
|
||||
continue;
|
||||
}
|
||||
|
||||
pieces.push({
|
||||
kind: "text",
|
||||
x: left - origin.left,
|
||||
width: right - left,
|
||||
y: rect.top - origin.top + band.top,
|
||||
height: band.height,
|
||||
onDark: onDark(style),
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const walk = (node: Element | ShadowRoot) => {
|
||||
// Text straight inside a shadow root, as state-display renders its state
|
||||
if (node instanceof ShadowRoot) {
|
||||
addText(node);
|
||||
}
|
||||
|
||||
for (const child of node.children) {
|
||||
const style = getComputedStyle(child);
|
||||
|
||||
if (!isRendered(style)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const rect = child.getBoundingClientRect();
|
||||
const tag = child.localName;
|
||||
// Elements such as slots take no space but their content does
|
||||
const hasSize = rect.width > 0 && rect.height > 0;
|
||||
const override = skeletonOverride(child);
|
||||
|
||||
if (override === "none") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const clipsOverflow =
|
||||
hasSize &&
|
||||
(style.overflowX !== "visible" || style.overflowY !== "visible");
|
||||
|
||||
const from = pieces.length;
|
||||
|
||||
// Read what's inside, cut to the child where it hides its overflow
|
||||
const descend = () => {
|
||||
if (child instanceof HTMLElement) {
|
||||
addText(child);
|
||||
}
|
||||
|
||||
if (child.shadowRoot) {
|
||||
walk(child.shadowRoot);
|
||||
}
|
||||
|
||||
walk(child);
|
||||
|
||||
if (clipsOverflow) {
|
||||
clipPieces(from, rect);
|
||||
}
|
||||
};
|
||||
|
||||
if (override === "keep") {
|
||||
// Its frame stays, but its own text is read like any other
|
||||
descend();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (override !== undefined) {
|
||||
if (
|
||||
hasSize &&
|
||||
(child instanceof HTMLElement || child instanceof SVGElement)
|
||||
) {
|
||||
const size = Math.min(rect.width, rect.height);
|
||||
const piece = box(rect);
|
||||
|
||||
pieces.push(
|
||||
override === "round"
|
||||
? {
|
||||
kind: "round",
|
||||
x: piece.x + (piece.width - size) / 2,
|
||||
y: piece.y + (piece.height - size) / 2,
|
||||
width: size,
|
||||
height: size,
|
||||
}
|
||||
: { kind: override, ...piece, radius: style.borderRadius }
|
||||
);
|
||||
parts.add(child);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
surface === undefined &&
|
||||
hasSize &&
|
||||
style.backgroundColor !== "rgba(0, 0, 0, 0)" &&
|
||||
!isSeeThrough(style.backgroundColor)
|
||||
) {
|
||||
surface = style.backgroundColor;
|
||||
}
|
||||
|
||||
if (child instanceof HTMLElement && ROUND_TAGS.has(tag)) {
|
||||
// Use the circle itself, such as the tile icon's 36px background
|
||||
const circle = (
|
||||
findRounded(child) ??
|
||||
findGlyph(child) ??
|
||||
child
|
||||
).getBoundingClientRect();
|
||||
|
||||
const size =
|
||||
Math.min(circle.width, circle.height) ||
|
||||
Math.max(circle.width, circle.height);
|
||||
|
||||
const piece = box(circle);
|
||||
|
||||
if (size > 0) {
|
||||
pieces.push({
|
||||
kind: "round",
|
||||
x: piece.x + (piece.width - size) / 2,
|
||||
y: piece.y + (piece.height - size) / 2,
|
||||
width: size,
|
||||
height: size,
|
||||
onDark: onDark(style),
|
||||
});
|
||||
parts.add(child);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// A see-through bar over a picture stays, so text keeps its contrast
|
||||
if (
|
||||
child instanceof HTMLElement &&
|
||||
hasSize &&
|
||||
style.position === "absolute" &&
|
||||
isSeeThrough(style.backgroundColor)
|
||||
) {
|
||||
pieces.push({
|
||||
kind: "scrim",
|
||||
...box(rect),
|
||||
radius: style.borderRadius,
|
||||
background: style.backgroundColor,
|
||||
});
|
||||
}
|
||||
|
||||
// Pictures drawn as a background, as hui-image does in a fixed ratio
|
||||
if (
|
||||
child instanceof HTMLElement &&
|
||||
hasSize &&
|
||||
style.backgroundImage.startsWith("url(")
|
||||
) {
|
||||
pieces.push({
|
||||
kind: "block",
|
||||
...box(rect),
|
||||
radius: style.borderRadius,
|
||||
});
|
||||
parts.add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (child instanceof HTMLElement && hasSize && BLOCK_TAGS.has(tag)) {
|
||||
pieces.push({
|
||||
kind: "block",
|
||||
...box(rect),
|
||||
radius: style.borderRadius,
|
||||
});
|
||||
parts.add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
child instanceof HTMLElement &&
|
||||
hasSize &&
|
||||
tag.endsWith("-card-feature")
|
||||
) {
|
||||
const control = findRounded(child);
|
||||
|
||||
const radius = control
|
||||
? getComputedStyle(control).borderRadius
|
||||
: style.borderRadius;
|
||||
|
||||
pieces.push({ kind: "block", ...box(rect), radius });
|
||||
parts.add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (child instanceof SVGSVGElement && hasSize) {
|
||||
const piece = box(rect);
|
||||
const mask = svgMask(child, piece.width, piece.height);
|
||||
|
||||
if (mask) {
|
||||
pieces.push({ kind: "shape", ...piece, mask });
|
||||
}
|
||||
|
||||
child.querySelectorAll("text").forEach((text) => {
|
||||
const textRect = text.getBoundingClientRect();
|
||||
|
||||
if (textRect.width === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// SVG text is scaled with its drawing, as the gauge value is
|
||||
const scale = text.getScreenCTM()?.a ?? 1;
|
||||
const textStyle = getComputedStyle(text);
|
||||
|
||||
const band = capitalBand(
|
||||
textStyle,
|
||||
parseFloat(textStyle.fontSize) * scale
|
||||
);
|
||||
|
||||
pieces.push({
|
||||
kind: "text",
|
||||
...box(textRect),
|
||||
y: textRect.top - origin.top + band.top,
|
||||
height: band.height,
|
||||
});
|
||||
});
|
||||
|
||||
parts.add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
descend();
|
||||
}
|
||||
};
|
||||
|
||||
// Text straight inside the root, such as plain text in an overlay
|
||||
addText(root);
|
||||
walk(root);
|
||||
|
||||
return {
|
||||
pieces: mergeLines(pieces),
|
||||
parts: [...parts],
|
||||
textParts: [...textParts],
|
||||
};
|
||||
};
|
||||
@@ -73,7 +73,7 @@ export class HaBadge extends LitElement {
|
||||
width: auto;
|
||||
border-radius: var(
|
||||
--ha-badge-border-radius,
|
||||
calc(var(--ha-badge-size, 36px) / 2)
|
||||
calc(var(--ha-border-radius-lg) + 3px)
|
||||
);
|
||||
background: var(
|
||||
--ha-card-background,
|
||||
@@ -132,7 +132,11 @@ export class HaBadge extends LitElement {
|
||||
::slotted(img[slot="icon"]) {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: var(--ha-picture-border-radius);
|
||||
/* Concentric with the badge, the picture sits 3px inside it */
|
||||
border-radius: calc(
|
||||
var(--ha-badge-border-radius, calc(var(--ha-border-radius-lg) + 3px)) -
|
||||
3px
|
||||
);
|
||||
object-fit: cover;
|
||||
overflow: hidden;
|
||||
margin-left: -10px;
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { ReactiveElement, render, html } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { unsafeHTML } from "lit/directives/unsafe-html.js";
|
||||
import hash from "object-hash";
|
||||
import { consume } from "../common/decorators/consume";
|
||||
import { transform } from "../common/decorators/transform";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { rewriteHtmlUrls } from "../common/dom/rewrite-html-urls";
|
||||
import { internationalizationContext } from "../data/context";
|
||||
import type { FootnoteLabels } from "../resources/markdown-worker";
|
||||
import {
|
||||
USER_CONTENT_PREFIX,
|
||||
userContentId,
|
||||
} from "../resources/markdown-user-content";
|
||||
import { renderMarkdown } from "../resources/render-markdown";
|
||||
import type { HomeAssistantInternationalization } from "../types";
|
||||
import { CacheManager } from "../util/cache-manager";
|
||||
|
||||
const h = (template: ReturnType<typeof unsafeHTML>) => html`${template}`;
|
||||
@@ -43,8 +52,35 @@ class HaMarkdownElement extends ReactiveElement {
|
||||
// For content whose relative addresses belong elsewhere, like a README
|
||||
@property({ attribute: false }) public rewriteUrl?: (url: string) => string;
|
||||
|
||||
// Without translations, like on the auth pages, the worker uses English
|
||||
@state({
|
||||
hasChanged: (value?: FootnoteLabels, oldValue?: FootnoteLabels) =>
|
||||
value?.heading !== oldValue?.heading ||
|
||||
value?.backReference !== oldValue?.backReference,
|
||||
})
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
@transform<HomeAssistantInternationalization, FootnoteLabels>({
|
||||
transformer: ({ localize }) => {
|
||||
const heading = localize("ui.components.markdown.footnotes");
|
||||
|
||||
const backReference = localize(
|
||||
"ui.components.markdown.footnote_back_reference",
|
||||
{ reference: "{0}" }
|
||||
);
|
||||
|
||||
return heading && backReference ? { heading, backReference } : undefined;
|
||||
},
|
||||
})
|
||||
private _footnoteLabels?: FootnoteLabels;
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this.addEventListener("click", this._handleAnchorClick);
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this.removeEventListener("click", this._handleAnchorClick);
|
||||
if (this.cache) {
|
||||
const key = this._computeCacheKey();
|
||||
markdownCache.set(key, this.innerHTML);
|
||||
@@ -87,6 +123,7 @@ class HaMarkdownElement extends ReactiveElement {
|
||||
allowDataUrl: this.allowDataUrl,
|
||||
breaks: this.breaks,
|
||||
rewriteUrl: Boolean(this.rewriteUrl),
|
||||
footnoteLabels: this._footnoteLabels,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -101,6 +138,7 @@ class HaMarkdownElement extends ReactiveElement {
|
||||
allowSvg: this.allowSvg,
|
||||
allowDataUrl: this.allowDataUrl,
|
||||
allowRelativeUrls: Boolean(this.rewriteUrl),
|
||||
footnoteLabels: this._footnoteLabels,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -203,6 +241,88 @@ class HaMarkdownElement extends ReactiveElement {
|
||||
}
|
||||
|
||||
private _resize = () => fireEvent(this, "content-resize");
|
||||
|
||||
// The content is in a shadow root, so the browser can't scroll to a `#` link
|
||||
// in it, and the app would navigate to it instead
|
||||
private _handleAnchorClick = (ev: MouseEvent) => {
|
||||
// Leave opening the link in a new tab or window to the browser
|
||||
if (
|
||||
ev.defaultPrevented ||
|
||||
ev.button !== 0 ||
|
||||
ev.metaKey ||
|
||||
ev.ctrlKey ||
|
||||
ev.shiftKey
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const anchor = ev
|
||||
.composedPath()
|
||||
.find((node) => node instanceof HTMLAnchorElement);
|
||||
|
||||
// Or one the author set to open somewhere else
|
||||
if (anchor?.target && anchor.target !== "_self") {
|
||||
return;
|
||||
}
|
||||
|
||||
const href = anchor?.getAttribute("href");
|
||||
|
||||
if (!href?.startsWith("#") || href.length === 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fragment = href.slice(1);
|
||||
|
||||
// Browsers take #top as the top of the page, READMEs use it for the top
|
||||
const target =
|
||||
this._findAnchorTarget(fragment) ??
|
||||
(fragment.toLowerCase() === "top" ? this : undefined);
|
||||
|
||||
// An anchor that isn't in the content does what it did before
|
||||
if (target) {
|
||||
ev.preventDefault();
|
||||
target.scrollIntoView({ block: "start" });
|
||||
|
||||
// Move focus there too, like the browser does, so Tab carries on from
|
||||
// the target. -1 makes a heading focusable without adding it to Tab.
|
||||
if (target instanceof HTMLElement) {
|
||||
if (!target.hasAttribute("tabindex") && target.tabIndex < 0) {
|
||||
target.tabIndex = -1;
|
||||
}
|
||||
|
||||
target.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Links like `#Setup` and `#%C3%BCber` still find `user-content-setup` and
|
||||
// `user-content-über`, like on GitHub
|
||||
private _findAnchorTarget(fragment: string) {
|
||||
let decoded = fragment;
|
||||
|
||||
try {
|
||||
decoded = decodeURIComponent(fragment);
|
||||
} catch {
|
||||
// Not encoded, look for it as written
|
||||
}
|
||||
|
||||
const ids = [fragment, decoded, decoded.toLowerCase()].flatMap((id) => [
|
||||
userContentId(id),
|
||||
// Heading ids always get the prefix, so `## user-content-setup` has
|
||||
// `user-content-user-content-setup`
|
||||
`${USER_CONTENT_PREFIX}${id}`,
|
||||
]);
|
||||
|
||||
for (const id of new Set(ids)) {
|
||||
const target = this.querySelector(`[id="${CSS.escape(id)}"]`);
|
||||
|
||||
if (target) {
|
||||
return target;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
@@ -201,6 +201,21 @@ export class HaMarkdown extends LitElement {
|
||||
margin-inline: 0;
|
||||
padding-inline: 1em;
|
||||
}
|
||||
section[data-footnotes] {
|
||||
border-top: 1px solid var(--divider-color);
|
||||
margin-top: var(--ha-space-4);
|
||||
color: var(--secondary-text-color);
|
||||
font-size: var(--ha-font-size-s);
|
||||
}
|
||||
/* Read out by screen readers but not shown, like on GitHub */
|
||||
section[data-footnotes] > h2 {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
` as CSSResultGroup;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { consume } from "../../common/decorators/consume";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { transform } from "../../common/decorators/transform";
|
||||
import { caseInsensitiveStringCompare } from "../../common/string/compare";
|
||||
import type { ButtonToggleSelector, SelectOption } from "../../data/selector";
|
||||
import type { ButtonToggleSelector } from "../../data/selector";
|
||||
import { internationalizationContext } from "../../data/context";
|
||||
import type { FrontendLocaleData } from "../../data/translation";
|
||||
import type {
|
||||
@@ -41,8 +41,8 @@ export class HaButtonToggleSelector extends LitElement {
|
||||
const options =
|
||||
this.selector.button_toggle?.options?.map((option) =>
|
||||
typeof option === "object"
|
||||
? (option as SelectOption)
|
||||
: ({ value: option, label: option } as SelectOption)
|
||||
? { ...option, label: option.label ?? option.value }
|
||||
: { value: option, label: option }
|
||||
) || [];
|
||||
|
||||
const translationKey = this.selector.button_toggle?.translation_key;
|
||||
@@ -64,7 +64,7 @@ export class HaButtonToggleSelector extends LitElement {
|
||||
);
|
||||
}
|
||||
|
||||
const toggleButtons: ToggleButton[] = options.map((item: SelectOption) => ({
|
||||
const toggleButtons: ToggleButton[] = options.map((item) => ({
|
||||
label: item.label,
|
||||
value: item.value,
|
||||
}));
|
||||
|
||||
@@ -4,7 +4,6 @@ import memoizeOne from "memoize-one";
|
||||
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import type { PeriodKey, PeriodSelector } from "../../data/selector";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { deepEqual } from "../../common/util/deep-equal";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import "../ha-form/ha-form";
|
||||
@@ -28,8 +27,6 @@ const PERIODS = {
|
||||
|
||||
@customElement("ha-selector-period")
|
||||
export class HaPeriodSelector extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public selector!: PeriodSelector;
|
||||
|
||||
@property({ attribute: false }) public value?: unknown;
|
||||
@@ -87,7 +84,6 @@ export class HaPeriodSelector extends LitElement {
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeHelper=${this._computeHelperCallback}
|
||||
|
||||
@@ -93,6 +93,12 @@ export class HaSelectSelector extends LitElement {
|
||||
if (localizedLabel) {
|
||||
option.label = localizedLabel;
|
||||
}
|
||||
const localizedDescription = this.localizeValue!(
|
||||
`${translationKey}.options_description.${option.value}`
|
||||
);
|
||||
if (localizedDescription) {
|
||||
option.description = localizedDescription;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -321,8 +327,8 @@ export class HaSelectSelector extends LitElement {
|
||||
(selector: SelectSelector) =>
|
||||
selector.select?.options?.map((option) =>
|
||||
typeof option === "object"
|
||||
? (option as SelectOption)
|
||||
: ({ value: String(option), label: option } as SelectOption)
|
||||
? { ...option, label: option.label ?? option.value }
|
||||
: { value: String(option), label: option }
|
||||
) || []
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,619 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import type {
|
||||
ExtractedSkeleton,
|
||||
SkeletonPiece,
|
||||
} from "../../common/dom/extract-skeleton";
|
||||
import { extractSkeleton } from "../../common/dom/extract-skeleton";
|
||||
import type { HASSDomEvent } from "../../common/dom/fire_event";
|
||||
import { parseAnimationDuration } from "../../common/util/parse-animation-duration";
|
||||
import { internationalizationContext } from "../../data/context";
|
||||
import type { HaSkeleton } from "./ha-skeleton";
|
||||
import "./ha-skeleton";
|
||||
|
||||
export interface SkeletonLoadingDetail {
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
interface ArrivingParts {
|
||||
/* The whole content, when it was hidden rather than its parts */
|
||||
content: Element[];
|
||||
opacityParts: (HTMLElement | SVGElement)[];
|
||||
colorParts: HTMLElement[];
|
||||
}
|
||||
|
||||
/* Transitions are held off too, so a part hides at once rather than easing
|
||||
out from under its skeleton */
|
||||
type HiddenProperty = "opacity" | "color" | "transition";
|
||||
|
||||
interface HiddenStyle {
|
||||
/* The inline value from before anything hid it */
|
||||
value: string;
|
||||
/* The value it was hidden with */
|
||||
hidden: string;
|
||||
holders: number;
|
||||
}
|
||||
|
||||
/* Overlays nest, as a stack card's cards each have their own, so two can
|
||||
hide the same element. The first to hide one notes the value it really
|
||||
had, and only the last to let go puts that back, so neither keeps the
|
||||
other's hidden value as the one to restore. */
|
||||
const hiddenStyles: Record<
|
||||
HiddenProperty,
|
||||
Map<HTMLElement | SVGElement, HiddenStyle>
|
||||
> = { opacity: new Map(), color: new Map(), transition: new Map() };
|
||||
|
||||
const hideStyle = (
|
||||
element: HTMLElement | SVGElement,
|
||||
name: HiddenProperty,
|
||||
hidden: string
|
||||
) => {
|
||||
const held = hiddenStyles[name].get(element);
|
||||
|
||||
if (held) {
|
||||
held.holders++;
|
||||
} else {
|
||||
hiddenStyles[name].set(element, {
|
||||
value: element.style[name],
|
||||
hidden,
|
||||
holders: 1,
|
||||
});
|
||||
}
|
||||
|
||||
element.style[name] = hidden;
|
||||
};
|
||||
|
||||
const releaseStyle = (
|
||||
element: HTMLElement | SVGElement,
|
||||
name: HiddenProperty
|
||||
) => {
|
||||
const held = hiddenStyles[name].get(element);
|
||||
|
||||
if (!held) {
|
||||
return;
|
||||
}
|
||||
|
||||
held.holders--;
|
||||
|
||||
if (held.holders === 0) {
|
||||
// Content that set its own value while it was hidden keeps that one
|
||||
if (element.style[name] === held.hidden) {
|
||||
element.style[name] = held.value;
|
||||
}
|
||||
|
||||
hiddenStyles[name].delete(element);
|
||||
}
|
||||
};
|
||||
|
||||
const holdersOf = (element: HTMLElement | SVGElement, name: HiddenProperty) =>
|
||||
hiddenStyles[name].get(element)?.holders ?? 0;
|
||||
|
||||
/* What's left out with data-skeleton="none" under an element, through
|
||||
shadow roots, as the skeleton is read */
|
||||
const leftOut = (root: Element | ShadowRoot): HTMLElement[] =>
|
||||
[...root.querySelectorAll("*")].flatMap((element) => [
|
||||
...(element instanceof HTMLElement && element.dataset.skeleton === "none"
|
||||
? [element]
|
||||
: []),
|
||||
...(element.shadowRoot ? leftOut(element.shadowRoot) : []),
|
||||
]);
|
||||
|
||||
/**
|
||||
* Shows a skeleton of its content while that content loads, read from the
|
||||
* content itself: each line of text, icon, image, control and drawing gets
|
||||
* its own piece. When loading ends, the pieces go and each part fades in.
|
||||
*
|
||||
* Loading is on while `loading` is set, or while anything inside has fired
|
||||
* a `skeleton-loading` event with `{ loading: true }` and not yet
|
||||
* `{ loading: false }`. The event stops at the nearest overlay, so content
|
||||
* doesn't need to know what wraps it.
|
||||
*
|
||||
* To take over:
|
||||
* - put your own skeleton in the `skeleton` slot, and it's used instead of
|
||||
* reading one
|
||||
* - set `data-skeleton` on any element inside, as described in
|
||||
* `extract-skeleton`, to change how that part is read or leave it out
|
||||
* - call `refresh()` when the content changes without changing size
|
||||
*
|
||||
* With nothing to read yet, such as before the content's code has loaded,
|
||||
* it fills itself with one plain wave. The skeleton follows the host's
|
||||
* corner radius.
|
||||
*
|
||||
* @slot - The content.
|
||||
* @slot skeleton - A skeleton of your own, used instead of reading one.
|
||||
*/
|
||||
@customElement("ha-skeleton-overlay")
|
||||
export class HaSkeletonOverlay extends LitElement {
|
||||
@property({ type: Boolean }) public loading = false;
|
||||
|
||||
@property() public effect: HaSkeleton["effect"] = "sheen";
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n?: ContextType<typeof internationalizationContext>;
|
||||
|
||||
/* What's inside that has said it's loading */
|
||||
@state() private _loadingSources = new Set<EventTarget>();
|
||||
|
||||
@state() private _pieces?: SkeletonPiece[];
|
||||
|
||||
@state() private _customSkeleton = false;
|
||||
|
||||
@state() private _onScreen = true;
|
||||
|
||||
@query("slot:not([name])") private _contentSlot?: HTMLSlotElement;
|
||||
|
||||
/* The parts this overlay hides, through hideStyle */
|
||||
private _hiddenOpacity = new Set<HTMLElement | SVGElement>();
|
||||
|
||||
private _hiddenColor = new Set<HTMLElement>();
|
||||
|
||||
private _heldTransition = new Set<HTMLElement | SVGElement>();
|
||||
|
||||
/* Inline colours of content left out inside hidden text, which keeps its
|
||||
own colour meanwhile */
|
||||
private _keptColor = new Map<HTMLElement, string>();
|
||||
|
||||
private _wasLoading = false;
|
||||
|
||||
/* What to fade in once loading has ended */
|
||||
private _arriving?: ArrivingParts;
|
||||
|
||||
/* The fades still running from the last time loading ended */
|
||||
private _fades: Animation[] = [];
|
||||
|
||||
private _measureFrame?: number;
|
||||
|
||||
private _resizeObserver = new ResizeObserver(() => this._scheduleMeasure());
|
||||
|
||||
private _intersectionObserver = new IntersectionObserver((entries) => {
|
||||
this._onScreen = entries[entries.length - 1].isIntersecting;
|
||||
});
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
// On the host rather than the slot, so content that says it's loading
|
||||
// as it connects, before the first render, is heard
|
||||
this.addEventListener("skeleton-loading", this._skeletonLoading);
|
||||
}
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this._resizeObserver.observe(this);
|
||||
this._intersectionObserver.observe(this);
|
||||
this._scheduleMeasure();
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._resizeObserver.disconnect();
|
||||
this._intersectionObserver.disconnect();
|
||||
|
||||
if (this._measureFrame !== undefined) {
|
||||
cancelAnimationFrame(this._measureFrame);
|
||||
this._measureFrame = undefined;
|
||||
}
|
||||
|
||||
// Never leave the content hidden while it's away
|
||||
this._cancelFades();
|
||||
this._showParts();
|
||||
}
|
||||
|
||||
/** Read the skeleton again, after the content changed but not its size */
|
||||
public refresh() {
|
||||
this._scheduleMeasure();
|
||||
}
|
||||
|
||||
private get _isLoading() {
|
||||
return this.loading || this._loadingSources.size > 0;
|
||||
}
|
||||
|
||||
protected willUpdate(changedProperties: PropertyValues<this>) {
|
||||
super.willUpdate(changedProperties);
|
||||
const loading = this._isLoading;
|
||||
|
||||
if (loading && !this._wasLoading) {
|
||||
// A fade still running would show the content over the hidden style
|
||||
this._cancelFades();
|
||||
this._customSkeleton = [...this.children].some(
|
||||
(child) => child.slot === "skeleton"
|
||||
);
|
||||
}
|
||||
|
||||
if (!loading && this._wasLoading) {
|
||||
this._endLoading();
|
||||
}
|
||||
|
||||
this._wasLoading = loading;
|
||||
}
|
||||
|
||||
protected updated(changedProperties: PropertyValues<this>) {
|
||||
super.updated(changedProperties);
|
||||
|
||||
// Only when loading starts: loading events, slot changes, sizes and
|
||||
// refresh() ask for their own, and measuring after every update would
|
||||
// run each frame for content that animates, such as a spinner, as every
|
||||
// reading comes out different and updates again
|
||||
if (this._isLoading && changedProperties.has("loading")) {
|
||||
this._scheduleMeasure();
|
||||
}
|
||||
|
||||
if (this._arriving) {
|
||||
this._fadeIn(this._arriving);
|
||||
this._arriving = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
const loading = this._isLoading;
|
||||
// Named like ha-spinner, which falls back to English before translations
|
||||
// have loaded
|
||||
const label = this._i18n?.localize("ui.common.loading") || "Loading";
|
||||
|
||||
// The content can't be focused, used or read out while it loads, frames
|
||||
// around the hidden parts included, such as a card that takes clicks
|
||||
return html`
|
||||
<div class="content" ?inert=${loading}>
|
||||
<slot
|
||||
class=${classMap({
|
||||
// Before the first reading, or under a skeleton of your own
|
||||
hidden:
|
||||
loading && (this._customSkeleton || this._pieces === undefined),
|
||||
})}
|
||||
@slotchange=${this._contentChanged}
|
||||
></slot>
|
||||
</div>
|
||||
${
|
||||
loading
|
||||
? html`
|
||||
<div class="skeleton" role="progressbar" aria-label=${label}>
|
||||
<slot
|
||||
name="skeleton"
|
||||
@slotchange=${this._skeletonSlotChanged}
|
||||
></slot>
|
||||
${this._customSkeleton ? nothing : this._renderPieces()}
|
||||
</div>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderPieces() {
|
||||
// Nothing still animates off screen
|
||||
const effect = this._onScreen ? this.effect : "none";
|
||||
|
||||
if (!this._pieces?.length) {
|
||||
return html`<ha-skeleton class="fill" .effect=${effect}></ha-skeleton>`;
|
||||
}
|
||||
|
||||
return this._pieces.map((piece) =>
|
||||
piece.kind === "scrim"
|
||||
? html`<div class="piece" style=${pieceStyle(piece)}></div>`
|
||||
: html`<ha-skeleton
|
||||
class=${classMap({
|
||||
piece: true,
|
||||
[piece.kind]: true,
|
||||
"on-dark": Boolean(piece.onDark),
|
||||
})}
|
||||
.effect=${effect}
|
||||
style=${pieceStyle(piece)}
|
||||
></ha-skeleton>`
|
||||
);
|
||||
}
|
||||
|
||||
private _skeletonLoading = (ev: HASSDomEvent<SkeletonLoadingDetail>) => {
|
||||
// The nearest overlay owns it
|
||||
ev.stopPropagation();
|
||||
const source = ev.composedPath()[0];
|
||||
const sources = new Set(this._loadingSources);
|
||||
|
||||
if (ev.detail.loading) {
|
||||
sources.add(source);
|
||||
} else {
|
||||
sources.delete(source);
|
||||
}
|
||||
|
||||
this._loadingSources = sources;
|
||||
this._scheduleMeasure();
|
||||
};
|
||||
|
||||
private _contentChanged() {
|
||||
this._resizeObserver.disconnect();
|
||||
this._resizeObserver.observe(this);
|
||||
this._contentSlot
|
||||
?.assignedElements()
|
||||
.forEach((element) => this._resizeObserver.observe(element));
|
||||
|
||||
this._pruneSources();
|
||||
this._scheduleMeasure();
|
||||
}
|
||||
|
||||
/* Content that went away, or moved out of this overlay, can't finish
|
||||
loading here. Removing it deep inside a card fires no slotchange, so
|
||||
this runs on every measure too, which any change of size starts. */
|
||||
private _pruneSources() {
|
||||
const sources = [...this._loadingSources].filter((source) =>
|
||||
this._holds(source)
|
||||
);
|
||||
|
||||
if (sources.length !== this._loadingSources.size) {
|
||||
this._loadingSources = new Set(sources);
|
||||
}
|
||||
}
|
||||
|
||||
/* Whether a source is still inside this overlay, the way its events
|
||||
travel: through the slots content shows in, and out of shadow roots */
|
||||
private _holds(source: EventTarget) {
|
||||
if (!(source instanceof Node)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let node: Node | null = source;
|
||||
|
||||
while (node) {
|
||||
if (node === this) {
|
||||
return true;
|
||||
}
|
||||
|
||||
node =
|
||||
node instanceof ShadowRoot
|
||||
? node.host
|
||||
: ((node instanceof Element || node instanceof Text
|
||||
? node.assignedSlot
|
||||
: null) ?? node.parentNode);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private _skeletonSlotChanged(ev: Event) {
|
||||
const slot = ev.target;
|
||||
|
||||
if (!(slot instanceof HTMLSlotElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._customSkeleton = slot.assignedNodes({ flatten: true }).length > 0;
|
||||
|
||||
if (this._customSkeleton) {
|
||||
// The whole content is hidden under it instead
|
||||
this._showParts();
|
||||
this._pieces = undefined;
|
||||
} else {
|
||||
// Read from the content again now it's gone
|
||||
this._scheduleMeasure();
|
||||
}
|
||||
}
|
||||
|
||||
private _scheduleMeasure() {
|
||||
if (this._measureFrame !== undefined || !this.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._measureFrame = requestAnimationFrame(() => {
|
||||
this._measureFrame = undefined;
|
||||
this._measure();
|
||||
});
|
||||
}
|
||||
|
||||
/* Read the skeleton from the content, and hide the parts it stands in for */
|
||||
private _measure() {
|
||||
this._pruneSources();
|
||||
|
||||
if (!this._isLoading || this._customSkeleton) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Read from the content as it really looks, then hide it again before
|
||||
// the next paint, so nothing flickers
|
||||
this._showParts();
|
||||
const skeleton = extractSkeleton(this, this.getBoundingClientRect());
|
||||
this._hideParts(skeleton);
|
||||
|
||||
if (JSON.stringify(skeleton.pieces) !== JSON.stringify(this._pieces)) {
|
||||
this._pieces = skeleton.pieces;
|
||||
}
|
||||
}
|
||||
|
||||
private _hideParts(skeleton: ExtractedSkeleton) {
|
||||
skeleton.parts.forEach((part) => {
|
||||
if (!this._hiddenOpacity.has(part)) {
|
||||
this._hiddenOpacity.add(part);
|
||||
hideStyle(part, "opacity", "0");
|
||||
}
|
||||
});
|
||||
|
||||
// What's left out with data-skeleton="none" inside text that's hidden
|
||||
// keeps the colour it has now, rather than taking the transparent one.
|
||||
// Read before any text is hidden.
|
||||
const kept = skeleton.textParts.flatMap((part) =>
|
||||
leftOut(part).map(
|
||||
(element) => [element, getComputedStyle(element).color] as const
|
||||
)
|
||||
);
|
||||
|
||||
// Text goes through its colour, so a frame drawn by the same element,
|
||||
// such as a badge's pill, stays
|
||||
skeleton.textParts.forEach((part) => {
|
||||
if (!this._hiddenColor.has(part)) {
|
||||
this._hiddenColor.add(part);
|
||||
hideStyle(part, "color", "transparent");
|
||||
}
|
||||
});
|
||||
|
||||
kept.forEach(([element, color]) => {
|
||||
if (!this._keptColor.has(element)) {
|
||||
this._keptColor.set(element, element.style.color);
|
||||
}
|
||||
|
||||
element.style.color = color;
|
||||
});
|
||||
|
||||
// In the same frame as the hiding, so no transition runs on it
|
||||
[...skeleton.parts, ...skeleton.textParts].forEach((part) => {
|
||||
if (!this._heldTransition.has(part)) {
|
||||
this._heldTransition.add(part);
|
||||
hideStyle(part, "transition", "none");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private _showParts() {
|
||||
this._hiddenOpacity.forEach((part) => releaseStyle(part, "opacity"));
|
||||
this._hiddenColor.forEach((part) => releaseStyle(part, "color"));
|
||||
this._keptColor.forEach((color, element) => {
|
||||
element.style.color = color;
|
||||
});
|
||||
this._heldTransition.forEach((part) => releaseStyle(part, "transition"));
|
||||
this._hiddenOpacity.clear();
|
||||
this._hiddenColor.clear();
|
||||
this._keptColor.clear();
|
||||
this._heldTransition.clear();
|
||||
}
|
||||
|
||||
/* Show the content again before the next paint, and note what to fade in */
|
||||
private _endLoading() {
|
||||
// Under a skeleton of its own, or before the first reading, the whole
|
||||
// content was hidden rather than its parts
|
||||
const wholeContent = this._customSkeleton || this._pieces === undefined;
|
||||
|
||||
this._arriving = {
|
||||
content: wholeContent
|
||||
? (this._contentSlot?.assignedElements() ?? [])
|
||||
: [],
|
||||
// Only what this overlay is the last to hide shows now; a part a
|
||||
// nested overlay still hides stays hidden, and fades in with that one
|
||||
opacityParts: [...this._hiddenOpacity].filter(
|
||||
(part) => holdersOf(part, "opacity") === 1
|
||||
),
|
||||
colorParts: [...this._hiddenColor].filter(
|
||||
(part) => holdersOf(part, "color") === 1
|
||||
),
|
||||
};
|
||||
|
||||
this._showParts();
|
||||
this._pieces = undefined;
|
||||
}
|
||||
|
||||
/* Fade each arriving part in, instantly with reduced motion */
|
||||
private _fadeIn({ content, opacityParts, colorParts }: ArrivingParts) {
|
||||
// In ms or s, as the token can be either; 150ms only when it isn't set
|
||||
const token = getComputedStyle(this)
|
||||
.getPropertyValue("--ha-animation-duration-fast")
|
||||
.trim();
|
||||
|
||||
const fade: KeyframeAnimationOptions = {
|
||||
duration: token ? parseAnimationDuration(token) : 150,
|
||||
easing: "ease-out",
|
||||
};
|
||||
|
||||
this._fades = [
|
||||
// To each part's own opacity, which isn't always 1
|
||||
...[...content, ...opacityParts].map((part) => {
|
||||
const opacity = getComputedStyle(part).opacity;
|
||||
|
||||
return part.animate([{ opacity: 0 }, { opacity }], fade);
|
||||
}),
|
||||
...colorParts.map((part) => {
|
||||
const color = getComputedStyle(part).color;
|
||||
|
||||
return part.animate([{ color: "transparent" }, { color }], fade);
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
private _cancelFades() {
|
||||
this._fades.forEach((fade) => fade.cancel());
|
||||
this._fades = [];
|
||||
}
|
||||
|
||||
static readonly styles: CSSResultGroup = css`
|
||||
:host {
|
||||
display: block;
|
||||
position: relative;
|
||||
}
|
||||
.content {
|
||||
display: contents;
|
||||
}
|
||||
slot.hidden::slotted(*) {
|
||||
opacity: 0;
|
||||
}
|
||||
.skeleton {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
border-radius: inherit;
|
||||
pointer-events: none;
|
||||
}
|
||||
/* Rounded by the layer it fills, which follows the host */
|
||||
.fill {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
--ha-skeleton-border-radius: 0;
|
||||
}
|
||||
.piece {
|
||||
position: absolute;
|
||||
min-height: 0;
|
||||
}
|
||||
.piece.round {
|
||||
--ha-skeleton-border-radius: var(--ha-border-radius-circle);
|
||||
}
|
||||
.piece.shape {
|
||||
--ha-skeleton-border-radius: 0;
|
||||
mask-size: 100% 100%;
|
||||
-webkit-mask-size: 100% 100%;
|
||||
mask-repeat: no-repeat;
|
||||
-webkit-mask-repeat: no-repeat;
|
||||
}
|
||||
/* Text and icons on a dark bar over a picture */
|
||||
.piece.on-dark {
|
||||
--ha-skeleton-color: rgba(255, 255, 255, 0.3);
|
||||
--ha-skeleton-sheen-color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
const pieceStyle = ({ maskBox, ...piece }: SkeletonPiece) => {
|
||||
const maskPosition = maskBox ? `${maskBox.x}px ${maskBox.y}px` : undefined;
|
||||
|
||||
const maskSize = maskBox
|
||||
? `${maskBox.width}px ${maskBox.height}px`
|
||||
: undefined;
|
||||
|
||||
return styleMap({
|
||||
left: `${piece.x}px`,
|
||||
top: `${piece.y}px`,
|
||||
width: `${piece.width}px`,
|
||||
height: `${piece.height}px`,
|
||||
"--ha-skeleton-border-radius": piece.radius,
|
||||
"border-radius": piece.kind === "scrim" ? piece.radius : undefined,
|
||||
"background-color": piece.background,
|
||||
"mask-image": piece.mask,
|
||||
"-webkit-mask-image": piece.mask,
|
||||
"mask-position": maskPosition,
|
||||
"-webkit-mask-position": maskPosition,
|
||||
"mask-size": maskSize,
|
||||
"-webkit-mask-size": maskSize,
|
||||
});
|
||||
};
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-skeleton-overlay": HaSkeletonOverlay;
|
||||
}
|
||||
|
||||
interface HASSDomEvents {
|
||||
"skeleton-loading": SkeletonLoadingDetail;
|
||||
}
|
||||
|
||||
// for add event listener
|
||||
interface HTMLElementEventMap {
|
||||
"skeleton-loading": HASSDomEvent<HASSDomEvents["skeleton-loading"]>;
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,12 @@ import { customElement, property } from "lit/decorators";
|
||||
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import type { LogbookEntry } from "../../data/logbook";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import "./hat-logbook-note";
|
||||
import "../../panels/logbook/ha-logbook-renderer";
|
||||
import type { TraceExtended } from "../../data/trace";
|
||||
|
||||
@customElement("ha-trace-logbook")
|
||||
export class HaTraceLogbook extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ type: Boolean, reflect: true }) public narrow = false;
|
||||
|
||||
@property({ attribute: false }) public trace!: TraceExtended;
|
||||
@@ -26,7 +23,6 @@ export class HaTraceLogbook extends LitElement {
|
||||
return this.logbookEntries.length
|
||||
? html`
|
||||
<ha-logbook-renderer
|
||||
.hass=${this.hass}
|
||||
.entries=${this.logbookEntries}
|
||||
.narrow=${this.narrow}
|
||||
no-detail
|
||||
|
||||
@@ -566,7 +566,6 @@ export class HaTracePathDetails extends LitElement {
|
||||
return entries.length
|
||||
? html`
|
||||
<ha-logbook-renderer
|
||||
.hass=${this.hass}
|
||||
.entries=${entries}
|
||||
.narrow=${this.narrow}
|
||||
no-detail
|
||||
|
||||
+17
-7
@@ -4,7 +4,7 @@ import type { TimestampStateDomain } from "../common/const";
|
||||
import { computeDomain } from "../common/entity/compute_domain";
|
||||
import { computeStateDomain } from "../common/entity/compute_state_domain";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import type { HomeAssistant, HomeAssistantFormatters } from "../types";
|
||||
import { UNAVAILABLE, UNKNOWN } from "./entity/entity";
|
||||
import { isNumericEntity } from "./history";
|
||||
|
||||
@@ -316,24 +316,34 @@ const STATE_ACTION_MESSAGES: Record<
|
||||
|
||||
const RESTORABLE_BUTTON_DOMAINS = new Set(["button", "input_button"]);
|
||||
|
||||
export type LogbookStateFormatters = Pick<
|
||||
HomeAssistantFormatters,
|
||||
"formatEntityState" | "formatEntityAttributeValue"
|
||||
>;
|
||||
|
||||
export const localizeStateMessage = (
|
||||
hass: HomeAssistant,
|
||||
localize: LocalizeFunc,
|
||||
formatters: LogbookStateFormatters,
|
||||
state: string,
|
||||
stateObj: HassEntity,
|
||||
domain: string,
|
||||
entry?: LogbookEntry
|
||||
): string => {
|
||||
if (state === UNKNOWN || state === UNAVAILABLE) {
|
||||
return hass.formatEntityState(stateObj, state);
|
||||
return formatters.formatEntityState(stateObj, state);
|
||||
}
|
||||
// Events show the triggered event type, falling back to a generic label when
|
||||
// the type is unknown (the timestamp state is meaningless on its own).
|
||||
if (domain === "event") {
|
||||
const eventType = entry?.attributes?.event_type;
|
||||
if (eventType != null) {
|
||||
return hass.formatEntityAttributeValue(stateObj, "event_type", eventType);
|
||||
return formatters.formatEntityAttributeValue(
|
||||
stateObj,
|
||||
"event_type",
|
||||
eventType
|
||||
);
|
||||
}
|
||||
return hass.localize(`${LOGBOOK_LOCALIZE_PATH}.detected_event_no_type`);
|
||||
return localize(`${LOGBOOK_LOCALIZE_PATH}.detected_event_no_type`);
|
||||
}
|
||||
const actionKey: LogbookActionMessage | undefined =
|
||||
STATE_ACTION_MESSAGES[domain as keyof typeof STATE_ACTION_MESSAGES];
|
||||
@@ -346,11 +356,11 @@ export const localizeStateMessage = (
|
||||
actionKey &&
|
||||
(!RESTORABLE_BUTTON_DOMAINS.has(domain) || matchesEntryTime)
|
||||
) {
|
||||
return hass.localize(`${LOGBOOK_LOCALIZE_PATH}.${actionKey}`);
|
||||
return localize(`${LOGBOOK_LOCALIZE_PATH}.${actionKey}`);
|
||||
}
|
||||
// Every other domain reuses the backend state translation, so the logbook
|
||||
// speaks the same vocabulary as the rest of the UI.
|
||||
return hass.formatEntityState(stateObj, state);
|
||||
return formatters.formatEntityState(stateObj, state);
|
||||
};
|
||||
|
||||
export const filterLogbookCompatibleEntities = (entity) => {
|
||||
|
||||
@@ -520,7 +520,7 @@ interface SelectBoxOptionImage {
|
||||
|
||||
export interface SelectOption {
|
||||
value: string;
|
||||
label: string;
|
||||
label?: string;
|
||||
description?: string;
|
||||
image?: string | SelectBoxOptionImage;
|
||||
disabled?: boolean;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { Connection } from "home-assistant-js-websocket";
|
||||
import type { Connection, UnsubscribeFunc } from "home-assistant-js-websocket";
|
||||
import { getCollection } from "home-assistant-js-websocket";
|
||||
import type { Store } from "home-assistant-js-websocket/dist/store";
|
||||
import type { HassioAddonsInfo } from "../hassio/addon";
|
||||
import type { CallWS } from "../../types";
|
||||
import type { HassioAddonDetails, HassioAddonsInfo } from "../hassio/addon";
|
||||
import type { HassioHassOSInfo, HassioHostInfo } from "../hassio/host";
|
||||
import type { NetworkInfo } from "../hassio/network";
|
||||
import type { HassioResolution } from "../hassio/resolution";
|
||||
@@ -112,6 +113,139 @@ const subscribeSupervisorEventUpdates = (
|
||||
}
|
||||
);
|
||||
|
||||
const subscribeSupervisorEvents = (
|
||||
conn: Connection,
|
||||
onEvent: (event: SupervisorEvent) => void
|
||||
) =>
|
||||
conn.subscribeMessage<SupervisorEvent>(onEvent, {
|
||||
type: "supervisor/subscribe",
|
||||
});
|
||||
|
||||
export type SupervisorAppEvent =
|
||||
// A store reload can change the latest version of any app
|
||||
| { type: "store" }
|
||||
| { type: "app"; slug: string; update: Partial<HassioAddonDetails> }
|
||||
| {
|
||||
type: "job";
|
||||
slug: string;
|
||||
// install, uninstall, update, rebuild or restore
|
||||
operation: string;
|
||||
done: boolean;
|
||||
};
|
||||
|
||||
interface SupervisorJob {
|
||||
name: string;
|
||||
reference: string | null;
|
||||
done: boolean;
|
||||
child_jobs: SupervisorJob[];
|
||||
}
|
||||
|
||||
// Settings in the v2 "app" status that the app info also has
|
||||
const APP_SETTINGS_KEYS = [
|
||||
"version_latest",
|
||||
"update_available",
|
||||
"boot",
|
||||
"watchdog",
|
||||
"ingress_panel",
|
||||
"protected",
|
||||
"auto_update",
|
||||
] as const;
|
||||
|
||||
// Older Supervisors name the app manager jobs addon_manager_*
|
||||
const appManagerOperation = (jobName: string | undefined) =>
|
||||
/^(?:addon|app)_manager_(\w+)$/.exec(jobName ?? "")?.[1];
|
||||
|
||||
/**
|
||||
* Parse a Supervisor event that changes the info of an app.
|
||||
*/
|
||||
export const parseSupervisorAppEvent = (
|
||||
event: SupervisorEvent
|
||||
): SupervisorAppEvent | undefined => {
|
||||
// Supervisor sends "addon" with only the state, or with its v2 websocket API
|
||||
// enabled "app" with the full status
|
||||
if (event.event === "addon" || event.event === "app") {
|
||||
const update: Partial<HassioAddonDetails> = {
|
||||
// The app info never reports "stopping"; the app runs until it stops
|
||||
...(event.state !== "stopping" && { state: event.state }),
|
||||
// The version is null while the app is not installed
|
||||
...(event.event === "app" && { version: event.version }),
|
||||
// The status has no settings while the app is not installed
|
||||
...(event.version &&
|
||||
Object.fromEntries(APP_SETTINGS_KEYS.map((key) => [key, event[key]]))),
|
||||
};
|
||||
return { type: "app", slug: event.slug, update };
|
||||
}
|
||||
if (event.event === "store_reloaded") {
|
||||
return { type: "store" };
|
||||
}
|
||||
const job = event.event === "job" ? event.data : undefined;
|
||||
// Only manager jobs count: their child jobs share the slug, and start, stop
|
||||
// and restart jobs change nothing beyond the state events. A manager job can
|
||||
// itself be a child, for example of a backup restore.
|
||||
// The first event of a job comes before Supervisor sets its reference.
|
||||
if (!job?.reference) {
|
||||
return undefined;
|
||||
}
|
||||
const operation = appManagerOperation(job.name);
|
||||
if (!operation) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
type: "job",
|
||||
slug: job.reference,
|
||||
operation,
|
||||
done: job.done === true,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the app manager operations that run now, keyed by app slug.
|
||||
*/
|
||||
export const fetchAppOperations = async (
|
||||
callWS: CallWS
|
||||
): Promise<Record<string, string>> => {
|
||||
const { jobs } = await callWS<{ jobs: SupervisorJob[] }>({
|
||||
type: "supervisor/api",
|
||||
endpoint: "/jobs/info",
|
||||
method: "get",
|
||||
});
|
||||
const operations: Record<string, string> = {};
|
||||
const addOperations = (list: SupervisorJob[]) => {
|
||||
for (const job of list) {
|
||||
const operation = appManagerOperation(job.name);
|
||||
if (operation && job.reference && !job.done) {
|
||||
operations[job.reference] = operation;
|
||||
}
|
||||
addOperations(job.child_jobs ?? []);
|
||||
}
|
||||
};
|
||||
addOperations(jobs);
|
||||
return operations;
|
||||
};
|
||||
|
||||
/**
|
||||
* Subscribe to Supervisor events that change app info. Events sent while the
|
||||
* connection is down are lost, so `onReconnect` runs after each reconnect.
|
||||
*/
|
||||
export const subscribeSupervisorAppEvents = async (
|
||||
conn: Connection,
|
||||
onEvent: (appEvent: SupervisorAppEvent) => void,
|
||||
onReconnect: () => void
|
||||
): Promise<UnsubscribeFunc> => {
|
||||
const unsub = await subscribeSupervisorEvents(conn, (event) => {
|
||||
const appEvent = parseSupervisorAppEvent(event);
|
||||
if (appEvent) {
|
||||
onEvent(appEvent);
|
||||
}
|
||||
});
|
||||
const handleReady = () => onReconnect();
|
||||
conn.addEventListener("ready", handleReady);
|
||||
return () => {
|
||||
conn.removeEventListener("ready", handleReady);
|
||||
unsub();
|
||||
};
|
||||
};
|
||||
|
||||
export const getSupervisorEventCollection = (
|
||||
conn: Connection,
|
||||
key: string,
|
||||
|
||||
@@ -104,6 +104,10 @@ export const DOMAINS_HIDE_DEFAULT_MORE_INFO = [
|
||||
/** Domains that should have the history hidden in the more info dialog. */
|
||||
export const DOMAINS_MORE_INFO_NO_HISTORY = ["camera", "configurator"];
|
||||
|
||||
/** Whether the info view explains why the entity isn't available instead of showing it. */
|
||||
export const computeShowUnavailableInfo = (stateObj?: HassEntity) =>
|
||||
!stateObj || Boolean(stateObj.attributes.restored);
|
||||
|
||||
export const computeShowHistoryComponent = (
|
||||
hass: HomeAssistant,
|
||||
entityId: string
|
||||
|
||||
@@ -87,6 +87,7 @@ import { showConfirmationDialog } from "../generic/show-dialog-box";
|
||||
import {
|
||||
computeShowHistoryComponent,
|
||||
computeShowLogBookComponent,
|
||||
computeShowUnavailableInfo,
|
||||
DOMAINS_WITH_MORE_INFO,
|
||||
EDITABLE_DOMAINS_WITH_ID,
|
||||
EDITABLE_DOMAINS_WITH_UNIQUE_ID,
|
||||
@@ -188,6 +189,8 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
|
||||
@state() private _entry?: ExtEntityRegistryEntry | null;
|
||||
|
||||
private _entryLoadFailed = false;
|
||||
|
||||
@state() private _infoEditMode = false;
|
||||
|
||||
@state() private _detailsYamlMode = false;
|
||||
@@ -223,16 +226,26 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
}
|
||||
|
||||
private async _loadEntityRegistryEntry() {
|
||||
if (!this._entityId) {
|
||||
const entityId = this._entityId;
|
||||
if (!entityId) {
|
||||
return;
|
||||
}
|
||||
if (this._entry?.entity_id !== entityId) {
|
||||
this._entry = undefined;
|
||||
}
|
||||
let entry: ExtEntityRegistryEntry | null | undefined;
|
||||
let failed = false;
|
||||
try {
|
||||
this._entry = await getExtendedEntityRegistryEntry(
|
||||
this.hass.callWS,
|
||||
this._entityId
|
||||
);
|
||||
} catch (_e) {
|
||||
this._entry = null;
|
||||
entry = await getExtendedEntityRegistryEntry(this.hass.callWS, entityId);
|
||||
} catch (err: any) {
|
||||
// Other errors, like a lost connection, don't tell whether it's
|
||||
// registered, so it loads again on reconnect
|
||||
failed = err?.code !== "not_found";
|
||||
entry = failed ? undefined : null;
|
||||
}
|
||||
if (this._entityId === entityId) {
|
||||
this._entry = entry;
|
||||
this._entryLoadFailed = failed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,6 +270,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
this._entityId = undefined;
|
||||
this._parentEntityIds = [];
|
||||
this._entry = undefined;
|
||||
this._entryLoadFailed = false;
|
||||
this._infoEditMode = false;
|
||||
this._detailsYamlMode = false;
|
||||
this._initialView = DEFAULT_VIEW;
|
||||
@@ -291,7 +305,8 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
|
||||
private _shouldShowHistory(domain: string): boolean {
|
||||
return (
|
||||
DOMAINS_WITH_MORE_INFO.includes(domain) &&
|
||||
(DOMAINS_WITH_MORE_INFO.includes(domain) ||
|
||||
computeShowUnavailableInfo(this.hass.states[this._entityId!])) &&
|
||||
(computeShowHistoryComponent(this.hass, this._entityId!) ||
|
||||
computeShowLogBookComponent(this.hass, this._entityId!))
|
||||
);
|
||||
@@ -1108,6 +1123,14 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
this._mediaNaturalWidth = undefined;
|
||||
this._cameraControlsHeight = undefined;
|
||||
}
|
||||
if (
|
||||
this._entryLoadFailed &&
|
||||
changedProps.has("hass") &&
|
||||
this.hass.connected &&
|
||||
!(changedProps.get("hass") as HomeAssistant | undefined)?.connected
|
||||
) {
|
||||
this._loadEntityRegistryEntry();
|
||||
}
|
||||
}
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { computeDomain } from "../../common/entity/compute_domain";
|
||||
import type { ExtEntityRegistryEntry } from "../../data/entity/entity_registry";
|
||||
@@ -8,12 +8,14 @@ import {
|
||||
computeShowHistoryComponent,
|
||||
computeShowLogBookComponent,
|
||||
computeShowNewMoreInfo,
|
||||
computeShowUnavailableInfo,
|
||||
DOMAINS_FULL_HEIGHT_MORE_INFO,
|
||||
DOMAINS_NO_INFO,
|
||||
DOMAINS_WITH_MORE_INFO,
|
||||
} from "./const";
|
||||
import "./ha-more-info-history";
|
||||
import "./ha-more-info-logbook";
|
||||
import "./ha-more-info-unavailable";
|
||||
import "./more-info-content";
|
||||
|
||||
@customElement("ha-more-info-info")
|
||||
@@ -31,41 +33,21 @@ export class MoreInfoInfo extends LitElement {
|
||||
protected render() {
|
||||
const entityId = this.entityId;
|
||||
const stateObj = this.hass.states[entityId] as HassEntity | undefined;
|
||||
const entityRegObj = this.hass.entities[entityId];
|
||||
|
||||
if (!stateObj || computeShowUnavailableInfo(stateObj)) {
|
||||
return html`<ha-more-info-unavailable
|
||||
.entry=${this.entry}
|
||||
.stateObj=${stateObj}
|
||||
></ha-more-info-unavailable>`;
|
||||
}
|
||||
|
||||
const domain = computeDomain(entityId);
|
||||
const isNewMoreInfo = stateObj && computeShowNewMoreInfo(stateObj);
|
||||
const isNewMoreInfo = computeShowNewMoreInfo(stateObj);
|
||||
const isFullHeight =
|
||||
isNewMoreInfo || DOMAINS_FULL_HEIGHT_MORE_INFO.includes(domain);
|
||||
|
||||
return html`
|
||||
<div class="container" data-domain=${domain}>
|
||||
${
|
||||
!stateObj
|
||||
? html`<ha-alert alert-type="warning">
|
||||
${
|
||||
this.entry?.disabled_by
|
||||
? this.hass.localize(
|
||||
"ui.dialogs.entity_registry.editor.entity_disabled"
|
||||
)
|
||||
: this.hass.localize(
|
||||
"ui.dialogs.entity_registry.editor.unavailable"
|
||||
)
|
||||
}
|
||||
</ha-alert>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
stateObj?.attributes.restored && entityRegObj
|
||||
? html`<ha-alert alert-type="warning">
|
||||
${this.hass.localize(
|
||||
"ui.dialogs.more_info_control.restored.no_longer_provided",
|
||||
{
|
||||
integration: entityRegObj.platform,
|
||||
}
|
||||
)}
|
||||
</ha-alert>`
|
||||
: nothing
|
||||
}
|
||||
<div class="content">
|
||||
${
|
||||
DOMAINS_NO_INFO.includes(domain) || isNewMoreInfo
|
||||
@@ -153,10 +135,6 @@ export class MoreInfoInfo extends LitElement {
|
||||
ha-more-info-logbook {
|
||||
margin-inline: calc(var(--ha-space-6) * -1);
|
||||
}
|
||||
|
||||
ha-alert {
|
||||
display: block;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
import {
|
||||
mdiCancel,
|
||||
mdiHelpCircleOutline,
|
||||
mdiPowerPlugOffOutline,
|
||||
} from "@mdi/js";
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import "@home-assistant/components/card";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import { transform } from "../../common/decorators/transform";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { navigate } from "../../common/navigate";
|
||||
import {
|
||||
adaptiveDialogModeContext,
|
||||
type DialogSheetMode,
|
||||
} from "../../components/ha-adaptive-dialog";
|
||||
import "../../components/ha-alert";
|
||||
import "../../components/ha-button";
|
||||
import "../../components/ha-empty-state";
|
||||
import "../../components/ha-relative-time";
|
||||
import type { ConfigEntry } from "../../data/config_entries";
|
||||
import { ERROR_STATES } from "../../data/config_entries";
|
||||
import {
|
||||
apiContext,
|
||||
configContext,
|
||||
configEntriesContext,
|
||||
formattersContext,
|
||||
internationalizationContext,
|
||||
} from "../../data/context";
|
||||
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
|
||||
import type { HistoryStates } from "../../data/history";
|
||||
import type { ExtEntityRegistryEntry } from "../../data/entity/entity_registry";
|
||||
import { updateEntityRegistryEntry } from "../../data/entity/entity_registry";
|
||||
import { domainToName } from "../../data/integration";
|
||||
import { renderConfigEntryError } from "../../panels/config/integrations/render-config-entry-error";
|
||||
import { showAlertDialog } from "../generic/show-dialog-box";
|
||||
|
||||
/**
|
||||
* @element ha-more-info-unavailable
|
||||
* @summary Info view of an entity that has no state or that its integration
|
||||
* doesn't provide, with the reason and how to make it available again.
|
||||
*/
|
||||
@customElement("ha-more-info-unavailable")
|
||||
export class HaMoreInfoUnavailable extends LitElement {
|
||||
/** `undefined` while the entry loads, `null` when the entity isn't registered. */
|
||||
@property({ attribute: false }) public entry?: ExtEntityRegistryEntry | null;
|
||||
|
||||
/** The `restored` state core keeps while the integration doesn't provide the entity. */
|
||||
@property({ attribute: false }) public stateObj?: HassEntity;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: ContextType<typeof internationalizationContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<ContextType<typeof configContext>, boolean>({
|
||||
transformer: ({ user }) => Boolean(user?.is_admin),
|
||||
})
|
||||
private _isAdmin = false;
|
||||
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: ContextType<typeof apiContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
private _formatters!: ContextType<typeof formattersContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: configEntriesContext, subscribe: true })
|
||||
private _configEntries?: ConfigEntry[];
|
||||
|
||||
/** `null` when the history has no state from before. */
|
||||
@state() private _lastKnown?: { state: string; until: Date } | null;
|
||||
|
||||
@state()
|
||||
@consume({ context: adaptiveDialogModeContext, subscribe: true })
|
||||
private _dialogMode?: DialogSheetMode;
|
||||
|
||||
@state() private _enabling = false;
|
||||
|
||||
private _lastKnownRequest = 0;
|
||||
|
||||
@state() private _error?: string;
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>) {
|
||||
super.willUpdate(changedProps);
|
||||
const platform = this.entry?.platform;
|
||||
if (platform && changedProps.get("entry")?.platform !== platform) {
|
||||
// Only the titles of loaded integrations are fetched by default
|
||||
this._i18n.loadBackendTranslation("title", platform);
|
||||
}
|
||||
if (
|
||||
changedProps.has("stateObj") &&
|
||||
changedProps.get("stateObj")?.last_changed !== this.stateObj?.last_changed
|
||||
) {
|
||||
this._fetchLastKnown();
|
||||
}
|
||||
}
|
||||
|
||||
private async _fetchLastKnown() {
|
||||
this._lastKnown = undefined;
|
||||
const request = ++this._lastKnownRequest;
|
||||
const stateObj = this.stateObj;
|
||||
if (!stateObj) {
|
||||
return;
|
||||
}
|
||||
const end = new Date(stateObj.last_changed);
|
||||
// Short periods first, as a sensor can write thousands of states a day
|
||||
for (const days of [1, 7, 30]) {
|
||||
let history: HistoryStates;
|
||||
try {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
history = await this._api.callWS<HistoryStates>({
|
||||
type: "history/history_during_period",
|
||||
start_time: new Date(end.getTime() - days * 86400000).toISOString(),
|
||||
end_time: end.toISOString(),
|
||||
entity_ids: [stateObj.entity_id],
|
||||
minimal_response: true,
|
||||
no_attributes: true,
|
||||
});
|
||||
} catch (_err) {
|
||||
this._lastKnown = null;
|
||||
return;
|
||||
}
|
||||
if (request !== this._lastKnownRequest) {
|
||||
return;
|
||||
}
|
||||
const states = history[stateObj.entity_id] ?? [];
|
||||
for (let i = states.length - 1; i >= 0; i--) {
|
||||
if (states[i].s !== UNAVAILABLE && states[i].s !== UNKNOWN) {
|
||||
const next = states[i + 1];
|
||||
this._lastKnown = {
|
||||
state: states[i].s,
|
||||
until: next ? new Date((next.lc ?? next.lu) * 1000) : end,
|
||||
};
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
this._lastKnown = null;
|
||||
}
|
||||
|
||||
protected render() {
|
||||
return html`
|
||||
<div
|
||||
class=${classMap({
|
||||
container: true,
|
||||
"bottom-sheet": this._dialogMode === "bottom-sheet",
|
||||
})}
|
||||
>
|
||||
${this._renderContent()}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderContent() {
|
||||
if (this.entry === undefined) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const localize = this._i18n.localize;
|
||||
|
||||
if (this.entry === null) {
|
||||
return html`
|
||||
<ha-empty-state
|
||||
.icon=${mdiHelpCircleOutline}
|
||||
.heading=${localize(
|
||||
"ui.dialogs.more_info_control.unavailable.not_found_title"
|
||||
)}
|
||||
.description=${localize(
|
||||
"ui.dialogs.more_info_control.unavailable.not_found"
|
||||
)}
|
||||
></ha-empty-state>
|
||||
`;
|
||||
}
|
||||
|
||||
const entry = this.entry;
|
||||
const integration = domainToName(localize, entry.platform);
|
||||
|
||||
if (!entry.disabled_by) {
|
||||
const configEntry = entry.config_entry_id
|
||||
? this._configEntries?.find(
|
||||
(item) => item.entry_id === entry.config_entry_id
|
||||
)
|
||||
: undefined;
|
||||
return html`
|
||||
<ha-empty-state
|
||||
.icon=${mdiPowerPlugOffOutline}
|
||||
.heading=${localize(
|
||||
"ui.dialogs.more_info_control.unavailable.not_provided_title"
|
||||
)}
|
||||
.description=${this._notProvidedDescription(integration, configEntry)}
|
||||
>
|
||||
${this._renderDetails(configEntry)}
|
||||
${this._isAdmin ? this._renderOpenIntegration() : nothing}
|
||||
</ha-empty-state>
|
||||
`;
|
||||
}
|
||||
|
||||
const canEnable =
|
||||
entry.disabled_by === "user" || entry.disabled_by === "integration";
|
||||
|
||||
return html`
|
||||
<ha-empty-state
|
||||
.icon=${mdiCancel}
|
||||
.heading=${localize(
|
||||
"ui.dialogs.more_info_control.unavailable.disabled_title"
|
||||
)}
|
||||
.description=${localize(
|
||||
`ui.dialogs.more_info_control.unavailable.disabled_by.${entry.disabled_by}`,
|
||||
{ integration }
|
||||
)}
|
||||
>
|
||||
${
|
||||
this._error
|
||||
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
!this._isAdmin
|
||||
? nothing
|
||||
: canEnable
|
||||
? html`
|
||||
<ha-button
|
||||
.loading=${this._enabling}
|
||||
.disabled=${this._enabling}
|
||||
@click=${this._enableEntry}
|
||||
>
|
||||
${localize(
|
||||
"ui.dialogs.more_info_control.unavailable.enable_entity"
|
||||
)}
|
||||
</ha-button>
|
||||
`
|
||||
: entry.disabled_by === "device" && entry.device_id
|
||||
? html`
|
||||
<ha-button appearance="plain" @click=${this._openDevice}>
|
||||
${localize(
|
||||
"ui.dialogs.more_info_control.unavailable.open_device"
|
||||
)}
|
||||
</ha-button>
|
||||
`
|
||||
: this._renderOpenIntegration()
|
||||
}
|
||||
</ha-empty-state>
|
||||
`;
|
||||
}
|
||||
|
||||
private _notProvidedDescription(
|
||||
integration: string,
|
||||
configEntry?: ConfigEntry
|
||||
) {
|
||||
const localize = this._i18n.localize;
|
||||
const key = "ui.dialogs.more_info_control.unavailable.integration_state";
|
||||
switch (configEntry?.state) {
|
||||
case "setup_retry":
|
||||
return localize(`${key}.setup_retry`, { integration });
|
||||
case "setup_error":
|
||||
case "migration_error":
|
||||
return localize(`${key}.setup_error`, { integration });
|
||||
case "setup_in_progress":
|
||||
return localize(`${key}.setup_in_progress`, { integration });
|
||||
case "not_loaded":
|
||||
case "failed_unload":
|
||||
case "unload_in_progress":
|
||||
return localize(`${key}.not_loaded`, { integration });
|
||||
default:
|
||||
return localize(
|
||||
this.stateObj
|
||||
? `${key}.no_longer_provided`
|
||||
: "ui.dialogs.more_info_control.unavailable.not_provided",
|
||||
{ integration }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private _renderDetails(configEntry?: ConfigEntry) {
|
||||
const localize = this._i18n.localize;
|
||||
const key = "ui.dialogs.more_info_control.unavailable.details";
|
||||
const reason =
|
||||
this._isAdmin &&
|
||||
configEntry?.reason &&
|
||||
ERROR_STATES.includes(configEntry.state)
|
||||
? renderConfigEntryError(this._i18n, configEntry)
|
||||
: undefined;
|
||||
// Only the history tells since when, the restored state's last_changed is the last restart
|
||||
const lastKnown = this.stateObj ? this._lastKnown : undefined;
|
||||
if (!reason && !lastKnown) {
|
||||
return nothing;
|
||||
}
|
||||
return html`
|
||||
<hac-card>
|
||||
<dl>
|
||||
${
|
||||
reason
|
||||
? html`<div class="stacked">
|
||||
<dt>${localize(`${key}.reason`)}</dt>
|
||||
<dd>${reason}</dd>
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
lastKnown
|
||||
? html`<div>
|
||||
<dt>${localize(`${key}.unavailable_since`)}</dt>
|
||||
<dd>
|
||||
<ha-relative-time
|
||||
.datetime=${lastKnown.until}
|
||||
capitalize
|
||||
></ha-relative-time>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>${localize(`${key}.last_known_state`)}</dt>
|
||||
<dd>
|
||||
${this._formatters.formatEntityState(
|
||||
this.stateObj!,
|
||||
lastKnown.state
|
||||
)}
|
||||
</dd>
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
</dl>
|
||||
</hac-card>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderOpenIntegration() {
|
||||
return html`
|
||||
<ha-button appearance="plain" @click=${this._openIntegration}>
|
||||
${this._i18n.localize(
|
||||
"ui.dialogs.more_info_control.unavailable.open_integration"
|
||||
)}
|
||||
</ha-button>
|
||||
`;
|
||||
}
|
||||
|
||||
private _openIntegration() {
|
||||
navigate(`/config/integrations/integration/${this.entry!.platform}`);
|
||||
}
|
||||
|
||||
private _openDevice() {
|
||||
navigate(`/config/devices/device/${this.entry!.device_id}`);
|
||||
}
|
||||
|
||||
private async _enableEntry() {
|
||||
this._error = undefined;
|
||||
this._enabling = true;
|
||||
try {
|
||||
const result = await updateEntityRegistryEntry(
|
||||
this._api.callWS,
|
||||
this.entry!.entity_id,
|
||||
{ disabled_by: null }
|
||||
);
|
||||
fireEvent(this, "entity-entry-updated", result.entity_entry);
|
||||
if (result.require_restart) {
|
||||
showAlertDialog(this, {
|
||||
text: this._i18n.localize(
|
||||
"ui.dialogs.entity_registry.editor.enabled_restart_confirm"
|
||||
),
|
||||
});
|
||||
}
|
||||
if (result.reload_delay) {
|
||||
showAlertDialog(this, {
|
||||
text: this._i18n.localize(
|
||||
"ui.dialogs.entity_registry.editor.enabled_delay_confirm",
|
||||
{ delay: result.reload_delay }
|
||||
),
|
||||
});
|
||||
}
|
||||
} catch (err: any) {
|
||||
this._error = err.message;
|
||||
} finally {
|
||||
this._enabling = false;
|
||||
}
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.container {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 400px;
|
||||
}
|
||||
|
||||
/* The bottom sheet has a fixed height, which is lower on a phone in landscape */
|
||||
.container.bottom-sheet {
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
ha-empty-state {
|
||||
flex: 1;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
hac-card {
|
||||
width: 100%;
|
||||
--hac-card-content-padding: var(--ha-space-3) var(--ha-space-4);
|
||||
}
|
||||
|
||||
dl {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--ha-space-2);
|
||||
margin: 0;
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
dl > div {
|
||||
display: flex;
|
||||
gap: var(--ha-space-4);
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
dl > div.stacked {
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.stacked dd {
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
dt {
|
||||
flex: none;
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
|
||||
dd {
|
||||
margin: 0;
|
||||
text-align: end;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
ha-alert {
|
||||
display: block;
|
||||
text-align: start;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-more-info-unavailable": HaMoreInfoUnavailable;
|
||||
}
|
||||
}
|
||||
@@ -177,7 +177,7 @@ window.hassConnection.then(({ conn }) => {
|
||||
const noop = () => {
|
||||
// do nothing
|
||||
};
|
||||
subscribeEntities(conn, noop, { batchUpdates: true });
|
||||
subscribeEntities(conn, noop);
|
||||
subscribeEntityRegistryDisplay(conn, noop);
|
||||
subscribeDeviceRegistry(conn, noop);
|
||||
subscribeAreaRegistry(conn, noop);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { mdiOpenInNew } from "@mdi/js";
|
||||
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { fireEvent, type HASSDomEvent } from "../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
@@ -35,9 +35,13 @@ class OnboardingAnalytics extends LitElement {
|
||||
|
||||
private _retryTimeout?: number;
|
||||
|
||||
@query("h1", true) private _heading?: HTMLElement;
|
||||
|
||||
protected render(): TemplateResult {
|
||||
return html`
|
||||
<h1>${this._localize("ui.panel.page-onboarding.analytics.header")}</h1>
|
||||
<h1 tabindex="-1">
|
||||
${this._localize("ui.panel.page-onboarding.analytics.header")}
|
||||
</h1>
|
||||
<p>${this._localize("ui.panel.page-onboarding.analytics.intro")}</p>
|
||||
<p>
|
||||
<a
|
||||
@@ -79,8 +83,9 @@ class OnboardingAnalytics extends LitElement {
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProps);
|
||||
this._heading?.focus();
|
||||
this.addEventListener("keypress", (ev) => {
|
||||
if (ev.key === "Enter") {
|
||||
if (ev.key === "Enter" && ev.composedPath()[0] !== this._heading) {
|
||||
this._save(ev);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { isComponentLoaded } from "../common/config/is_component_loaded";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
@@ -43,6 +43,10 @@ class OnboardingIntegrations extends SubscribeMixin(LitElement) {
|
||||
|
||||
@state() private _discoveredDomainsReceived = false;
|
||||
|
||||
@state() private _entriesReceived = false;
|
||||
|
||||
@query("h1") private _heading?: HTMLElement;
|
||||
|
||||
public hassSubscribe(): (UnsubscribeFunc | Promise<UnsubscribeFunc>)[] {
|
||||
return [
|
||||
subscribeConfigFlowInProgress(this.hass, (messages) => {
|
||||
@@ -64,6 +68,7 @@ class OnboardingIntegrations extends SubscribeMixin(LitElement) {
|
||||
subscribeConfigEntries(
|
||||
this.hass,
|
||||
(messages) => {
|
||||
this._entriesReceived = true;
|
||||
let fullUpdate = false;
|
||||
const newEntries: ConfigEntry[] = [];
|
||||
const integrations = new Set<string>();
|
||||
@@ -104,7 +109,7 @@ class OnboardingIntegrations extends SubscribeMixin(LitElement) {
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this._discoveredDomainsReceived) {
|
||||
if (!this._discoveredDomainsReceived || !this._entriesReceived) {
|
||||
return nothing;
|
||||
}
|
||||
// Render discovered and existing entries together sorted by localized title.
|
||||
@@ -127,7 +132,7 @@ class OnboardingIntegrations extends SubscribeMixin(LitElement) {
|
||||
if (foundIntegrations === 0) {
|
||||
return html`
|
||||
<div class="all-set-icon">🎉</div>
|
||||
<h1>
|
||||
<h1 tabindex="-1">
|
||||
${this._localize("ui.panel.page-onboarding.integration.all_set")}
|
||||
</h1>
|
||||
<p>
|
||||
@@ -146,7 +151,9 @@ class OnboardingIntegrations extends SubscribeMixin(LitElement) {
|
||||
}
|
||||
|
||||
return html`
|
||||
<h1>${this._localize("ui.panel.page-onboarding.integration.header")}</h1>
|
||||
<h1 tabindex="-1">
|
||||
${this._localize("ui.panel.page-onboarding.integration.header")}
|
||||
</h1>
|
||||
<p>${this._localize("ui.panel.page-onboarding.integration.intro")}</p>
|
||||
<div class="badges">
|
||||
${domains.map(
|
||||
@@ -182,6 +189,18 @@ class OnboardingIntegrations extends SubscribeMixin(LitElement) {
|
||||
this._scanUSBDevices();
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues) {
|
||||
super.updated(changedProps);
|
||||
if (
|
||||
(changedProps.has("_discoveredDomainsReceived") ||
|
||||
changedProps.has("_entriesReceived")) &&
|
||||
this._discoveredDomainsReceived &&
|
||||
this._entriesReceived
|
||||
) {
|
||||
this._heading?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
private async _scanUSBDevices() {
|
||||
if (!isComponentLoaded(this.hass.config, "usb")) {
|
||||
return;
|
||||
|
||||
@@ -413,6 +413,7 @@ class OnboardingLocation extends LitElement {
|
||||
private _detectLocation() {
|
||||
if (window.isSecureContext && navigator.geolocation) {
|
||||
this._working = true;
|
||||
this._status = undefined;
|
||||
const options = {
|
||||
enableHighAccuracy: true,
|
||||
timeout: 5000,
|
||||
@@ -464,6 +465,7 @@ class OnboardingLocation extends LitElement {
|
||||
return;
|
||||
}
|
||||
this._working = true;
|
||||
this._status = undefined;
|
||||
try {
|
||||
const values = await detectCoreConfig(this.hass);
|
||||
|
||||
@@ -478,6 +480,9 @@ class OnboardingLocation extends LitElement {
|
||||
}
|
||||
);
|
||||
this._location = [Number(values.latitude), Number(values.longitude)];
|
||||
this._status = this._localize(
|
||||
"ui.panel.page-onboarding.core-config.location_detected"
|
||||
);
|
||||
}
|
||||
if (values.elevation) {
|
||||
this._elevation = String(values.elevation);
|
||||
|
||||
@@ -10,6 +10,9 @@ export const onBoardingStyles = css`
|
||||
line-height: var(--ha-line-height-condensed);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
h1:focus {
|
||||
outline: none;
|
||||
}
|
||||
ha-icon-button-arrow-prev {
|
||||
margin-left: -12px;
|
||||
display: block;
|
||||
|
||||
@@ -59,6 +59,7 @@ import "../../../../../components/ha-switch";
|
||||
import type { HaSwitch } from "../../../../../components/ha-switch";
|
||||
import "../../../../../components/item/ha-list-item-switch";
|
||||
import "../../../../../components/item/ha-row-item";
|
||||
import { ConnectionSubscriptionController } from "../../../../../data/connection-subscription-controller";
|
||||
import {
|
||||
apiContext,
|
||||
internationalizationContext,
|
||||
@@ -90,6 +91,8 @@ import {
|
||||
supervisorUrl,
|
||||
} from "../../../../../data/hassio/common";
|
||||
import type { StoreAddonDetails } from "../../../../../data/supervisor/store";
|
||||
import type { SupervisorAppEvent } from "../../../../../data/supervisor/supervisor";
|
||||
import { subscribeSupervisorAppEvents } from "../../../../../data/supervisor/supervisor";
|
||||
import {
|
||||
showAlertDialog,
|
||||
showConfirmationDialog,
|
||||
@@ -127,8 +130,6 @@ const RATING_ICON = {
|
||||
|
||||
const MAX_RATING = 8;
|
||||
|
||||
const POLL_INTERVAL_SECONDS = 5;
|
||||
|
||||
@customElement("supervisor-app-info")
|
||||
class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
@property({ type: Boolean }) public narrow = false;
|
||||
@@ -168,7 +169,13 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
})
|
||||
private _updateState?: HassEntity;
|
||||
|
||||
private _pollInterval?: number;
|
||||
// Supervisor sends an event each time a field of its events changes, so
|
||||
// the fields from the last events are never older than those of a response
|
||||
private _eventUpdate: Partial<HassioAddonDetails> = {};
|
||||
|
||||
private _refreshes = 0;
|
||||
|
||||
private _subscribed = false;
|
||||
|
||||
protected mobileSizeQuery =
|
||||
"all and (max-width: 1120px), all and (max-height: 500px)";
|
||||
@@ -177,13 +184,44 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
return this._addon || this.addon;
|
||||
}
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this._startPolling();
|
||||
constructor() {
|
||||
super();
|
||||
new ConnectionSubscriptionController(this, {
|
||||
subscribe: async (connection) => {
|
||||
const unsub = await subscribeSupervisorAppEvents(
|
||||
connection,
|
||||
(appEvent) => {
|
||||
if (
|
||||
appEvent.type === "store" ||
|
||||
appEvent.slug === this._currentAddon.slug
|
||||
) {
|
||||
this._handleAppEvent(appEvent);
|
||||
}
|
||||
},
|
||||
() => this._reloadAfterMissedEvents()
|
||||
);
|
||||
// The parent loads the app for the first subscription. A later one
|
||||
// follows a detach from the page, which loses events.
|
||||
if (this._subscribed) {
|
||||
this._reloadAfterMissedEvents();
|
||||
}
|
||||
this._subscribed = true;
|
||||
return unsub;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>) {
|
||||
super.willUpdate(changedProps);
|
||||
// The parent reloads the app after each action
|
||||
if (changedProps.has("addon")) {
|
||||
if (changedProps.get("addon")?.slug !== this.addon.slug) {
|
||||
this._eventUpdate = {};
|
||||
}
|
||||
this._setAddon(this.addon);
|
||||
// A refresh that is still running can be older than the parent's data
|
||||
this._refreshes++;
|
||||
}
|
||||
// Registries load asynchronously and change over time; resolve the update
|
||||
// entity reactively instead of only once on connect.
|
||||
this._updateEntityId = this._findUpdateEntityId(
|
||||
@@ -193,11 +231,6 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
);
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._stopPolling();
|
||||
}
|
||||
|
||||
private _renderInfoCard() {
|
||||
const systemManaged = this._isSystemManaged(this._currentAddon);
|
||||
|
||||
@@ -1032,20 +1065,27 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
}
|
||||
}
|
||||
|
||||
private _startPolling() {
|
||||
if (this._pollInterval) {
|
||||
private _handleAppEvent(appEvent: SupervisorAppEvent) {
|
||||
if (appEvent.type === "app") {
|
||||
this._eventUpdate = { ...this._eventUpdate, ...appEvent.update };
|
||||
this._setAddon({
|
||||
...this._currentAddon,
|
||||
...appEvent.update,
|
||||
} as HassioAddonDetails);
|
||||
return;
|
||||
}
|
||||
this._pollInterval = window.setInterval(() => {
|
||||
if (appEvent.type === "store" || appEvent.done) {
|
||||
this._refreshAddonInfo();
|
||||
}, POLL_INTERVAL_SECONDS * 1000);
|
||||
}
|
||||
}
|
||||
|
||||
private _stopPolling() {
|
||||
if (this._pollInterval) {
|
||||
clearInterval(this._pollInterval);
|
||||
this._pollInterval = undefined;
|
||||
}
|
||||
private _setAddon(addon: HassioAddonDetails | StoreAddonDetails) {
|
||||
this._addon = { ...addon, ...this._eventUpdate } as HassioAddonDetails;
|
||||
}
|
||||
|
||||
private _reloadAfterMissedEvents() {
|
||||
this._eventUpdate = {};
|
||||
this._refreshAddonInfo();
|
||||
}
|
||||
|
||||
private async _refreshAddonInfo(): Promise<void> {
|
||||
@@ -1053,8 +1093,12 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
if (!addon?.slug) {
|
||||
return;
|
||||
}
|
||||
const refresh = ++this._refreshes;
|
||||
try {
|
||||
this._addon = await fetchHassioAddonInfo(this.api.callWS, addon.slug);
|
||||
const info = await fetchHassioAddonInfo(this.api.callWS, addon.slug);
|
||||
if (refresh === this._refreshes) {
|
||||
this._setAddon(info);
|
||||
}
|
||||
} catch (err: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error("Failed to fetch addon info", err);
|
||||
@@ -1321,7 +1365,6 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
});
|
||||
}
|
||||
button.progress = false;
|
||||
this._refreshAddonInfo();
|
||||
}
|
||||
|
||||
private async _stopClicked(ev: CustomEvent): Promise<void> {
|
||||
@@ -1350,7 +1393,6 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
});
|
||||
}
|
||||
button.progress = false;
|
||||
this._refreshAddonInfo();
|
||||
}
|
||||
|
||||
private async _restartClicked(ev: CustomEvent): Promise<void> {
|
||||
@@ -1379,7 +1421,6 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
});
|
||||
}
|
||||
button.progress = false;
|
||||
this._refreshAddonInfo();
|
||||
}
|
||||
|
||||
private async _rebuildClicked(ev: CustomEvent): Promise<void> {
|
||||
@@ -1399,7 +1440,6 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
});
|
||||
}
|
||||
button.progress = false;
|
||||
this._refreshAddonInfo();
|
||||
}
|
||||
|
||||
private async _startClicked(ev: CustomEvent): Promise<void> {
|
||||
@@ -1441,7 +1481,6 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
|
||||
try {
|
||||
await startHassioAddon(this.api.callWS, addon.slug);
|
||||
this._addon = await fetchHassioAddonInfo(this.api.callWS, addon.slug);
|
||||
const eventdata = {
|
||||
success: true,
|
||||
response: undefined,
|
||||
@@ -1461,7 +1500,6 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
}
|
||||
button.actionSuccess();
|
||||
button.progress = false;
|
||||
this._refreshAddonInfo();
|
||||
}
|
||||
|
||||
private _openConfiguration(): void {
|
||||
@@ -1534,7 +1572,6 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
|
||||
});
|
||||
} finally {
|
||||
this._uninstalling = false;
|
||||
this._refreshAddonInfo();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,8 @@ class SupervisorAppsCardContent extends LitElement {
|
||||
|
||||
@property() public state?: AddonState;
|
||||
|
||||
@property() public operation?: "install" | "uninstall";
|
||||
|
||||
@property({ type: Boolean }) public installed = false;
|
||||
|
||||
@property() public description?: string;
|
||||
@@ -97,6 +99,7 @@ class SupervisorAppsCardContent extends LitElement {
|
||||
this.state !== undefined
|
||||
? html`<supervisor-apps-state
|
||||
.state=${this.state || "unknown"}
|
||||
.operation=${this.operation}
|
||||
></supervisor-apps-state>`
|
||||
: this.installed
|
||||
? html`<div class="installed">
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { TemplateResult } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import "../../../../components/ha-spinner";
|
||||
import "../../../../components/ha-svg-icon";
|
||||
import { internationalizationContext } from "../../../../data/context";
|
||||
import type { AddonState } from "../../../../data/hassio/addon";
|
||||
@@ -12,11 +13,25 @@ import type { AddonState } from "../../../../data/hassio/addon";
|
||||
class SupervisorAppsState extends LitElement {
|
||||
@property() public state: Exclude<AddonState, null> = "unknown";
|
||||
|
||||
@property() public operation?: "install" | "uninstall";
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: ContextType<typeof internationalizationContext>;
|
||||
|
||||
protected render(): TemplateResult {
|
||||
if (this.operation) {
|
||||
return html`
|
||||
<ha-spinner size="tiny"></ha-spinner>
|
||||
<span
|
||||
>${this._i18n.localize(
|
||||
this.operation === "install"
|
||||
? "ui.panel.config.apps.state.installing"
|
||||
: "ui.panel.config.apps.state.uninstalling"
|
||||
)}</span
|
||||
>
|
||||
`;
|
||||
}
|
||||
return html`
|
||||
${
|
||||
this.state === "unknown"
|
||||
|
||||
@@ -76,11 +76,14 @@ class HaConfigAppDashboard extends LitElement {
|
||||
protected updated(changedProperties: PropertyValues<this>) {
|
||||
if (changedProperties.has("route") && this.route) {
|
||||
const oldRoute = changedProperties.get("route") as Route | undefined;
|
||||
const oldSlug = oldRoute?.path.split("/")[1];
|
||||
const newSlug = this.route.path.split("/")[1];
|
||||
const [, oldSlug, oldTab = "info"] = oldRoute?.path.split("/") ?? [];
|
||||
const [, newSlug, newTab = "info"] = this.route.path.split("/");
|
||||
|
||||
if (oldSlug !== newSlug && newSlug && !this._loading) {
|
||||
this._loadAddon();
|
||||
} else if (oldRoute && oldTab !== "info" && newTab === "info") {
|
||||
// The app can change while another tab shows
|
||||
this._loadAddon();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -236,8 +239,10 @@ class HaConfigAppDashboard extends LitElement {
|
||||
}
|
||||
|
||||
if (path === "uninstall") {
|
||||
// Navigate back to installed apps after uninstall
|
||||
goBack(this._fromStore ? "/config/apps/available" : "/config/apps");
|
||||
// The user can leave the page while the uninstall runs
|
||||
if (this.isConnected) {
|
||||
goBack(this._fromStore ? "/config/apps/available" : "/config/apps");
|
||||
}
|
||||
} else {
|
||||
// Reload app info
|
||||
await this._loadAddon();
|
||||
|
||||
@@ -18,11 +18,20 @@ import "../../../components/ha-card";
|
||||
import "../../../components/ha-icon-button";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import "../../../components/input/ha-input-search";
|
||||
import { ConnectionSubscriptionController } from "../../../data/connection-subscription-controller";
|
||||
import type {
|
||||
HassioAddonInfo,
|
||||
HassioAddonsInfo,
|
||||
} from "../../../data/hassio/addon";
|
||||
import { fetchHassioAddonsInfo } from "../../../data/hassio/addon";
|
||||
import {
|
||||
fetchHassioAddonInfo,
|
||||
fetchHassioAddonsInfo,
|
||||
} from "../../../data/hassio/addon";
|
||||
import type { SupervisorAppEvent } from "../../../data/supervisor/supervisor";
|
||||
import {
|
||||
fetchAppOperations,
|
||||
subscribeSupervisorAppEvents,
|
||||
} from "../../../data/supervisor/supervisor";
|
||||
import "../../../layouts/hass-error-screen";
|
||||
import "../../../layouts/hass-loading-screen";
|
||||
import "../../../layouts/hass-subpage";
|
||||
@@ -49,8 +58,30 @@ export class HaConfigAppsInstalled extends LitElement {
|
||||
|
||||
@state() private _checkingUpdates = false;
|
||||
|
||||
protected firstUpdated() {
|
||||
this._loadData();
|
||||
// Installs and uninstalls that run now, keyed by app slug
|
||||
@state() private _operations: Record<string, "install" | "uninstall"> = {};
|
||||
|
||||
private _queuedEvents?: SupervisorAppEvent[];
|
||||
|
||||
private _loads = 0;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
new ConnectionSubscriptionController(this, {
|
||||
subscribe: async (connection) => {
|
||||
try {
|
||||
return await subscribeSupervisorAppEvents(
|
||||
connection,
|
||||
(appEvent) => this._handleAppEvent(appEvent),
|
||||
() => this._loadData()
|
||||
);
|
||||
} finally {
|
||||
// Load after each subscription, also after a detach from the page
|
||||
// that lost events
|
||||
this._loadData();
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
protected render(): TemplateResult {
|
||||
@@ -136,6 +167,7 @@ export class HaConfigAppsInstalled extends LitElement {
|
||||
available
|
||||
.tags=${this._getAppTags(addon)}
|
||||
.state=${addon.state}
|
||||
.operation=${this._operations[addon.slug]}
|
||||
.icon=${
|
||||
addon.update_available
|
||||
? mdiArrowUpBoldCircle
|
||||
@@ -195,23 +227,114 @@ export class HaConfigAppsInstalled extends LitElement {
|
||||
}
|
||||
|
||||
private async _loadData(): Promise<void> {
|
||||
// A reconnect can start a load while another one runs; the newest wins
|
||||
const load = ++this._loads;
|
||||
// Events can arrive before or after the responses they changed, so hold
|
||||
// them until the list is in and apply them on top of it
|
||||
const queuedEvents: SupervisorAppEvent[] = [];
|
||||
this._queuedEvents = queuedEvents;
|
||||
let addonInfo: HassioAddonsInfo;
|
||||
let operations: Record<string, string>;
|
||||
try {
|
||||
this._addonInfo = await fetchHassioAddonsInfo(this.hass);
|
||||
[addonInfo, operations] = await Promise.all([
|
||||
fetchHassioAddonsInfo(this.hass),
|
||||
// Operations only decorate the list, so they must not fail the page
|
||||
fetchAppOperations(this.hass.callWS).catch(() => ({})),
|
||||
]);
|
||||
} catch (err: any) {
|
||||
this._error =
|
||||
err.message || this.hass.localize("ui.panel.config.apps.error_loading");
|
||||
if (load === this._loads) {
|
||||
this._queuedEvents = undefined;
|
||||
this._error =
|
||||
err.message ||
|
||||
this.hass.localize("ui.panel.config.apps.error_loading");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (load !== this._loads) {
|
||||
return;
|
||||
}
|
||||
this._queuedEvents = undefined;
|
||||
this._error = undefined;
|
||||
this._addonInfo = addonInfo;
|
||||
this._operations = {};
|
||||
for (const [slug, operation] of Object.entries(operations)) {
|
||||
this._handleAppEvent({
|
||||
type: "job",
|
||||
slug,
|
||||
operation,
|
||||
done: false,
|
||||
});
|
||||
}
|
||||
queuedEvents.forEach((appEvent) => this._handleAppEvent(appEvent));
|
||||
}
|
||||
|
||||
private _handleAppEvent(appEvent: SupervisorAppEvent) {
|
||||
if (this._queuedEvents) {
|
||||
this._queuedEvents.push(appEvent);
|
||||
return;
|
||||
}
|
||||
const addons = this._addonInfo?.addons;
|
||||
if (!addons) {
|
||||
return;
|
||||
}
|
||||
if (appEvent.type === "store") {
|
||||
this._loadData();
|
||||
return;
|
||||
}
|
||||
if (appEvent.type === "app") {
|
||||
this._addonInfo = {
|
||||
addons: addons.map((addon) =>
|
||||
addon.slug === appEvent.slug
|
||||
? { ...addon, ...appEvent.update }
|
||||
: addon
|
||||
),
|
||||
};
|
||||
return;
|
||||
}
|
||||
const { slug, operation } = appEvent;
|
||||
if (!appEvent.done) {
|
||||
if (
|
||||
(operation === "install" || operation === "uninstall") &&
|
||||
this._operations[slug] !== operation
|
||||
) {
|
||||
this._operations = { ...this._operations, [slug]: operation };
|
||||
if (operation === "install") {
|
||||
this._addInstallingApp(slug);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
const { [slug]: _done, ...operations } = this._operations;
|
||||
this._operations = operations;
|
||||
this._loadData();
|
||||
}
|
||||
|
||||
private async _addInstallingApp(slug: string): Promise<void> {
|
||||
if (this._addonInfo!.addons.some((addon) => addon.slug === slug)) {
|
||||
return;
|
||||
}
|
||||
let app: HassioAddonInfo;
|
||||
try {
|
||||
app = await fetchHassioAddonInfo(this.hass.callWS, slug);
|
||||
} catch (_err: any) {
|
||||
return;
|
||||
}
|
||||
// The install can finish while the fetch runs
|
||||
if (
|
||||
this._operations[slug] !== "install" ||
|
||||
this._addonInfo!.addons.some((addon) => addon.slug === slug)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this._addonInfo = { addons: [...this._addonInfo!.addons, app] };
|
||||
}
|
||||
|
||||
private async _handleCheckUpdates() {
|
||||
this._checkingUpdates = true;
|
||||
try {
|
||||
const info = await checkForAppUpdates(this, this.hass);
|
||||
if (info) {
|
||||
this._addonInfo = info;
|
||||
} else {
|
||||
this._loadData();
|
||||
}
|
||||
await checkForAppUpdates(this, this.hass);
|
||||
// A full load keeps the cards of apps that are still installing
|
||||
this._loadData();
|
||||
} finally {
|
||||
this._checkingUpdates = false;
|
||||
}
|
||||
|
||||
@@ -270,17 +270,13 @@ export class HaTriggerCondition extends LitElement {
|
||||
ha-list-selectable {
|
||||
--ha-list-gap: var(--ha-space-2);
|
||||
--ha-list-padding: 0;
|
||||
}
|
||||
ha-list-item-option {
|
||||
--ha-list-item-padding: var(--ha-space-1) var(--ha-space-2);
|
||||
margin-inline: calc(var(--ha-space-4) * -1);
|
||||
}
|
||||
.trigger-row-leading {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-2);
|
||||
}
|
||||
ha-trigger-icon {
|
||||
--mdc-icon-size: 20px;
|
||||
color: var(--ha-color-on-neutral-quiet);
|
||||
}
|
||||
.missing-trigger-badge {
|
||||
|
||||
@@ -392,7 +392,6 @@ export class HaAutomationTrace extends LitElement {
|
||||
: this._view === "logbook"
|
||||
? html`
|
||||
<ha-trace-logbook
|
||||
.hass=${this.hass}
|
||||
.narrow=${this.narrow}
|
||||
.trace=${this._trace}
|
||||
.logbookEntries=${this._logbookEntries}
|
||||
|
||||
@@ -68,7 +68,6 @@ export const rowStyles = css`
|
||||
.trigger-leading {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-2);
|
||||
}
|
||||
|
||||
.trigger-leading {
|
||||
@@ -77,7 +76,6 @@ export const rowStyles = css`
|
||||
|
||||
.trigger-leading ha-trigger-icon,
|
||||
.trigger-leading ha-svg-icon {
|
||||
--mdc-icon-size: 20px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@@ -87,6 +85,7 @@ export const rowStyles = css`
|
||||
align-items: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
margin-inline-end: var(--ha-space-2);
|
||||
border: 2px dotted var(--ha-color-border-neutral-normal);
|
||||
border-radius: var(--ha-border-radius-circle);
|
||||
box-sizing: border-box;
|
||||
|
||||
@@ -134,7 +134,7 @@ import {
|
||||
getLabelsTableColumn,
|
||||
} from "../common/data-table-columns";
|
||||
import { configSections } from "../config-sections";
|
||||
import { renderConfigEntryError } from "../integrations/ha-config-integration-page";
|
||||
import { renderConfigEntryError } from "../integrations/render-config-entry-error";
|
||||
import "../integrations/ha-integration-overflow-menu";
|
||||
import { showLabelDetailDialog } from "../labels/show-dialog-label-detail";
|
||||
import {
|
||||
|
||||
@@ -46,7 +46,7 @@ import type { LoggedError } from "../../../data/system_log";
|
||||
import { fetchSystemLog } from "../../../data/system_log";
|
||||
import { DialogMixin } from "../../../dialogs/dialog-mixin";
|
||||
import { haStyleDialog } from "../../../resources/styles";
|
||||
import { renderConfigEntryError } from "./ha-config-integration-page";
|
||||
import { renderConfigEntryError } from "./render-config-entry-error";
|
||||
import type { ConfigEntryHealthDialogParams } from "./show-dialog-config-entry-health";
|
||||
|
||||
const STATUS_ICONS: Record<HealthStatus, string> = {
|
||||
|
||||
@@ -75,11 +75,9 @@ import {
|
||||
showPromptDialog,
|
||||
} from "../../lovelace/custom-card-helpers";
|
||||
import "./ha-config-entry-device-row";
|
||||
import {
|
||||
renderConfigEntryError,
|
||||
type ConfigEntryData,
|
||||
} from "./ha-config-integration-page";
|
||||
import type { ConfigEntryData } from "./ha-config-integration-page";
|
||||
import "./ha-config-sub-entry-row";
|
||||
import { renderConfigEntryError } from "./render-config-entry-error";
|
||||
import { offerMarketplaceUninstall } from "./offer-marketplace-uninstall";
|
||||
|
||||
@customElement("ha-config-entry-row")
|
||||
|
||||
@@ -13,10 +13,9 @@ import {
|
||||
mdiWeb,
|
||||
} from "@mdi/js";
|
||||
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
|
||||
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property, queryAll, state } from "lit/decorators";
|
||||
import { until } from "lit/directives/until";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { ensureArray } from "../../../common/array/ensure-array";
|
||||
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
|
||||
@@ -116,46 +115,6 @@ export interface ConfigEntryData {
|
||||
// The AI settings show how to connect to the MCP server and its APIs.
|
||||
const AI_SETTINGS_DOMAINS = ["mcp", "mcp_server"];
|
||||
|
||||
export const renderConfigEntryError = (
|
||||
hass: Pick<HomeAssistant, "localize" | "loadBackendTranslation">,
|
||||
entry: ConfigEntry
|
||||
): TemplateResult => {
|
||||
if (entry.reason) {
|
||||
if (entry.error_reason_translation_key) {
|
||||
// The error may be translated by another integration, e.g. one raised by
|
||||
// a shared helper and owned by the homeassistant integration.
|
||||
const translationDomain =
|
||||
entry.error_reason_translation_domain || entry.domain;
|
||||
const lokalisePromExc = hass
|
||||
.loadBackendTranslation("exceptions", translationDomain)
|
||||
.then(
|
||||
(localize) =>
|
||||
localize(
|
||||
`component.${translationDomain}.exceptions.${entry.error_reason_translation_key}.message`,
|
||||
entry.error_reason_translation_placeholders ?? undefined
|
||||
) || entry.reason
|
||||
);
|
||||
return html`${until(lokalisePromExc)}`;
|
||||
}
|
||||
const lokalisePromError = hass
|
||||
.loadBackendTranslation("config", entry.domain)
|
||||
.then(
|
||||
(localize) =>
|
||||
localize(`component.${entry.domain}.config.error.${entry.reason}`) ||
|
||||
entry.reason
|
||||
);
|
||||
return html`${until(lokalisePromError, entry.reason)}`;
|
||||
}
|
||||
return html`
|
||||
<br />
|
||||
<a href=${`/config/logs?search=${encodeURIComponent(entry.domain)}`}>
|
||||
${hass.localize(
|
||||
"ui.panel.config.integrations.config_entry.check_the_logs"
|
||||
)}
|
||||
</a>
|
||||
`;
|
||||
};
|
||||
|
||||
@customElement("ha-config-integration-page")
|
||||
class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@@ -55,7 +55,7 @@ import { haStyle } from "../../../../../resources/styles";
|
||||
import type { HomeAssistant, Route } from "../../../../../types";
|
||||
import { brandsUrl } from "../../../../../util/brands-url";
|
||||
import { fileDownload } from "../../../../../util/file_download";
|
||||
import { renderConfigEntryError } from "../../ha-config-integration-page";
|
||||
import { renderConfigEntryError } from "../../render-config-entry-error";
|
||||
import {
|
||||
attentionCount,
|
||||
devicesWithEntities,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { TemplateResult } from "lit";
|
||||
import { html } from "lit";
|
||||
import { until } from "lit/directives/until";
|
||||
import type { ConfigEntry } from "../../../data/config_entries";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
|
||||
export const renderConfigEntryError = (
|
||||
hass: Pick<HomeAssistant, "localize" | "loadBackendTranslation">,
|
||||
entry: ConfigEntry
|
||||
): TemplateResult => {
|
||||
if (entry.reason) {
|
||||
if (entry.error_reason_translation_key) {
|
||||
// The error may be translated by another integration, e.g. one raised by
|
||||
// a shared helper and owned by the homeassistant integration.
|
||||
const translationDomain =
|
||||
entry.error_reason_translation_domain || entry.domain;
|
||||
const lokalisePromExc = hass
|
||||
.loadBackendTranslation("exceptions", translationDomain)
|
||||
.then(
|
||||
(localize) =>
|
||||
localize(
|
||||
`component.${translationDomain}.exceptions.${entry.error_reason_translation_key}.message`,
|
||||
entry.error_reason_translation_placeholders ?? undefined
|
||||
) || entry.reason
|
||||
);
|
||||
return html`${until(lokalisePromExc)}`;
|
||||
}
|
||||
const lokalisePromError = hass
|
||||
.loadBackendTranslation("config", entry.domain)
|
||||
.then(
|
||||
(localize) =>
|
||||
localize(`component.${entry.domain}.config.error.${entry.reason}`) ||
|
||||
entry.reason
|
||||
);
|
||||
return html`${until(lokalisePromError, entry.reason)}`;
|
||||
}
|
||||
return html`
|
||||
<br />
|
||||
<a href=${`/config/logs?search=${encodeURIComponent(entry.domain)}`}>
|
||||
${hass.localize(
|
||||
"ui.panel.config.integrations.config_entry.check_the_logs"
|
||||
)}
|
||||
</a>
|
||||
`;
|
||||
};
|
||||
@@ -360,7 +360,6 @@ export class HaScriptTrace extends LitElement {
|
||||
: this._view === "logbook"
|
||||
? html`
|
||||
<ha-trace-logbook
|
||||
.hass=${this.hass}
|
||||
.narrow=${this.narrow}
|
||||
.trace=${this._trace}
|
||||
.logbookEntries=${this._logbookEntries}
|
||||
|
||||
@@ -108,7 +108,7 @@ class HaPanelToolsActionHistory extends LitElement {
|
||||
userIdToName: Record<string, string>,
|
||||
systemUserIds: Set<string>,
|
||||
services: HomeAssistant["services"],
|
||||
_entities: HomeAssistant["entities"],
|
||||
entities: HomeAssistant["entities"],
|
||||
devices: HomeAssistant["devices"],
|
||||
areas: HomeAssistant["areas"],
|
||||
floors: HomeAssistant["floors"]
|
||||
@@ -118,7 +118,13 @@ class HaPanelToolsActionHistory extends LitElement {
|
||||
const user = computeUserCause(call, userIdToName, systemUserIds);
|
||||
// Names come from the registries, which are inputs. The states are
|
||||
// not, so the rows are not rebuilt on every state change.
|
||||
const cause = computeContextCause(this.hass, call) ?? user;
|
||||
const cause =
|
||||
computeContextCause(
|
||||
this.hass.states,
|
||||
{ entities, devices, areas, floors },
|
||||
localize,
|
||||
call
|
||||
) ?? user;
|
||||
const data = call.service_data;
|
||||
return {
|
||||
id: String(index),
|
||||
|
||||
@@ -7,6 +7,7 @@ import memoizeOne from "memoize-one";
|
||||
import { isComponentLoaded } from "../../common/config/is_component_loaded";
|
||||
import { formatDateTimeWithSeconds } from "../../common/datetime/format_date_time";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { computeRTL } from "../../common/util/compute_rtl";
|
||||
import "../../components/ha-adaptive-dialog";
|
||||
import "../../components/ha-alert";
|
||||
import "../../components/ha-icon";
|
||||
@@ -137,7 +138,18 @@ class DialogLogbookDetail
|
||||
}
|
||||
|
||||
const { entry } = this._params;
|
||||
const item = computeLogbookItem(this.hass, entry);
|
||||
const { entities, devices, areas, floors } = this.hass;
|
||||
const item = computeLogbookItem(
|
||||
this.hass.states,
|
||||
{ entities, devices, areas, floors },
|
||||
this.hass.localize,
|
||||
{
|
||||
formatEntityState: this.hass.formatEntityState,
|
||||
formatEntityAttributeValue: this.hass.formatEntityAttributeValue,
|
||||
},
|
||||
entry,
|
||||
{ isRTL: this._isRTL() }
|
||||
);
|
||||
|
||||
return html`
|
||||
<ha-adaptive-dialog
|
||||
@@ -153,6 +165,13 @@ class DialogLogbookDetail
|
||||
`;
|
||||
}
|
||||
|
||||
private _isRTL() {
|
||||
return computeRTL(
|
||||
this.hass.language,
|
||||
this.hass.translationMetadata.translations
|
||||
);
|
||||
}
|
||||
|
||||
private _renderFacts(item: LogbookItem, entry: LogbookEntry) {
|
||||
const stateObj = entry.entity_id
|
||||
? this.hass.states[entry.entity_id]
|
||||
@@ -176,7 +195,7 @@ class DialogLogbookDetail
|
||||
? html`<span class="old-state"
|
||||
>${transition.oldState}</span
|
||||
><span class="arrow"
|
||||
>${transitionArrow(this.hass)}</span
|
||||
>${transitionArrow(this._isRTL())}</span
|
||||
>`
|
||||
: nothing
|
||||
}<span class="new-state">${transition.newState}</span>
|
||||
@@ -242,7 +261,13 @@ class DialogLogbookDetail
|
||||
// icon either, so fall back to the chain's own integration glyph.
|
||||
private _renderSubjectIcon(item: LogbookItem, entry: LogbookEntry) {
|
||||
if (item.glyph.type !== "brand") {
|
||||
return renderLogbookGlyph(this.hass, entry, item.glyph);
|
||||
return renderLogbookGlyph(
|
||||
this.hass.config,
|
||||
this.hass.auth.data.hassUrl,
|
||||
this.hass.themes?.darkMode,
|
||||
entry,
|
||||
item.glyph
|
||||
);
|
||||
}
|
||||
return item.glyph.icon
|
||||
? html`<ha-icon .icon=${item.glyph.icon}></ha-icon>`
|
||||
|
||||
@@ -7,6 +7,7 @@ import { styleMap } from "lit/directives/style-map";
|
||||
import { formatTimeWithMilliseconds } from "../../common/datetime/format_time";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { isNavigationClick } from "../../common/dom/is-navigation-click";
|
||||
import { computeRTL } from "../../common/util/compute_rtl";
|
||||
import { navigate } from "../../common/navigate";
|
||||
import "../../components/ha-icon-next";
|
||||
import "../../components/ha-state-icon";
|
||||
@@ -16,9 +17,9 @@ import type { LogbookEntry } from "../../data/logbook";
|
||||
import { createHistoricState, localizeTriggerSource } from "../../data/logbook";
|
||||
import type { TraceContexts } from "../../data/trace";
|
||||
import { haStyle } from "../../resources/styles";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import type { HomeAssistant, HomeAssistantRegistries } from "../../types";
|
||||
import type { LogbookChain } from "./logbook-chain-resolver";
|
||||
import type { LogbookCause } from "./logbook-entry-model";
|
||||
import type { LogbookCause, LogbookGlyph } from "./logbook-entry-model";
|
||||
import {
|
||||
computeLogbookItem,
|
||||
computeRunTraceLink,
|
||||
@@ -169,7 +170,11 @@ class HaLogbookChain extends LitElement {
|
||||
: undefined;
|
||||
const secondary = isState
|
||||
? origin.entityId
|
||||
? entityDisplay(this.hass, origin.entityId).secondary
|
||||
? entityDisplay(
|
||||
this.hass.states[origin.entityId],
|
||||
this._registries(),
|
||||
this._isRTL()
|
||||
).secondary
|
||||
: undefined
|
||||
: this._actionUsedText(originRow);
|
||||
const isAvatar = origin.type === "user" && !origin.systemUser;
|
||||
@@ -242,6 +247,42 @@ class HaLogbookChain extends LitElement {
|
||||
return renderLogbookCauseIcon(origin);
|
||||
}
|
||||
|
||||
private _registries(): HomeAssistantRegistries {
|
||||
const { entities, devices, areas, floors } = this.hass;
|
||||
return { entities, devices, areas, floors };
|
||||
}
|
||||
|
||||
private _isRTL() {
|
||||
return computeRTL(
|
||||
this.hass.language,
|
||||
this.hass.translationMetadata.translations
|
||||
);
|
||||
}
|
||||
|
||||
private _computeItem(row: LogbookEntry) {
|
||||
return computeLogbookItem(
|
||||
this.hass.states,
|
||||
this._registries(),
|
||||
this.hass.localize,
|
||||
{
|
||||
formatEntityState: this.hass.formatEntityState,
|
||||
formatEntityAttributeValue: this.hass.formatEntityAttributeValue,
|
||||
},
|
||||
row,
|
||||
{ isRTL: this._isRTL() }
|
||||
);
|
||||
}
|
||||
|
||||
private _renderGlyph(row: LogbookEntry, glyph: LogbookGlyph) {
|
||||
return renderLogbookGlyph(
|
||||
this.hass.config,
|
||||
this.hass.auth.data.hassUrl,
|
||||
this.hass.themes?.darkMode,
|
||||
row,
|
||||
glyph
|
||||
);
|
||||
}
|
||||
|
||||
private _formatTimeWithMs(when: number) {
|
||||
return formatTimeWithMilliseconds(
|
||||
new Date(when),
|
||||
@@ -251,14 +292,14 @@ class HaLogbookChain extends LitElement {
|
||||
}
|
||||
|
||||
private _renderRunNode(row: LogbookEntry) {
|
||||
const item = computeLogbookItem(this.hass, row);
|
||||
const item = this._computeItem(row);
|
||||
const time = this._formatTimeWithMs(item.when);
|
||||
const traceLink = computeRunTraceLink(this.traceContexts, row);
|
||||
return this._renderRow(
|
||||
row.entity_id,
|
||||
html`
|
||||
<span class="chain-node run">
|
||||
${renderLogbookGlyph(this.hass, row, item.glyph)}
|
||||
${this._renderGlyph(row, item.glyph)}
|
||||
</span>
|
||||
<span class="chain-content">
|
||||
<span class="name">${item.name}</span>
|
||||
@@ -277,7 +318,7 @@ class HaLogbookChain extends LitElement {
|
||||
}
|
||||
|
||||
private _renderEffectNode(row: LogbookEntry) {
|
||||
const item = computeLogbookItem(this.hass, row);
|
||||
const item = this._computeItem(row);
|
||||
const stateObj = row.entity_id
|
||||
? this.hass.states[row.entity_id]
|
||||
: undefined;
|
||||
@@ -293,7 +334,7 @@ class HaLogbookChain extends LitElement {
|
||||
class="chain-node"
|
||||
style=${color ? styleMap({ "--node-color": color }) : nothing}
|
||||
>
|
||||
${renderLogbookGlyph(this.hass, row, item.glyph)}
|
||||
${this._renderGlyph(row, item.glyph)}
|
||||
</span>
|
||||
<span class="chain-content">
|
||||
<span class="name">${item.name}</span>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { HassConfig, HassEntities } from "home-assistant-js-websocket";
|
||||
import type { CSSResultGroup, TemplateResult } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
@@ -8,13 +10,26 @@ import { computeTimelineColor } from "../../components/chart/timeline-color";
|
||||
import { computeDomain } from "../../common/entity/compute_domain";
|
||||
import { formatTimeWithSeconds } from "../../common/datetime/format_time";
|
||||
import { useAmPm } from "../../common/datetime/use_am_pm";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import { transform } from "../../common/decorators/transform";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { computeRTL } from "../../common/util/compute_rtl";
|
||||
import "../../components/ha-icon-next";
|
||||
import "../../components/ha-tooltip";
|
||||
import {
|
||||
brandsAccessTokenContext,
|
||||
configContext,
|
||||
connectionContext,
|
||||
formattersContext,
|
||||
internationalizationContext,
|
||||
registriesContext,
|
||||
statesContext,
|
||||
uiContext,
|
||||
} from "../../data/context";
|
||||
import { UNAVAILABLE } from "../../data/entity/entity";
|
||||
import type { LogbookEntry } from "../../data/logbook";
|
||||
import { haStyle } from "../../resources/styles";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import type { HomeAssistantConfig, HomeAssistantUI } from "../../types";
|
||||
import type {
|
||||
LogbookCause,
|
||||
LogbookCauseType,
|
||||
@@ -38,6 +53,7 @@ type EntryLayout = "timeline" | "list" | "inline";
|
||||
interface LogbookRenderItem extends LogbookItem {
|
||||
renderedTime: string;
|
||||
renderedValue: TemplateResult | string;
|
||||
isRTL: boolean;
|
||||
}
|
||||
|
||||
export interface LogbookEntrySelectedDetail {
|
||||
@@ -52,8 +68,6 @@ declare global {
|
||||
|
||||
@customElement("ha-logbook-entry")
|
||||
class HaLogbookEntry extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public item!: LogbookEntry;
|
||||
|
||||
@property({ attribute: false }) public userIdToName: Record<string, string> =
|
||||
@@ -82,6 +96,45 @@ class HaLogbookEntry extends LitElement {
|
||||
@property({ type: Boolean, attribute: "show-cause" }) public showCause =
|
||||
false;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: ContextType<typeof internationalizationContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
private _formatters!: ContextType<typeof formattersContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: registriesContext, subscribe: true })
|
||||
private _registries!: ContextType<typeof registriesContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, HassConfig>({
|
||||
transformer: ({ config }) => config,
|
||||
})
|
||||
private _config!: HassConfig;
|
||||
|
||||
@consume({ context: connectionContext, subscribe: true })
|
||||
private _connection!: ContextType<typeof connectionContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: brandsAccessTokenContext, subscribe: true })
|
||||
// @ts-ignore re-render trigger only, its value is never read
|
||||
private _brandsAccessToken?: string;
|
||||
|
||||
@state()
|
||||
@consume({ context: uiContext, subscribe: true })
|
||||
@transform<HomeAssistantUI, boolean | undefined>({
|
||||
transformer: ({ themes }) => themes?.darkMode,
|
||||
})
|
||||
private _darkMode?: boolean;
|
||||
|
||||
// Not reactive: rows keep the names they rendered with instead of
|
||||
// rerendering on every state change.
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
private _states?: HassEntities | null;
|
||||
|
||||
// Reading custom properties forces a style recalc, costly to repeat per row
|
||||
// while scrolling — resolve once and cache.
|
||||
private _computedStyle?: CSSStyleDeclaration;
|
||||
@@ -90,11 +143,23 @@ class HaLogbookEntry extends LitElement {
|
||||
const entry = this.item;
|
||||
const seenEntityIds: string[] = [];
|
||||
|
||||
const item = computeLogbookItem(this.hass, entry, {
|
||||
nameDetail: this.nameDetail,
|
||||
userIdToName: this.userIdToName,
|
||||
systemUserIds: this.systemUserIds,
|
||||
});
|
||||
const isRTL = computeRTL(
|
||||
this._i18n.language,
|
||||
this._i18n.translationMetadata.translations
|
||||
);
|
||||
const item = computeLogbookItem(
|
||||
this._states ?? {},
|
||||
this._registries,
|
||||
this._i18n.localize,
|
||||
this._formatters,
|
||||
entry,
|
||||
{
|
||||
nameDetail: this.nameDetail,
|
||||
isRTL,
|
||||
userIdToName: this.userIdToName,
|
||||
systemUserIds: this.systemUserIds,
|
||||
}
|
||||
);
|
||||
|
||||
const hideName = this.nameDetail === "none";
|
||||
const layout: EntryLayout =
|
||||
@@ -103,14 +168,15 @@ class HaLogbookEntry extends LitElement {
|
||||
|
||||
const renderedTime = formatTimeWithSeconds(
|
||||
new Date(item.when),
|
||||
this.hass.locale,
|
||||
this.hass.config
|
||||
this._i18n.locale,
|
||||
this._config
|
||||
);
|
||||
|
||||
const ctx: LogbookRenderItem = {
|
||||
...item,
|
||||
renderedTime,
|
||||
renderedValue: this._renderValue(item.value, seenEntityIds),
|
||||
isRTL,
|
||||
};
|
||||
|
||||
const clickable = !this.noDetail;
|
||||
@@ -125,7 +191,7 @@ class HaLogbookEntry extends LitElement {
|
||||
[`node-${node}`]: true,
|
||||
"last-of-day": this.lastOfDay,
|
||||
[`category-${ctx.category}`]: true,
|
||||
"time-am-pm": useAmPm(this.hass.locale),
|
||||
"time-am-pm": useAmPm(this._i18n.locale),
|
||||
clickable,
|
||||
})}"
|
||||
role=${ifDefined(clickable ? "button" : undefined)}
|
||||
@@ -213,7 +279,7 @@ class HaLogbookEntry extends LitElement {
|
||||
ctx.renderedValue
|
||||
? valueIsState
|
||||
? html`<span class="arrow"
|
||||
>${transitionArrow(this.hass)}</span
|
||||
>${transitionArrow(ctx.isRTL)}</span
|
||||
>`
|
||||
: " "
|
||||
: nothing
|
||||
@@ -265,7 +331,7 @@ class HaLogbookEntry extends LitElement {
|
||||
}
|
||||
|
||||
private _renderCauseLine(cause: LogbookCause) {
|
||||
const { localize } = this.hass;
|
||||
const { localize } = this._i18n;
|
||||
if (cause.entityId) {
|
||||
const prefixMap: Partial<Record<LogbookCauseType, string>> = {
|
||||
automation: localize("ui.components.logbook.cause.by_automation", {
|
||||
@@ -284,7 +350,7 @@ class HaLogbookEntry extends LitElement {
|
||||
</span>`;
|
||||
}
|
||||
return html`<span class="cause-line"
|
||||
>${computeCausePhrase(this.hass.localize, cause)}</span
|
||||
>${computeCausePhrase(localize, cause)}</span
|
||||
>`;
|
||||
}
|
||||
|
||||
@@ -313,11 +379,10 @@ class HaLogbookEntry extends LitElement {
|
||||
entityId: string | undefined,
|
||||
entityName: string | undefined
|
||||
) {
|
||||
const stateObj = entityId ? this._states?.[entityId] : undefined;
|
||||
return (
|
||||
entityName ||
|
||||
(entityId && entityId in this.hass.states
|
||||
? this.hass.formatEntityName(this.hass.states[entityId])
|
||||
: entityId)
|
||||
(stateObj ? this._formatters.formatEntityName(stateObj) : entityId)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -328,7 +393,8 @@ class HaLogbookEntry extends LitElement {
|
||||
if (message.indexOf(".") !== -1) {
|
||||
const messageParts = message.split(" ");
|
||||
for (let i = 0, size = messageParts.length; i < size; i++) {
|
||||
if (messageParts[i] in this.hass.states) {
|
||||
const stateObj = this._states?.[messageParts[i]];
|
||||
if (stateObj) {
|
||||
const entityId = messageParts[i];
|
||||
if (seenEntities.includes(entityId)) {
|
||||
return "";
|
||||
@@ -337,8 +403,7 @@ class HaLogbookEntry extends LitElement {
|
||||
const messageEnd = messageParts.splice(i);
|
||||
messageEnd.shift();
|
||||
return html`${messageParts.join(" ")}
|
||||
${this.hass.formatEntityName(this.hass.states[entityId])}
|
||||
${messageEnd.join(" ")}`;
|
||||
${this._formatters.formatEntityName(stateObj)} ${messageEnd.join(" ")}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -374,7 +439,13 @@ class HaLogbookEntry extends LitElement {
|
||||
const unavailable =
|
||||
item.glyph.type === "state" && item.glyph.stateObj.state === UNAVAILABLE;
|
||||
return html`<div class="node-glyph" style=${style}>
|
||||
${renderLogbookGlyph(this.hass, this.item, item.glyph)}
|
||||
${renderLogbookGlyph(
|
||||
this._config,
|
||||
this._connection.hassUrl(),
|
||||
this._darkMode,
|
||||
this.item,
|
||||
item.glyph
|
||||
)}
|
||||
${unavailable ? html`<span class="node-badge"></span>` : nothing}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { VisibilityChangedEvent } from "@lit-labs/virtualizer";
|
||||
import type { HassConfig } from "home-assistant-js-websocket";
|
||||
import memoizeOne from "memoize-one";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, eventOptions, property, state } from "lit/decorators";
|
||||
import { formatDate } from "../../common/datetime/format_date";
|
||||
import { capitalizeFirstLetter } from "../../common/string/capitalize-first-letter";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import { restoreScroll } from "../../common/decorators/restore-scroll";
|
||||
import { transform } from "../../common/decorators/transform";
|
||||
import type { HASSDomEvent } from "../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { configContext, internationalizationContext } from "../../data/context";
|
||||
import type { LogbookEntry } from "../../data/logbook";
|
||||
import type { TraceContexts } from "../../data/trace";
|
||||
import { haStyle, haStyleScrollbar } from "../../resources/styles";
|
||||
import { loadVirtualizer } from "../../resources/virtualizer";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import type { HomeAssistantConfig } from "../../types";
|
||||
import "./ha-logbook-entry";
|
||||
import type { LogbookEntrySelectedDetail } from "./ha-logbook-entry";
|
||||
import type { LogbookNameDetail } from "./logbook-entry-model";
|
||||
@@ -27,8 +32,6 @@ declare global {
|
||||
|
||||
@customElement("ha-logbook-renderer")
|
||||
class HaLogbookRenderer extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public userIdToName: Record<string, string> =
|
||||
{};
|
||||
|
||||
@@ -62,40 +65,33 @@ class HaLogbookRenderer extends LitElement {
|
||||
|
||||
@state() private _firstVisibleIndex = 0;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: ContextType<typeof internationalizationContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, HassConfig>({
|
||||
transformer: ({ config }) => config,
|
||||
})
|
||||
private _config!: HassConfig;
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>) {
|
||||
if (
|
||||
(!this.hasUpdated && this.virtualize) ||
|
||||
(changedProps.has("virtualize") && this.virtualize)
|
||||
) {
|
||||
this.hass.loadBackendTranslation("services");
|
||||
this.hass.loadBackendTranslation("title");
|
||||
this._i18n.loadBackendTranslation("services");
|
||||
this._i18n.loadBackendTranslation("title");
|
||||
loadVirtualizer();
|
||||
}
|
||||
}
|
||||
|
||||
protected shouldUpdate(changedProps: PropertyValues<this>) {
|
||||
const oldHass = changedProps.get("hass") as HomeAssistant | undefined;
|
||||
const languageChanged =
|
||||
oldHass === undefined ||
|
||||
oldHass.locale !== this.hass.locale ||
|
||||
oldHass.localize !== this.hass.localize;
|
||||
|
||||
return (
|
||||
changedProps.has("entries") ||
|
||||
changedProps.has("traceContexts") ||
|
||||
changedProps.has("noDetail") ||
|
||||
changedProps.has("userIdToName") ||
|
||||
changedProps.has("systemUserIds") ||
|
||||
changedProps.has("_firstVisibleIndex" as never) ||
|
||||
languageChanged
|
||||
);
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.entries?.length) {
|
||||
return html`
|
||||
<div class="container no-entries">
|
||||
${this.hass.localize("ui.components.logbook.entries_not_found")}
|
||||
${this._i18n.localize("ui.components.logbook.entries_not_found")}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
@@ -128,7 +124,9 @@ class HaLogbookRenderer extends LitElement {
|
||||
.renderItem=${
|
||||
this._getRenderRow(
|
||||
this.userIdToName,
|
||||
this.systemUserIds
|
||||
this.systemUserIds,
|
||||
this._i18n,
|
||||
this._config
|
||||
) as any
|
||||
}
|
||||
>
|
||||
@@ -142,7 +140,12 @@ class HaLogbookRenderer extends LitElement {
|
||||
// Memoized on every input the rows render from, so the virtualizer sees a
|
||||
// new renderItem and refreshes already-rendered rows when one changes.
|
||||
private _getRenderRow = memoizeOne(
|
||||
(_userIdToName: Record<string, string>, _systemUserIds: Set<string>) =>
|
||||
(
|
||||
_userIdToName: Record<string, string>,
|
||||
_systemUserIds: Set<string>,
|
||||
_i18n: ContextType<typeof internationalizationContext>,
|
||||
_config: HassConfig
|
||||
) =>
|
||||
(item: LogbookEntry, index: number) =>
|
||||
this._renderItem(item, index)
|
||||
);
|
||||
@@ -165,7 +168,6 @@ class HaLogbookRenderer extends LitElement {
|
||||
: nothing
|
||||
}
|
||||
<ha-logbook-entry
|
||||
.hass=${this.hass}
|
||||
.item=${item}
|
||||
.userIdToName=${this.userIdToName}
|
||||
.systemUserIds=${this.systemUserIds}
|
||||
@@ -203,9 +205,9 @@ class HaLogbookRenderer extends LitElement {
|
||||
const d = new Date(date);
|
||||
d.setHours(0, 0, 0, 0);
|
||||
const diffDays = Math.round((today.getTime() - d.getTime()) / 86400000);
|
||||
const fullDate = formatDate(date, this.hass.locale, this.hass.config);
|
||||
const fullDate = formatDate(date, this._i18n.locale, this._config);
|
||||
if (diffDays === 0 || diffDays === 1) {
|
||||
const rtf = new Intl.RelativeTimeFormat(this.hass.locale.language, {
|
||||
const rtf = new Intl.RelativeTimeFormat(this._i18n.locale.language, {
|
||||
numeric: "auto",
|
||||
});
|
||||
const rel = rtf.format(diffDays === 0 ? 0 : -1, "day");
|
||||
|
||||
@@ -149,7 +149,6 @@ export class HaLogbook extends LitElement {
|
||||
|
||||
return html`
|
||||
<ha-logbook-renderer
|
||||
.hass=${this.hass}
|
||||
.narrow=${this.narrow}
|
||||
.virtualize=${this.virtualize}
|
||||
.noIcon=${this.noIcon}
|
||||
@@ -192,11 +191,20 @@ export class HaLogbook extends LitElement {
|
||||
return entries;
|
||||
}
|
||||
const causes = new Set(causeFilter);
|
||||
const { states, entities, devices, areas, floors, localize } = this.hass;
|
||||
const registries = { entities, devices, areas, floors };
|
||||
return entries.filter((entry) =>
|
||||
causes.has(
|
||||
computeLogbookCauseKey(
|
||||
entry,
|
||||
computeRowCause(this.hass, entry, userIdToName, systemUserIds),
|
||||
computeRowCause(
|
||||
states,
|
||||
registries,
|
||||
localize,
|
||||
entry,
|
||||
userIdToName,
|
||||
systemUserIds
|
||||
),
|
||||
personUserIds
|
||||
)
|
||||
)
|
||||
|
||||
@@ -110,6 +110,8 @@ export const resolveLogbookChain = async (
|
||||
): Promise<LogbookChain> => {
|
||||
const userIdToName = options.userIdToName ?? {};
|
||||
const { systemUserIds } = options;
|
||||
const { entities, devices, areas, floors } = hass;
|
||||
const registries = { entities, devices, areas, floors };
|
||||
|
||||
let rows: LogbookEntry[] = [];
|
||||
if (entry.context_id) {
|
||||
@@ -137,7 +139,9 @@ export const resolveLogbookChain = async (
|
||||
let syntheticRun: LogbookCause | undefined;
|
||||
if (runRow) {
|
||||
const runCause = computeLogbookCause(
|
||||
hass,
|
||||
hass.states,
|
||||
registries,
|
||||
hass.localize,
|
||||
runRow,
|
||||
userIdToName,
|
||||
systemUserIds
|
||||
@@ -155,7 +159,12 @@ export const resolveLogbookChain = async (
|
||||
}
|
||||
} else {
|
||||
const userCause = computeUserCause(entry, userIdToName, systemUserIds);
|
||||
const contextCause = computeContextCause(hass, entry);
|
||||
const contextCause = computeContextCause(
|
||||
hass.states,
|
||||
registries,
|
||||
hass.localize,
|
||||
entry
|
||||
);
|
||||
if (isRunCause(contextCause)) {
|
||||
syntheticRun = contextCause;
|
||||
if (userCause) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isSameDay } from "date-fns";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
|
||||
import { computeDomain } from "../../common/entity/compute_domain";
|
||||
import { computeEntityNameParts } from "../../common/entity/compute_entity_name_display";
|
||||
import { stateColorCss } from "../../common/entity/state_color";
|
||||
@@ -7,9 +7,8 @@ import type {
|
||||
LocalizeFunc,
|
||||
LocalizeKeys,
|
||||
} from "../../common/translations/localize";
|
||||
import { computeRTL } from "../../common/util/compute_rtl";
|
||||
import { domainToName } from "../../data/integration";
|
||||
import type { LogbookEntry } from "../../data/logbook";
|
||||
import type { LogbookEntry, LogbookStateFormatters } from "../../data/logbook";
|
||||
import {
|
||||
createHistoricState,
|
||||
logbookUserCauseKey,
|
||||
@@ -18,7 +17,7 @@ import {
|
||||
} from "../../data/logbook";
|
||||
import type { TraceContexts } from "../../data/trace";
|
||||
import { getTraceUrl } from "../../data/trace";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import type { HomeAssistantRegistries } from "../../types";
|
||||
|
||||
export type LogbookEntryCategory = "entity" | "automation" | "integration";
|
||||
|
||||
@@ -63,12 +62,23 @@ export interface EntityDisplay {
|
||||
secondary?: string;
|
||||
}
|
||||
|
||||
const entityPrimaryName = (
|
||||
stateObj: HassEntity | undefined,
|
||||
registries: HomeAssistantRegistries
|
||||
): string | undefined => {
|
||||
if (!stateObj) {
|
||||
return undefined;
|
||||
}
|
||||
const { entity, device } = computeEntityNameParts(stateObj, registries);
|
||||
return entity || device || stateObj.entity_id;
|
||||
};
|
||||
|
||||
export const entityDisplay = (
|
||||
hass: HomeAssistant,
|
||||
entityId: string,
|
||||
stateObj: HassEntity | undefined,
|
||||
registries: HomeAssistantRegistries,
|
||||
isRTL: boolean,
|
||||
nameDetail?: LogbookNameDetail
|
||||
): EntityDisplay => {
|
||||
const stateObj = hass.states[entityId] as HassEntity | undefined;
|
||||
if (!stateObj) {
|
||||
return {};
|
||||
}
|
||||
@@ -78,9 +88,9 @@ export const entityDisplay = (
|
||||
device: deviceName,
|
||||
parent_device: parentDeviceName,
|
||||
area: areaName,
|
||||
} = computeEntityNameParts(stateObj, hass);
|
||||
} = computeEntityNameParts(stateObj, registries);
|
||||
|
||||
const primary = entityName || deviceName || entityId;
|
||||
const primary = entityName || deviceName || stateObj.entity_id;
|
||||
|
||||
// Show the device only when the entity has its own name; otherwise the
|
||||
// device name is the subject and repeating it would duplicate it.
|
||||
@@ -101,10 +111,6 @@ export const entityDisplay = (
|
||||
}
|
||||
|
||||
const filtered = parts.filter(Boolean) as string[];
|
||||
const isRTL = computeRTL(
|
||||
hass.language,
|
||||
hass.translationMetadata.translations
|
||||
);
|
||||
const secondary = filtered.length
|
||||
? filtered.join(isRTL ? " ◂ " : " ▸ ")
|
||||
: undefined;
|
||||
@@ -204,7 +210,9 @@ export const computeUserCause = (
|
||||
};
|
||||
|
||||
export const computeContextCause = (
|
||||
hass: HomeAssistant,
|
||||
states: HassEntities,
|
||||
registries: HomeAssistantRegistries,
|
||||
localize: LocalizeFunc,
|
||||
item: LogbookEntry
|
||||
): LogbookCause | undefined => {
|
||||
if (
|
||||
@@ -213,7 +221,7 @@ export const computeContextCause = (
|
||||
) {
|
||||
const name =
|
||||
(item.context_entity_id
|
||||
? entityDisplay(hass, item.context_entity_id).primary
|
||||
? entityPrimaryName(states[item.context_entity_id], registries)
|
||||
: undefined) ?? item.context_name;
|
||||
if (name) {
|
||||
return {
|
||||
@@ -231,13 +239,13 @@ export const computeContextCause = (
|
||||
return {
|
||||
type: "integration",
|
||||
brandDomain: item.context_domain,
|
||||
name: domainToName(hass.localize, item.context_domain),
|
||||
name: domainToName(localize, item.context_domain),
|
||||
};
|
||||
}
|
||||
|
||||
if (item.context_state && item.context_entity_id) {
|
||||
const name =
|
||||
entityDisplay(hass, item.context_entity_id).primary ??
|
||||
entityPrimaryName(states[item.context_entity_id], registries) ??
|
||||
item.context_entity_id_name;
|
||||
if (name) {
|
||||
return { type: "state", name, entityId: item.context_entity_id };
|
||||
@@ -253,8 +261,8 @@ export const computeContextCause = (
|
||||
const { platform, entityId } = parseTriggerSource(item.source);
|
||||
if (platform === "state" || platform === "numeric_state") {
|
||||
const name = entityId
|
||||
? (entityDisplay(hass, entityId).primary ?? entityId)
|
||||
: hass.localize(
|
||||
? (entityPrimaryName(states[entityId], registries) ?? entityId)
|
||||
: localize(
|
||||
`ui.components.logbook.trigger_type.${platform}` as LocalizeKeys
|
||||
) || platform;
|
||||
return { type: "state", name, entityId };
|
||||
@@ -269,7 +277,7 @@ export const computeContextCause = (
|
||||
return {
|
||||
type: "homeassistant",
|
||||
name:
|
||||
hass.localize(`ui.components.logbook.${key}` as LocalizeKeys) ||
|
||||
localize(`ui.components.logbook.${key}` as LocalizeKeys) ||
|
||||
item.source,
|
||||
};
|
||||
}
|
||||
@@ -277,7 +285,7 @@ export const computeContextCause = (
|
||||
return {
|
||||
type: "integration",
|
||||
name:
|
||||
hass.localize(
|
||||
localize(
|
||||
`ui.components.logbook.trigger_type.${platform}` as LocalizeKeys
|
||||
) || platform,
|
||||
};
|
||||
@@ -298,13 +306,15 @@ export const computeContextCause = (
|
||||
};
|
||||
|
||||
export const computeLogbookCause = (
|
||||
hass: HomeAssistant,
|
||||
states: HassEntities,
|
||||
registries: HomeAssistantRegistries,
|
||||
localize: LocalizeFunc,
|
||||
item: LogbookEntry,
|
||||
userIdToName: Record<string, string>,
|
||||
systemUserIds?: Set<string>
|
||||
): LogbookCause | undefined =>
|
||||
computeUserCause(item, userIdToName, systemUserIds) ??
|
||||
computeContextCause(hass, item);
|
||||
computeContextCause(states, registries, localize, item);
|
||||
|
||||
export const computeCausePhrase = (
|
||||
localize: LocalizeFunc,
|
||||
@@ -345,12 +355,14 @@ export const isRunCause = (cause?: LogbookCause): boolean =>
|
||||
|
||||
// A row shows the run over the user who started it; the dialog shows both.
|
||||
export const computeRowCause = (
|
||||
hass: HomeAssistant,
|
||||
states: HassEntities,
|
||||
registries: HomeAssistantRegistries,
|
||||
localize: LocalizeFunc,
|
||||
item: LogbookEntry,
|
||||
userIdToName: Record<string, string>,
|
||||
systemUserIds?: Set<string>
|
||||
): LogbookCause | undefined => {
|
||||
const contextCause = computeContextCause(hass, item);
|
||||
const contextCause = computeContextCause(states, registries, localize, item);
|
||||
if (isRunCause(contextCause)) {
|
||||
return contextCause;
|
||||
}
|
||||
@@ -409,7 +421,8 @@ export interface LogbookValue {
|
||||
}
|
||||
|
||||
const computeLogbookValue = (
|
||||
hass: HomeAssistant,
|
||||
localize: LocalizeFunc,
|
||||
formatters: LogbookStateFormatters,
|
||||
item: LogbookEntry,
|
||||
domain: string | undefined,
|
||||
stateObj: HassEntity | undefined
|
||||
@@ -417,7 +430,14 @@ const computeLogbookValue = (
|
||||
if (item.entity_id && item.state) {
|
||||
return {
|
||||
text: stateObj
|
||||
? localizeStateMessage(hass, item.state, stateObj, domain!, item)
|
||||
? localizeStateMessage(
|
||||
localize,
|
||||
formatters,
|
||||
item.state,
|
||||
stateObj,
|
||||
domain!,
|
||||
item
|
||||
)
|
||||
: item.state,
|
||||
type: "state",
|
||||
};
|
||||
@@ -432,7 +452,7 @@ const computeLogbookValue = (
|
||||
isRunMessage(domain, item.message);
|
||||
if (isAutomationRun) {
|
||||
return {
|
||||
text: hass.localize(
|
||||
text: localize(
|
||||
domain === "script"
|
||||
? "ui.components.logbook.script_ran"
|
||||
: "ui.components.logbook.automation_triggered"
|
||||
@@ -466,12 +486,16 @@ export interface LogbookItem {
|
||||
|
||||
export interface BuildLogbookItemOptions {
|
||||
nameDetail?: LogbookNameDetail;
|
||||
isRTL?: boolean;
|
||||
userIdToName?: Record<string, string>;
|
||||
systemUserIds?: Set<string>;
|
||||
}
|
||||
|
||||
export const computeLogbookItem = (
|
||||
hass: HomeAssistant,
|
||||
states: HassEntities,
|
||||
registries: HomeAssistantRegistries,
|
||||
localize: LocalizeFunc,
|
||||
formatters: LogbookStateFormatters,
|
||||
entry: LogbookEntry,
|
||||
opts: BuildLogbookItemOptions = {}
|
||||
): LogbookItem => {
|
||||
@@ -479,15 +503,18 @@ export const computeLogbookItem = (
|
||||
const domain = entry.entity_id
|
||||
? computeDomain(entry.entity_id)
|
||||
: entry.domain;
|
||||
const currentStateObj = entry.entity_id
|
||||
? hass.states[entry.entity_id]
|
||||
: undefined;
|
||||
const currentStateObj = entry.entity_id ? states[entry.entity_id] : undefined;
|
||||
const historicStateObj = currentStateObj
|
||||
? createHistoricState(currentStateObj, entry.state)
|
||||
: undefined;
|
||||
|
||||
const display = entry.entity_id
|
||||
? entityDisplay(hass, entry.entity_id, opts.nameDetail)
|
||||
? entityDisplay(
|
||||
currentStateObj,
|
||||
registries,
|
||||
opts.isRTL ?? false,
|
||||
opts.nameDetail
|
||||
)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
@@ -496,9 +523,17 @@ export const computeLogbookItem = (
|
||||
entityId: entry.entity_id,
|
||||
name: display?.primary ?? entry.name,
|
||||
context: display?.secondary,
|
||||
value: computeLogbookValue(hass, entry, domain, historicStateObj),
|
||||
value: computeLogbookValue(
|
||||
localize,
|
||||
formatters,
|
||||
entry,
|
||||
domain,
|
||||
historicStateObj
|
||||
),
|
||||
cause: computeRowCause(
|
||||
hass,
|
||||
states,
|
||||
registries,
|
||||
localize,
|
||||
entry,
|
||||
opts.userIdToName ?? {},
|
||||
opts.systemUserIds
|
||||
|
||||
@@ -7,9 +7,9 @@ import {
|
||||
mdiScriptText,
|
||||
mdiStateMachine,
|
||||
} from "@mdi/js";
|
||||
import type { HassConfig } from "home-assistant-js-websocket";
|
||||
import { html } from "lit";
|
||||
import { isComponentLoaded } from "../../common/config/is_component_loaded";
|
||||
import { computeRTL } from "../../common/util/compute_rtl";
|
||||
import "../../components/entity/state-badge";
|
||||
import "../../components/ha-domain-icon";
|
||||
import "../../components/ha-state-icon";
|
||||
@@ -18,7 +18,6 @@ import "../../components/user/ha-user-badge";
|
||||
import { mdiHomeAssistant } from "../../resources/home-assistant-logo-svg";
|
||||
import type { LogbookEntry } from "../../data/logbook";
|
||||
import type { User } from "../../data/user";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { brandsUrl } from "../../util/brands-url";
|
||||
import type { LogbookCause, LogbookGlyph } from "./logbook-entry-model";
|
||||
|
||||
@@ -90,7 +89,9 @@ export const renderLogbookCauseIcon = (cause: LogbookCause) => {
|
||||
};
|
||||
|
||||
const brandImage = (
|
||||
hass: HomeAssistant,
|
||||
config: HassConfig,
|
||||
hassUrl: string,
|
||||
darkMode: boolean | undefined,
|
||||
entry: LogbookEntry,
|
||||
domain?: string
|
||||
): string | undefined => {
|
||||
@@ -98,25 +99,19 @@ const brandImage = (
|
||||
!domain ||
|
||||
entry.icon ||
|
||||
entry.state ||
|
||||
!isComponentLoaded(hass.config, domain)
|
||||
!isComponentLoaded(config, domain)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return brandsUrl(
|
||||
{
|
||||
domain,
|
||||
type: "icon",
|
||||
darkOptimized: hass.themes?.darkMode,
|
||||
},
|
||||
hass.auth.data.hassUrl
|
||||
);
|
||||
return brandsUrl({ domain, type: "icon", darkOptimized: darkMode }, hassUrl);
|
||||
};
|
||||
|
||||
export const transitionArrow = (hass: HomeAssistant) =>
|
||||
computeRTL(hass.language, hass.translationMetadata.translations) ? "←" : "→";
|
||||
export const transitionArrow = (isRTL: boolean) => (isRTL ? "←" : "→");
|
||||
|
||||
export const renderLogbookGlyph = (
|
||||
hass: HomeAssistant,
|
||||
config: HassConfig,
|
||||
hassUrl: string,
|
||||
darkMode: boolean | undefined,
|
||||
entry: LogbookEntry,
|
||||
glyph: LogbookGlyph
|
||||
) => {
|
||||
@@ -133,7 +128,7 @@ export const renderLogbookGlyph = (
|
||||
}
|
||||
return html`<state-badge
|
||||
.overrideIcon=${glyph.icon}
|
||||
.overrideImage=${brandImage(hass, entry, glyph.domain)}
|
||||
.overrideImage=${brandImage(config, hassUrl, darkMode, entry, glyph.domain)}
|
||||
.stateColor=${false}
|
||||
></state-badge>`;
|
||||
};
|
||||
@@ -201,7 +201,7 @@ export class HuiAlertBadge extends LitElement implements LovelaceBadge {
|
||||
isolation: isolate;
|
||||
border-radius: var(
|
||||
--ha-badge-border-radius,
|
||||
calc(var(--ha-badge-size, 36px) / 2)
|
||||
calc(var(--ha-border-radius-lg) + 3px)
|
||||
);
|
||||
background: var(--ha-alert-badge-background);
|
||||
--ha-card-background: transparent;
|
||||
|
||||
@@ -1,27 +1,43 @@
|
||||
import { mdiAlertCircle } from "@mdi/js";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { computeCssColor } from "../../../common/color/compute-color";
|
||||
import { hsv2rgb, rgb2hex, rgb2hsv } from "../../../common/color/convert-color";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../common/decorators/transform";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import { computeDomain } from "../../../common/entity/compute_domain";
|
||||
import { stateActive } from "../../../common/entity/state_active";
|
||||
import { stateColorCss } from "../../../common/entity/state_color";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-badge";
|
||||
import "../../../components/ha-state-icon";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import {
|
||||
brandsAccessTokenContext,
|
||||
connectionContext,
|
||||
formattersContext,
|
||||
} from "../../../data/context";
|
||||
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
import type {
|
||||
HomeAssistant,
|
||||
HomeAssistantConnection,
|
||||
HomeAssistantFormatters,
|
||||
} from "../../../types";
|
||||
import {
|
||||
getTileImageUrl,
|
||||
hasTileCardAction,
|
||||
} from "../cards/tile/tile-card-helpers";
|
||||
import { actionHandler } from "../common/directives/action-handler-directive";
|
||||
import { findEntities } from "../common/find-entities";
|
||||
import { handleAction } from "../common/handle-action";
|
||||
import { hasAction } from "../common/has-action";
|
||||
import type { LovelaceBadge, LovelaceBadgeEditor } from "../types";
|
||||
import type { EntityBadgeConfig } from "./types";
|
||||
@@ -89,10 +105,38 @@ export class HuiEntityBadge extends LitElement implements LovelaceBadge {
|
||||
return DEFAULT_CONFIG;
|
||||
}
|
||||
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@state() protected _config?: EntityBadgeConfig;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
|
||||
private _stateObj?: HassEntity;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
@transform<
|
||||
HomeAssistantFormatters,
|
||||
HomeAssistantFormatters["formatEntityName"]
|
||||
>({
|
||||
transformer: ({ formatEntityName }) => formatEntityName,
|
||||
})
|
||||
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
|
||||
|
||||
@state()
|
||||
@consume({ context: connectionContext, subscribe: true })
|
||||
@transform<HomeAssistantConnection, HomeAssistantConnection["hassUrl"]>({
|
||||
transformer: ({ hassUrl }) => hassUrl,
|
||||
})
|
||||
private _hassUrl!: HomeAssistantConnection["hassUrl"];
|
||||
|
||||
@state()
|
||||
@consume({ context: brandsAccessTokenContext, subscribe: true })
|
||||
// @ts-ignore re-render trigger only, its value is never read
|
||||
private _brandsAccessToken?: string;
|
||||
|
||||
public setConfig(config: EntityBadgeConfig): void {
|
||||
this._config = {
|
||||
...DEFAULT_CONFIG,
|
||||
@@ -136,18 +180,18 @@ export class HuiEntityBadge extends LitElement implements LovelaceBadge {
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this._config || !this.hass) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const entityId = this._config.entity;
|
||||
const stateObj = entityId ? this.hass.states[entityId] : undefined;
|
||||
const stateObj = this._stateObj;
|
||||
|
||||
if (!stateObj) {
|
||||
return html`
|
||||
<ha-badge .label=${entityId} class="error">
|
||||
<ha-svg-icon slot="icon" .path=${mdiAlertCircle}></ha-svg-icon>
|
||||
${this.hass.localize("ui.badge.entity.not_found")}
|
||||
${this._localize("ui.badge.entity.not_found")}
|
||||
</ha-badge>
|
||||
`;
|
||||
}
|
||||
@@ -159,7 +203,7 @@ export class HuiEntityBadge extends LitElement implements LovelaceBadge {
|
||||
"--badge-color": color,
|
||||
};
|
||||
|
||||
const name = this.hass.formatEntityName(stateObj, this._config.name);
|
||||
const name = this._formatEntityName(stateObj, this._config.name);
|
||||
|
||||
const stateDisplay = html`
|
||||
<state-display
|
||||
@@ -177,7 +221,7 @@ export class HuiEntityBadge extends LitElement implements LovelaceBadge {
|
||||
const showEntityPicture = this._config.show_entity_picture;
|
||||
|
||||
const imageUrl = showEntityPicture
|
||||
? getTileImageUrl(this.hass, stateObj, 32)
|
||||
? getTileImageUrl(this._hassUrl, stateObj, 32)
|
||||
: undefined;
|
||||
|
||||
const label = showState && showName ? name : undefined;
|
||||
@@ -216,7 +260,10 @@ export class HuiEntityBadge extends LitElement implements LovelaceBadge {
|
||||
}
|
||||
|
||||
private _handleAction(ev: ActionHandlerEvent) {
|
||||
handleAction(this, this.hass!, this._config!, ev.detail.action!);
|
||||
fireEvent(this, "hass-action", {
|
||||
config: this._config!,
|
||||
action: ev.detail.action,
|
||||
});
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
|
||||
@@ -2,9 +2,10 @@ import { mdiAlertCircle } from "@mdi/js";
|
||||
import { dump } from "js-yaml";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-badge";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
import { showAlertDialog } from "../custom-card-helpers";
|
||||
import type { LovelaceBadge } from "../types";
|
||||
import type { ErrorBadgeConfig } from "./types";
|
||||
@@ -22,7 +23,7 @@ export const createErrorBadgeConfig = (error) => ({
|
||||
|
||||
@customElement("hui-error-badge")
|
||||
export class HuiErrorBadge extends LitElement implements LovelaceBadge {
|
||||
public hass?: HomeAssistant;
|
||||
@state() @consumeLocalize() private _localize?: LocalizeFunc;
|
||||
|
||||
@state() private _config?: ErrorBadgeConfig;
|
||||
|
||||
@@ -59,8 +60,7 @@ export class HuiErrorBadge extends LitElement implements LovelaceBadge {
|
||||
@click=${this._viewDetail}
|
||||
type="button"
|
||||
.label=${
|
||||
this.hass?.localize("ui.panel.lovelace.editor.error_section.title") ??
|
||||
""
|
||||
this._localize?.("ui.panel.lovelace.editor.error_section.title") ?? ""
|
||||
}
|
||||
>
|
||||
<ha-svg-icon slot="icon" .path=${mdiAlertCircle}></ha-svg-icon>
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { css, html, LitElement, nothing, type PropertyValues } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { computeCssColor } from "../../../common/color/compute-color";
|
||||
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-badge";
|
||||
import "../../../components/ha-icon";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
|
||||
import { NavigationPathInfoController } from "../../../data/navigation-path-controller";
|
||||
import { ServiceInfoController } from "../../../data/service-info-controller";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
import { getShortcutCardDefaults } from "../cards/hui-shortcut-card-defaults";
|
||||
import { actionHandler } from "../common/directives/action-handler-directive";
|
||||
import { handleAction } from "../common/handle-action";
|
||||
import { hasAction } from "../common/has-action";
|
||||
import type { LovelaceBadge, LovelaceBadgeEditor } from "../types";
|
||||
import type { ShortcutBadgeConfig } from "./types";
|
||||
@@ -33,10 +34,12 @@ export class HuiShortcutBadge extends LitElement implements LovelaceBadge {
|
||||
};
|
||||
}
|
||||
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@state() private _config?: ShortcutBadgeConfig;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
private _navInfo = new NavigationPathInfoController(this);
|
||||
|
||||
private _serviceInfo = new ServiceInfoController(this);
|
||||
@@ -65,7 +68,10 @@ export class HuiShortcutBadge extends LitElement implements LovelaceBadge {
|
||||
}
|
||||
|
||||
private _handleAction(ev: ActionHandlerEvent) {
|
||||
handleAction(this, this.hass!, this._config!, ev.detail.action!);
|
||||
fireEvent(this, "hass-action", {
|
||||
config: this._config!,
|
||||
action: ev.detail.action,
|
||||
});
|
||||
}
|
||||
|
||||
private get _hasAction() {
|
||||
@@ -77,12 +83,12 @@ export class HuiShortcutBadge extends LitElement implements LovelaceBadge {
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this._config || !this.hass) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const defaults = getShortcutCardDefaults(
|
||||
this.hass.localize,
|
||||
this._localize,
|
||||
this._config.tap_action,
|
||||
this._navInfo.info,
|
||||
this._serviceInfo.info
|
||||
@@ -103,7 +109,7 @@ export class HuiShortcutBadge extends LitElement implements LovelaceBadge {
|
||||
.iconOnly=${!text}
|
||||
.accessibleLabel=${
|
||||
defaults.label ||
|
||||
this.hass.localize("ui.panel.lovelace.editor.badge.shortcut.name")
|
||||
this._localize("ui.panel.lovelace.editor.badge.shortcut.name")
|
||||
}
|
||||
style=${styleMap(style)}
|
||||
@action=${this._handleAction}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import type { TemplateResult } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-card";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
import "../../config/logs/error-log-card";
|
||||
import type { LovelaceCard } from "../types";
|
||||
|
||||
@customElement("hui-recovery-mode-card")
|
||||
export class HuiRecoveryModeCard extends LitElement implements LovelaceCard {
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
public getCardSize(): number {
|
||||
return 3;
|
||||
@@ -21,14 +22,12 @@ export class HuiRecoveryModeCard extends LitElement implements LovelaceCard {
|
||||
protected render(): TemplateResult {
|
||||
return html`
|
||||
<ha-card
|
||||
.header=${this.hass!.localize(
|
||||
.header=${this._localize(
|
||||
"ui.panel.lovelace.cards.recovery-mode.header"
|
||||
)}
|
||||
>
|
||||
<div class="card-content">
|
||||
${this.hass!.localize(
|
||||
"ui.panel.lovelace.cards.recovery-mode.description"
|
||||
)}
|
||||
${this._localize("ui.panel.lovelace.cards.recovery-mode.description")}
|
||||
</div>
|
||||
<error-log-card provider="core"></error-log-card>
|
||||
</ha-card>
|
||||
|
||||
@@ -286,7 +286,7 @@ export class HuiTileCard extends LitElement implements LovelaceCard {
|
||||
};
|
||||
|
||||
const imageUrl = this._config.show_entity_picture
|
||||
? getTileImageUrl(this.hass, stateObj)
|
||||
? getTileImageUrl(this.hass.hassUrl, stateObj)
|
||||
: undefined;
|
||||
|
||||
const featurePosition = this._featurePosition(this._config);
|
||||
|
||||
@@ -47,7 +47,7 @@ export const getTileIconActionConfig = (
|
||||
});
|
||||
|
||||
export const getTileImageUrl = (
|
||||
connection: Pick<HomeAssistantConnection, "hassUrl">,
|
||||
hassUrl: HomeAssistantConnection["hassUrl"],
|
||||
stateObj: HassEntity,
|
||||
size = 80
|
||||
): string | undefined => {
|
||||
@@ -59,7 +59,7 @@ export const getTileImageUrl = (
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const imageUrl = connection.hassUrl(entityPicture);
|
||||
const imageUrl = hassUrl(entityPicture);
|
||||
|
||||
return computeDomain(stateObj.entity_id) === "camera"
|
||||
? cameraUrlWithWidthHeight(imageUrl, size, size)
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
|
||||
import type {
|
||||
HassConfig,
|
||||
HassEntities,
|
||||
HassEntity,
|
||||
} from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import {
|
||||
@@ -11,7 +15,10 @@ import {
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { DOMAINS_INPUT_ROW } from "../../../common/const";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import {
|
||||
consume,
|
||||
ContextSubscriptionController,
|
||||
} from "../../../common/decorators/consume";
|
||||
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../common/decorators/transform";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
@@ -21,10 +28,13 @@ import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/entity/state-badge";
|
||||
import "../../../components/ha-relative-time";
|
||||
import "../../../components/ha-tooltip";
|
||||
import { configContext, formattersContext } from "../../../data/context";
|
||||
import {
|
||||
configContext,
|
||||
formattersContext,
|
||||
statesContext,
|
||||
} from "../../../data/context";
|
||||
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
|
||||
import type {
|
||||
HomeAssistant,
|
||||
HomeAssistantConfig,
|
||||
HomeAssistantFormatters,
|
||||
} from "../../../types";
|
||||
@@ -36,9 +46,6 @@ import "../../../state-display/state-display";
|
||||
|
||||
@customElement("hui-generic-entity-row")
|
||||
export class HuiGenericEntityRow extends LitElement {
|
||||
// Fallback for custom rows that pass `hass` instead of `stateObj`
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public stateObj?: HassEntity;
|
||||
|
||||
@property({ attribute: false }) public config?: EntitiesCardEntityConfig;
|
||||
@@ -70,6 +77,13 @@ export class HuiGenericEntityRow extends LitElement {
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
private _formatters?: HomeAssistantFormatters;
|
||||
|
||||
// Custom rows may pass only `config`; built-in rows pass `stateObj`.
|
||||
@state() private _fallbackStateObj?: HassEntity;
|
||||
|
||||
private _states?: HassEntities | null;
|
||||
|
||||
private _statesController?: ContextSubscriptionController<HassEntities>;
|
||||
|
||||
@query(".row > slot") private _controlSlot?: HTMLSlotElement;
|
||||
|
||||
private _pressedControl = false;
|
||||
@@ -83,9 +97,7 @@ export class HuiGenericEntityRow extends LitElement {
|
||||
) {
|
||||
return nothing;
|
||||
}
|
||||
const stateObj =
|
||||
this.stateObj ??
|
||||
(this.config.entity ? this.hass?.states[this.config.entity] : undefined);
|
||||
const stateObj = this.stateObj ?? this._fallbackStateObj;
|
||||
|
||||
if (!stateObj) {
|
||||
return html`
|
||||
@@ -175,6 +187,34 @@ export class HuiGenericEntityRow extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>): void {
|
||||
super.willUpdate(changedProps);
|
||||
const needsFallback = !this.stateObj && Boolean(this.config?.entity);
|
||||
if (needsFallback && !this._statesController) {
|
||||
this._statesController = new ContextSubscriptionController(
|
||||
this,
|
||||
statesContext,
|
||||
(states) => {
|
||||
this._states = states;
|
||||
this._fallbackStateObj = this._pickFallbackStateObj();
|
||||
}
|
||||
);
|
||||
} else if (!needsFallback && this._statesController) {
|
||||
this._statesController.hostDisconnected();
|
||||
this.removeController(this._statesController);
|
||||
this._statesController = undefined;
|
||||
this._states = undefined;
|
||||
this._fallbackStateObj = undefined;
|
||||
} else if (needsFallback && changedProps.has("config")) {
|
||||
this._fallbackStateObj = this._pickFallbackStateObj();
|
||||
}
|
||||
}
|
||||
|
||||
private _pickFallbackStateObj(): HassEntity | undefined {
|
||||
const entityId = this.config?.entity;
|
||||
return entityId ? this._states?.[entityId] : undefined;
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues<this>): void {
|
||||
super.updated(changedProps);
|
||||
this.toggleAttribute(
|
||||
|
||||
@@ -111,7 +111,6 @@ export class HuiBadgeSuggestionPicker extends LitElement {
|
||||
<div class=${classMap({ sidebar: true, hidden: !showTree })}>
|
||||
<hui-suggestion-entity-tree
|
||||
class="tree"
|
||||
.hass=${this.hass}
|
||||
.selectedEntityId=${this._entityId}
|
||||
@entity-picked=${this._handleEntityPicked}
|
||||
></hui-suggestion-entity-tree>
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { mdiDragHorizontalVariant } from "@mdi/js";
|
||||
import type { CSSResultGroup } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import { repeat } from "lit/directives/repeat";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-button";
|
||||
import "../../../../components/ha-dialog";
|
||||
import "../../../../components/ha-dialog-footer";
|
||||
import "../../../../components/ha-sortable";
|
||||
import "../../../../components/ha-svg-icon";
|
||||
import { haStyleDialog } from "../../../../resources/styles";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type {
|
||||
FavoriteCardItem,
|
||||
ReorderFavoriteCardsDialogParams,
|
||||
@@ -19,7 +20,7 @@ import type {
|
||||
|
||||
@customElement("hui-dialog-reorder-favorite-cards")
|
||||
export class HuiDialogReorderFavoriteCards extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _params?: ReorderFavoriteCardsDialogParams;
|
||||
|
||||
@@ -54,7 +55,7 @@ export class HuiDialogReorderFavoriteCards extends LitElement {
|
||||
return html`
|
||||
<ha-dialog
|
||||
.open=${this._open}
|
||||
header-title=${this.hass.localize(
|
||||
header-title=${this._localize(
|
||||
"ui.panel.lovelace.editor.card.generic.reorder_favorites"
|
||||
)}
|
||||
@closed=${this._dialogClosed}
|
||||
@@ -79,7 +80,7 @@ export class HuiDialogReorderFavoriteCards extends LitElement {
|
||||
</ha-sortable>
|
||||
<ha-dialog-footer slot="footer">
|
||||
<ha-button slot="primaryAction" @click=${this.closeDialog}>
|
||||
${this.hass.localize("ui.common.close")}
|
||||
${this._localize("ui.common.close")}
|
||||
</ha-button>
|
||||
</ha-dialog-footer>
|
||||
</ha-dialog>
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import type { PropertyValues, TemplateResult } from "lit";
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { HassEntities } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import { transform } from "../../../../common/decorators/transform";
|
||||
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import { computeDomain } from "../../../../common/entity/compute_domain";
|
||||
@@ -19,8 +23,14 @@ import type {
|
||||
} from "../../../../components/data-table/ha-data-table";
|
||||
import "../../../../components/entity/state-badge";
|
||||
import "../../../../components/ha-relative-time";
|
||||
import {
|
||||
configContext,
|
||||
internationalizationContext,
|
||||
registriesContext,
|
||||
statesContext,
|
||||
} from "../../../../data/context";
|
||||
import { domainToName } from "../../../../data/integration";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type { HomeAssistant, HomeAssistantConfig } from "../../../../types";
|
||||
|
||||
const ENTITY_ID_STYLE = styleMap({
|
||||
fontFamily: "var(--ha-font-family-code)",
|
||||
@@ -42,15 +52,32 @@ interface EntityPickerTableRowData extends DataTableRowData {
|
||||
|
||||
@customElement("hui-entity-picker-table")
|
||||
export class HuiEntityPickerTable extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ type: Boolean }) public narrow = false;
|
||||
|
||||
@property({ type: Array }) public entities?: string[];
|
||||
|
||||
@state()
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
private _states?: HassEntities;
|
||||
|
||||
@state()
|
||||
@consume({ context: registriesContext, subscribe: true })
|
||||
private _registries!: ContextType<typeof registriesContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: ContextType<typeof internationalizationContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, boolean>({
|
||||
transformer: (value) => Boolean(value?.userData?.showEntityIdPicker),
|
||||
})
|
||||
private _showEntityId = false;
|
||||
|
||||
protected firstUpdated(_changedProperties: PropertyValues<this>): void {
|
||||
super.firstUpdated(_changedProperties);
|
||||
this.hass.loadBackendTranslation("title");
|
||||
this._i18n.loadBackendTranslation("title");
|
||||
}
|
||||
|
||||
private _data = memoizeOne(
|
||||
@@ -93,32 +120,38 @@ export class HuiEntityPickerTable extends LitElement {
|
||||
)
|
||||
);
|
||||
|
||||
protected render(): TemplateResult {
|
||||
protected render() {
|
||||
if (!this._states) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const data = this._data(
|
||||
this.hass.states,
|
||||
this.hass.entities,
|
||||
this.hass.devices,
|
||||
this.hass.areas,
|
||||
this.hass.floors,
|
||||
this.hass.localize,
|
||||
this._states,
|
||||
this._registries.entities,
|
||||
this._registries.devices,
|
||||
this._registries.areas,
|
||||
this._registries.floors,
|
||||
this._i18n.localize,
|
||||
this.entities
|
||||
);
|
||||
|
||||
const showEntityId = Boolean(this.hass.userData?.showEntityIdPicker);
|
||||
|
||||
const columns = this._columns(this.narrow, showEntityId);
|
||||
const columns = this._columns(
|
||||
this.narrow,
|
||||
this._showEntityId,
|
||||
this._i18n.localize
|
||||
);
|
||||
|
||||
return html`
|
||||
<ha-data-table
|
||||
class=${showEntityId ? "show-entity-id" : ""}
|
||||
class=${this._showEntityId ? "show-entity-id" : ""}
|
||||
selectable
|
||||
.id=${"entity_id"}
|
||||
.columns=${columns}
|
||||
.data=${data}
|
||||
.searchLabel=${this.hass.localize(
|
||||
.searchLabel=${this._i18n.localize(
|
||||
"ui.panel.lovelace.unused_entities.search"
|
||||
)}
|
||||
.noDataText=${this.hass.localize(
|
||||
.noDataText=${this._i18n.localize(
|
||||
"ui.panel.lovelace.unused_entities.no_data"
|
||||
)}
|
||||
@selection-changed=${this._handleSelectionChanged}
|
||||
@@ -126,118 +159,116 @@ export class HuiEntityPickerTable extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private _columns = memoizeOne((narrow: boolean, showEntityId: boolean) => {
|
||||
const columns: DataTableColumnContainer = {
|
||||
icon: {
|
||||
title: "",
|
||||
label: this.hass!.localize(
|
||||
"ui.panel.lovelace.unused_entities.state_icon"
|
||||
),
|
||||
type: "icon",
|
||||
template: (entity) => html`
|
||||
<state-badge
|
||||
@click=${this._handleEntityClicked}
|
||||
.stateObj=${entity.stateObj}
|
||||
></state-badge>
|
||||
`,
|
||||
},
|
||||
name: {
|
||||
title: this.hass!.localize("ui.panel.lovelace.unused_entities.entity"),
|
||||
private _columns = memoizeOne(
|
||||
(narrow: boolean, showEntityId: boolean, localize: LocalizeFunc) => {
|
||||
const columns: DataTableColumnContainer = {
|
||||
icon: {
|
||||
title: "",
|
||||
label: localize("ui.panel.lovelace.unused_entities.state_icon"),
|
||||
type: "icon",
|
||||
template: (entity) => html`
|
||||
<state-badge
|
||||
@click=${this._handleEntityClicked}
|
||||
.stateObj=${entity.stateObj}
|
||||
></state-badge>
|
||||
`,
|
||||
},
|
||||
name: {
|
||||
title: localize("ui.panel.lovelace.unused_entities.entity"),
|
||||
sortable: true,
|
||||
filterable: true,
|
||||
flex: 2,
|
||||
main: true,
|
||||
direction: "asc",
|
||||
template: (entity: any) => {
|
||||
const { primary, secondary } = computeEntityPickerDisplay(
|
||||
{
|
||||
entities: this._registries.entities,
|
||||
devices: this._registries.devices,
|
||||
areas: this._registries.areas,
|
||||
floors: this._registries.floors,
|
||||
language: this._i18n.language,
|
||||
translationMetadata: this._i18n.translationMetadata,
|
||||
},
|
||||
entity.stateObj
|
||||
);
|
||||
return html`
|
||||
<div @click=${this._handleEntityClicked} style="cursor: pointer;">
|
||||
${primary}
|
||||
${
|
||||
secondary
|
||||
? html`<div class="secondary">${secondary}</div>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
narrow && showEntityId
|
||||
? html`
|
||||
<div class="secondary" style=${ENTITY_ID_STYLE}>
|
||||
${entity.entity_id}
|
||||
</div>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
`;
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
columns.entity_name = {
|
||||
title: "entity_name",
|
||||
filterable: true,
|
||||
hidden: true,
|
||||
};
|
||||
|
||||
columns.device_name = {
|
||||
title: "device_name",
|
||||
filterable: true,
|
||||
hidden: true,
|
||||
};
|
||||
|
||||
columns.parent_device_name = {
|
||||
title: "parent_device_name",
|
||||
filterable: true,
|
||||
hidden: true,
|
||||
};
|
||||
|
||||
columns.area_name = {
|
||||
title: "area_name",
|
||||
filterable: true,
|
||||
hidden: true,
|
||||
};
|
||||
|
||||
columns.entity_id = {
|
||||
title: localize("ui.panel.lovelace.unused_entities.entity_id"),
|
||||
sortable: true,
|
||||
filterable: true,
|
||||
flex: 2,
|
||||
main: true,
|
||||
direction: "asc",
|
||||
template: (entity: any) => {
|
||||
const { primary, secondary } = computeEntityPickerDisplay(
|
||||
{
|
||||
entities: this.hass!.entities,
|
||||
devices: this.hass!.devices,
|
||||
areas: this.hass!.areas,
|
||||
floors: this.hass!.floors,
|
||||
language: this.hass!.language,
|
||||
translationMetadata: this.hass!.translationMetadata,
|
||||
},
|
||||
entity.stateObj
|
||||
);
|
||||
return html`
|
||||
<div @click=${this._handleEntityClicked} style="cursor: pointer;">
|
||||
${primary}
|
||||
${
|
||||
secondary
|
||||
? html`<div class="secondary">${secondary}</div>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
narrow && showEntityId
|
||||
? html`
|
||||
<div class="secondary" style=${ENTITY_ID_STYLE}>
|
||||
${entity.entity_id}
|
||||
</div>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
`;
|
||||
},
|
||||
},
|
||||
};
|
||||
hidden: narrow || !showEntityId,
|
||||
};
|
||||
|
||||
columns.entity_name = {
|
||||
title: "entity_name",
|
||||
filterable: true,
|
||||
hidden: true,
|
||||
};
|
||||
columns.domain_name = {
|
||||
title: localize("ui.panel.lovelace.unused_entities.domain"),
|
||||
sortable: true,
|
||||
filterable: true,
|
||||
hidden: narrow || showEntityId,
|
||||
};
|
||||
|
||||
columns.device_name = {
|
||||
title: "device_name",
|
||||
filterable: true,
|
||||
hidden: true,
|
||||
};
|
||||
columns.last_changed = {
|
||||
title: localize("ui.panel.lovelace.unused_entities.last_changed"),
|
||||
type: "numeric",
|
||||
sortable: true,
|
||||
hidden: narrow,
|
||||
template: (entity) => html`
|
||||
<ha-relative-time
|
||||
.datetime=${entity.last_changed}
|
||||
capitalize
|
||||
></ha-relative-time>
|
||||
`,
|
||||
};
|
||||
|
||||
columns.parent_device_name = {
|
||||
title: "parent_device_name",
|
||||
filterable: true,
|
||||
hidden: true,
|
||||
};
|
||||
|
||||
columns.area_name = {
|
||||
title: "area_name",
|
||||
filterable: true,
|
||||
hidden: true,
|
||||
};
|
||||
|
||||
columns.entity_id = {
|
||||
title: this.hass!.localize("ui.panel.lovelace.unused_entities.entity_id"),
|
||||
sortable: true,
|
||||
filterable: true,
|
||||
hidden: narrow || !showEntityId,
|
||||
};
|
||||
|
||||
columns.domain_name = {
|
||||
title: this.hass!.localize("ui.panel.lovelace.unused_entities.domain"),
|
||||
sortable: true,
|
||||
filterable: true,
|
||||
hidden: narrow || showEntityId,
|
||||
};
|
||||
|
||||
columns.last_changed = {
|
||||
title: this.hass!.localize(
|
||||
"ui.panel.lovelace.unused_entities.last_changed"
|
||||
),
|
||||
type: "numeric",
|
||||
sortable: true,
|
||||
hidden: narrow,
|
||||
template: (entity) => html`
|
||||
<ha-relative-time
|
||||
.datetime=${entity.last_changed}
|
||||
capitalize
|
||||
></ha-relative-time>
|
||||
`,
|
||||
};
|
||||
|
||||
return columns;
|
||||
});
|
||||
return columns;
|
||||
}
|
||||
);
|
||||
|
||||
private _handleSelectionChanged(
|
||||
ev: HASSDomEvent<SelectionChangedEvent>
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
mdiMagnify,
|
||||
mdiTextureBox,
|
||||
} from "@mdi/js";
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { HassEntities } 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";
|
||||
@@ -18,6 +20,7 @@ import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import { mainWindow } from "../../../../common/dom/get_main_window";
|
||||
import { computeEntityPickerDisplay } from "../../../../common/entity/compute_entity_name_display";
|
||||
import { ignoreRepeatedActivation } from "../../../../common/keyboard/ignore-repeated-activation";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import { computeRTL } from "../../../../common/util/compute_rtl";
|
||||
import { debounce } from "../../../../common/util/debounce";
|
||||
import "../../../../components/entity/state-badge";
|
||||
@@ -35,10 +38,14 @@ import type { HaListBase } from "../../../../components/list/ha-list-base";
|
||||
import "../../../../components/list/ha-list-virtualized";
|
||||
import type { HaListVirtualizedItem } from "../../../../components/list/ha-list-virtualized";
|
||||
import type { ConfigEntry } from "../../../../data/config_entries";
|
||||
import { configEntriesContext } from "../../../../data/context";
|
||||
import {
|
||||
configEntriesContext,
|
||||
internationalizationContext,
|
||||
registriesContext,
|
||||
statesContext,
|
||||
} from "../../../../data/context";
|
||||
import { haStyleScrollbar } from "../../../../resources/styles";
|
||||
import { loadVirtualizer } from "../../../../resources/virtualizer";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type {
|
||||
AreaNode,
|
||||
DeviceNode,
|
||||
@@ -87,10 +94,19 @@ const SELECTED_SEARCH_ROW_STYLE = {
|
||||
*/
|
||||
@customElement("hui-suggestion-entity-tree")
|
||||
export class HuiSuggestionEntityTree extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public selectedEntityId?: string;
|
||||
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
private _states?: HassEntities;
|
||||
|
||||
@state()
|
||||
@consume({ context: registriesContext, subscribe: true })
|
||||
private _registries!: ContextType<typeof registriesContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: ContextType<typeof internationalizationContext>;
|
||||
|
||||
@state() private _filter = "";
|
||||
|
||||
@state() private _expanded: Record<string, boolean> = {};
|
||||
@@ -105,10 +121,10 @@ export class HuiSuggestionEntityTree extends LitElement {
|
||||
})
|
||||
private _configEntryLookup?: Record<string, ConfigEntry>;
|
||||
|
||||
// Captured from the load promise to avoid racing parent hass propagation.
|
||||
@state() private _domainLocalize?: HomeAssistant["localize"];
|
||||
// Captured from the load promise to avoid racing the context update.
|
||||
@state() private _domainLocalize?: LocalizeFunc;
|
||||
|
||||
// Built once; rebuilding the structure and Fuse index on each hass tick
|
||||
// Built once; rebuilding the structure and Fuse index on each state change
|
||||
// would freeze the picker on large registries.
|
||||
@state() private _tree?: EntityTree;
|
||||
|
||||
@@ -147,8 +163,8 @@ export class HuiSuggestionEntityTree extends LitElement {
|
||||
}
|
||||
|
||||
private async _loadDomainTranslations() {
|
||||
if (!this.hass) return;
|
||||
this._domainLocalize = await this.hass.loadBackendTranslation("title");
|
||||
if (!this._i18n) return;
|
||||
this._domainLocalize = await this._i18n.loadBackendTranslation("title");
|
||||
}
|
||||
|
||||
public disconnectedCallback(): void {
|
||||
@@ -159,7 +175,7 @@ export class HuiSuggestionEntityTree extends LitElement {
|
||||
}
|
||||
|
||||
private _deviceDomain(deviceId: string): string | undefined {
|
||||
const device = this.hass?.devices[deviceId];
|
||||
const device = this._registries.devices?.[deviceId];
|
||||
if (!device?.primary_config_entry) return undefined;
|
||||
return this._configEntryLookup?.[device.primary_config_entry]?.domain;
|
||||
}
|
||||
@@ -171,14 +187,22 @@ export class HuiSuggestionEntityTree extends LitElement {
|
||||
if (!this.hasUpdated) {
|
||||
loadVirtualizer();
|
||||
}
|
||||
if (!this._tree && this.hass && this._domainLocalize) {
|
||||
if (
|
||||
!this._tree &&
|
||||
this._states &&
|
||||
this._registries.entities &&
|
||||
this._registries.devices &&
|
||||
this._registries.areas &&
|
||||
this._registries.floors &&
|
||||
this._domainLocalize
|
||||
) {
|
||||
this._tree = buildEntityTree({
|
||||
states: this.hass.states,
|
||||
entities: this.hass.entities,
|
||||
devices: this.hass.devices,
|
||||
areas: this.hass.areas,
|
||||
floors: this.hass.floors,
|
||||
language: this.hass.locale?.language,
|
||||
states: this._states,
|
||||
entities: this._registries.entities,
|
||||
devices: this._registries.devices,
|
||||
areas: this._registries.areas,
|
||||
floors: this._registries.floors,
|
||||
language: this._i18n.locale?.language,
|
||||
localize: this._domainLocalize,
|
||||
});
|
||||
this._fuseIndex = buildSearchIndex(this._tree.searchableEntities);
|
||||
@@ -193,13 +217,11 @@ export class HuiSuggestionEntityTree extends LitElement {
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.hass) return nothing;
|
||||
|
||||
return html`
|
||||
<ha-input-search
|
||||
appearance="outlined"
|
||||
.value=${this._filter}
|
||||
.placeholder=${this.hass.localize(
|
||||
.placeholder=${this._i18n.localize(
|
||||
"ui.panel.lovelace.editor.cardpicker.search_entities"
|
||||
)}
|
||||
@input=${this._handleFilterChange}
|
||||
@@ -236,7 +258,7 @@ export class HuiSuggestionEntityTree extends LitElement {
|
||||
tree.floors.length || tree.otherAreas.length
|
||||
? html`
|
||||
<ha-section-title>
|
||||
${this.hass.localize("ui.panel.lovelace.editor.cardpicker.home")}
|
||||
${this._i18n.localize("ui.panel.lovelace.editor.cardpicker.home")}
|
||||
</ha-section-title>
|
||||
${repeat(
|
||||
tree.floors,
|
||||
@@ -255,7 +277,7 @@ export class HuiSuggestionEntityTree extends LitElement {
|
||||
: this._renderFloor(
|
||||
{
|
||||
id: OTHER_AREAS_ID,
|
||||
name: this.hass.localize(
|
||||
name: this._i18n.localize(
|
||||
"ui.panel.lovelace.editor.cardpicker.other_areas"
|
||||
),
|
||||
icon: null,
|
||||
@@ -273,7 +295,7 @@ export class HuiSuggestionEntityTree extends LitElement {
|
||||
tree.unassignedSections.length
|
||||
? html`
|
||||
<ha-section-title>
|
||||
${this.hass.localize(
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.editor.cardpicker.unassigned"
|
||||
)}
|
||||
</ha-section-title>
|
||||
@@ -305,12 +327,12 @@ export class HuiSuggestionEntityTree extends LitElement {
|
||||
<div class="empty">
|
||||
<ha-svg-icon .path=${mdiMagnify}></ha-svg-icon>
|
||||
<h2>
|
||||
${this.hass.localize(
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.editor.cardpicker.no_search_results_title"
|
||||
)}
|
||||
</h2>
|
||||
<p>
|
||||
${this.hass.localize(
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.editor.cardpicker.no_search_results_description"
|
||||
)}
|
||||
</p>
|
||||
@@ -340,11 +362,11 @@ export class HuiSuggestionEntityTree extends LitElement {
|
||||
item: SearchableEntity,
|
||||
index: number
|
||||
): TemplateResult => {
|
||||
const stateObj = this.hass.states[item.id];
|
||||
const stateObj = this._states?.[item.id];
|
||||
const selected = this.selectedEntityId === item.id;
|
||||
const rtl = computeRTL(
|
||||
this.hass.language,
|
||||
this.hass.translationMetadata.translations
|
||||
this._i18n.language,
|
||||
this._i18n.translationMetadata.translations
|
||||
);
|
||||
const separator = rtl ? " ◂ " : " ▸ ";
|
||||
const secondary = [item.area, item.parentDevice, item.device]
|
||||
@@ -614,17 +636,17 @@ export class HuiSuggestionEntityTree extends LitElement {
|
||||
}
|
||||
|
||||
private _renderEntity(entityId: string, depthClass: string): TemplateResult {
|
||||
const stateObj = this.hass.states[entityId];
|
||||
const stateObj = this._states?.[entityId];
|
||||
const selected = this.selectedEntityId === entityId;
|
||||
const name = stateObj
|
||||
? computeEntityPickerDisplay(
|
||||
{
|
||||
entities: this.hass.entities,
|
||||
devices: this.hass.devices,
|
||||
areas: this.hass.areas,
|
||||
floors: this.hass.floors,
|
||||
language: this.hass.language,
|
||||
translationMetadata: this.hass.translationMetadata,
|
||||
entities: this._registries.entities,
|
||||
devices: this._registries.devices,
|
||||
areas: this._registries.areas,
|
||||
floors: this._registries.floors,
|
||||
language: this._i18n.language,
|
||||
translationMetadata: this._i18n.translationMetadata,
|
||||
},
|
||||
stateObj
|
||||
).primary
|
||||
|
||||
@@ -111,7 +111,6 @@ export class HuiSuggestionPicker extends LitElement {
|
||||
<div class=${classMap({ sidebar: true, hidden: !showTree })}>
|
||||
<hui-suggestion-entity-tree
|
||||
class="tree"
|
||||
.hass=${this.hass}
|
||||
.selectedEntityId=${this._entityId}
|
||||
@entity-picked=${this._handleEntityPicked}
|
||||
></hui-suggestion-entity-tree>
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
|
||||
import { html, LitElement } from "lit";
|
||||
import { property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { assert, literal, number, object, optional, string } from "superstruct";
|
||||
import { consume } from "../../../../../common/decorators/consume";
|
||||
import {
|
||||
consumeLocalize,
|
||||
preserveUnchangedEntityStatesRecord,
|
||||
} from "../../../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../../../common/decorators/transform";
|
||||
import { fireEvent } from "../../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../../common/translations/localize";
|
||||
import "../../../../../components/ha-form/ha-form";
|
||||
@@ -10,8 +16,9 @@ import type {
|
||||
SchemaUnion,
|
||||
HaFormSchema,
|
||||
} from "../../../../../components/ha-form/types";
|
||||
import { formattersContext, statesContext } from "../../../../../data/context";
|
||||
import { NON_NUMERIC_ATTRIBUTES } from "../../../../../data/entity/entity_attributes";
|
||||
import type { HomeAssistant } from "../../../../../types";
|
||||
import type { HomeAssistantFormatters } from "../../../../../types";
|
||||
import type {
|
||||
NumericStateCondition,
|
||||
StateCondition,
|
||||
@@ -42,8 +49,6 @@ interface NumericStateConditionData {
|
||||
// Base for the entity-filter (no-entity) numeric_state editor. Not registered
|
||||
// itself; dashboard editing uses the automation condition editor.
|
||||
export class HaCardConditionNumericState extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public condition!: NumericStateCondition;
|
||||
|
||||
@property({ type: Boolean }) public disabled = false;
|
||||
@@ -52,6 +57,38 @@ export class HaCardConditionNumericState extends LitElement {
|
||||
@consume({ context: conditionsEntityContext, subscribe: true })
|
||||
private _entityContext?: ConditionsEntityContext;
|
||||
|
||||
@state()
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
@transform<HassEntities, Record<string, HassEntity>>({
|
||||
transformer: function (this: HaCardConditionNumericState, states) {
|
||||
const ctx = this._entityContext;
|
||||
const next: Record<string, HassEntity> = {};
|
||||
for (const id of [
|
||||
this.condition?.entity,
|
||||
ctx?.mode === "current" ? ctx.entityId : undefined,
|
||||
]) {
|
||||
if (id && states?.[id]) {
|
||||
next[id] = states[id];
|
||||
}
|
||||
}
|
||||
return preserveUnchangedEntityStatesRecord(this._stateObjs, next);
|
||||
},
|
||||
watch: ["condition", "_entityContext"],
|
||||
})
|
||||
private _stateObjs?: Record<string, HassEntity>;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
@transform<
|
||||
HomeAssistantFormatters,
|
||||
HomeAssistantFormatters["formatEntityName"]
|
||||
>({
|
||||
transformer: ({ formatEntityName }) => formatEntityName,
|
||||
})
|
||||
private _formatEntityName?: HomeAssistantFormatters["formatEntityName"];
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
public static get defaultConfig(): NumericStateCondition {
|
||||
return { condition: "numeric_state", entity: "" };
|
||||
}
|
||||
@@ -135,13 +172,13 @@ export class HaCardConditionNumericState extends LitElement {
|
||||
? currentEntityId
|
||||
: this.condition.entity;
|
||||
const stateObj = selectedEntityId
|
||||
? this.hass.states[selectedEntityId]
|
||||
? this._stateObjs?.[selectedEntityId]
|
||||
: undefined;
|
||||
const currentStateObj = currentEntityId
|
||||
? this.hass.states[currentEntityId]
|
||||
? this._stateObjs?.[currentEntityId]
|
||||
: undefined;
|
||||
const currentEntityName = currentStateObj
|
||||
? this.hass.formatEntityName(currentStateObj)
|
||||
? this._formatEntityName?.(currentStateObj)
|
||||
: undefined;
|
||||
|
||||
const unit = this.condition.attribute
|
||||
@@ -155,10 +192,9 @@ export class HaCardConditionNumericState extends LitElement {
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${this._schema(
|
||||
this.hass.localize,
|
||||
this._localize,
|
||||
currentEntityId,
|
||||
currentEntityName,
|
||||
useCurrentEntity,
|
||||
@@ -196,14 +232,14 @@ export class HaCardConditionNumericState extends LitElement {
|
||||
): string => {
|
||||
switch (schema.name) {
|
||||
case "entity":
|
||||
return this.hass.localize("ui.components.entity.entity-picker.entity");
|
||||
return this._localize("ui.components.entity.entity-picker.entity");
|
||||
case "attribute":
|
||||
return this.hass.localize(
|
||||
return this._localize(
|
||||
"ui.panel.lovelace.editor.condition-editor.condition.numeric_state.attribute"
|
||||
);
|
||||
case "below":
|
||||
case "above":
|
||||
return this.hass.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.condition-editor.condition.numeric_state.${schema.name}`
|
||||
);
|
||||
default:
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { html, LitElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { getAllCombinations } from "../../../../../common/array/combinations";
|
||||
import { consumeLocalize } from "../../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../../common/translations/localize";
|
||||
import "../../../../../components/ha-form/ha-form";
|
||||
@@ -95,12 +96,12 @@ interface ScreenConditionData {
|
||||
|
||||
@customElement("ha-card-condition-screen")
|
||||
export class HaCardConditionScreen extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public condition!: ScreenCondition;
|
||||
|
||||
@property({ type: Boolean }) public disabled = false;
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
public static get defaultConfig(): ScreenCondition {
|
||||
return { condition: "screen", media_query: "" };
|
||||
}
|
||||
@@ -160,9 +161,8 @@ export class HaCardConditionScreen extends LitElement {
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${this._schema(this.hass.localize)}
|
||||
.schema=${this._schema(this._localize)}
|
||||
.disabled=${this.disabled}
|
||||
@value-changed=${this._valueChanged}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -189,7 +189,7 @@ export class HaCardConditionScreen extends LitElement {
|
||||
): string => {
|
||||
switch (schema.name) {
|
||||
case "breakpoints":
|
||||
return this.hass.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.condition-editor.condition.screen.${schema.name}`
|
||||
);
|
||||
default:
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
|
||||
import { html, LitElement } from "lit";
|
||||
import { property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { assert, literal, object, optional, string } from "superstruct";
|
||||
import { consume } from "../../../../../common/decorators/consume";
|
||||
import { consumeLocalize } from "../../../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../../../common/decorators/transform";
|
||||
import { fireEvent } from "../../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../../common/translations/localize";
|
||||
import "../../../../../components/ha-form/ha-form";
|
||||
@@ -10,8 +13,12 @@ import type {
|
||||
SchemaUnion,
|
||||
HaFormSchema,
|
||||
} from "../../../../../components/ha-form/types";
|
||||
import { formattersContext, statesContext } from "../../../../../data/context";
|
||||
import { STATE_CONDITION_HIDDEN_ATTRIBUTES } from "../../../../../data/entity/entity_attributes";
|
||||
import type { HomeAssistant } from "../../../../../types";
|
||||
import type {
|
||||
HomeAssistant,
|
||||
HomeAssistantFormatters,
|
||||
} from "../../../../../types";
|
||||
import type { StateCondition } from "../../../common/validate-condition";
|
||||
import type { ConditionsEntityContext } from "../context";
|
||||
import { conditionsEntityContext } from "../context";
|
||||
@@ -49,6 +56,29 @@ export class HaCardConditionState extends LitElement {
|
||||
@consume({ context: conditionsEntityContext, subscribe: true })
|
||||
private _entityContext?: ConditionsEntityContext;
|
||||
|
||||
@state()
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
@transform<HassEntities, HassEntity | undefined>({
|
||||
transformer: function (this: HaCardConditionState, states) {
|
||||
const ctx = this._entityContext;
|
||||
return ctx?.mode === "current" ? states?.[ctx.entityId] : undefined;
|
||||
},
|
||||
watch: ["_entityContext"],
|
||||
})
|
||||
private _currentStateObj?: HassEntity;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
@transform<
|
||||
HomeAssistantFormatters,
|
||||
HomeAssistantFormatters["formatEntityName"]
|
||||
>({
|
||||
transformer: ({ formatEntityName }) => formatEntityName,
|
||||
})
|
||||
private _formatEntityName?: HomeAssistantFormatters["formatEntityName"];
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
public static get defaultConfig(): StateCondition {
|
||||
return { condition: "state", entity: "", state: "" };
|
||||
}
|
||||
@@ -148,11 +178,8 @@ export class HaCardConditionState extends LitElement {
|
||||
const useCurrentEntity =
|
||||
currentEntityId !== undefined && !this.condition.entity;
|
||||
|
||||
const currentStateObj = currentEntityId
|
||||
? this.hass.states[currentEntityId]
|
||||
: undefined;
|
||||
const currentEntityName = currentStateObj
|
||||
? this.hass.formatEntityName(currentStateObj)
|
||||
const currentEntityName = this._currentStateObj
|
||||
? this._formatEntityName?.(this._currentStateObj)
|
||||
: undefined;
|
||||
|
||||
const data: StateConditionData = {
|
||||
@@ -167,7 +194,7 @@ export class HaCardConditionState extends LitElement {
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${this._schema(
|
||||
this.hass.localize,
|
||||
this._localize,
|
||||
currentEntityId,
|
||||
currentEntityName,
|
||||
useCurrentEntity,
|
||||
@@ -214,15 +241,13 @@ export class HaCardConditionState extends LitElement {
|
||||
): string => {
|
||||
switch (schema.name) {
|
||||
case "entity":
|
||||
return this.hass.localize("ui.components.entity.entity-picker.entity");
|
||||
return this._localize("ui.components.entity.entity-picker.entity");
|
||||
case "attribute":
|
||||
return this.hass.localize(
|
||||
return this._localize(
|
||||
"ui.panel.lovelace.editor.condition-editor.condition.state.attribute"
|
||||
);
|
||||
case "state":
|
||||
return this.hass.localize(
|
||||
"ui.components.entity.entity-state-picker.state"
|
||||
);
|
||||
return this._localize("ui.components.entity.entity-state-picker.state");
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { html, LitElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import {
|
||||
literal,
|
||||
array,
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
enums,
|
||||
} from "superstruct";
|
||||
import memoizeOne from "memoize-one";
|
||||
import type { HomeAssistant } from "../../../../../types";
|
||||
import { consumeLocalize } from "../../../../../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../../../../../common/translations/localize";
|
||||
import {
|
||||
WEEKDAY_SHORT_TO_LONG,
|
||||
@@ -33,12 +33,12 @@ const timeConditionStruct = object({
|
||||
|
||||
@customElement("ha-card-condition-time")
|
||||
export class HaCardConditionTime extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public condition!: TimeCondition;
|
||||
|
||||
@property({ type: Boolean }) public disabled = false;
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
public static get defaultConfig(): TimeCondition {
|
||||
return { condition: "time", after: "08:00", before: "17:00" };
|
||||
}
|
||||
@@ -71,10 +71,9 @@ export class HaCardConditionTime extends LitElement {
|
||||
protected render() {
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${this.condition}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
.schema=${this._schema(this.hass.localize)}
|
||||
.schema=${this._schema(this._localize)}
|
||||
.disabled=${this.disabled}
|
||||
@value-changed=${this._valueChanged}
|
||||
></ha-form>
|
||||
@@ -90,7 +89,7 @@ export class HaCardConditionTime extends LitElement {
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
): string =>
|
||||
this.hass.localize(
|
||||
this._localize(
|
||||
`ui.panel.lovelace.editor.condition-editor.condition.time.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { LitElement, css, html } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
@@ -7,6 +8,7 @@ import {
|
||||
arrayWith,
|
||||
arrayWithout,
|
||||
} from "../../../../../common/array/array-with";
|
||||
import { consume } from "../../../../../common/decorators/consume";
|
||||
import { fireEvent } from "../../../../../common/dom/fire_event";
|
||||
import { stringCompare } from "../../../../../common/string/compare";
|
||||
import "../../../../../components/item/ha-list-item-option";
|
||||
@@ -14,9 +16,12 @@ import type { HaListItemOption } from "../../../../../components/item/ha-list-it
|
||||
import "../../../../../components/list/ha-list-selectable";
|
||||
import type { HaListSelectable } from "../../../../../components/list/ha-list-selectable";
|
||||
import "../../../../../components/user/ha-user-badge";
|
||||
import {
|
||||
apiContext,
|
||||
internationalizationContext,
|
||||
} from "../../../../../data/context";
|
||||
import type { User } from "../../../../../data/user";
|
||||
import { fetchUsers } from "../../../../../data/user";
|
||||
import type { HomeAssistant } from "../../../../../types";
|
||||
import type { UserCondition } from "../../../common/validate-condition";
|
||||
|
||||
const userConditionStruct = object({
|
||||
@@ -26,7 +31,12 @@ const userConditionStruct = object({
|
||||
|
||||
@customElement("ha-card-condition-user")
|
||||
export class HaCardConditionUser extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: ContextType<typeof internationalizationContext>;
|
||||
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: ContextType<typeof apiContext>;
|
||||
|
||||
@property({ attribute: false }) public condition!: UserCondition;
|
||||
|
||||
@@ -42,10 +52,8 @@ export class HaCardConditionUser extends LitElement {
|
||||
return assert(condition, userConditionStruct);
|
||||
}
|
||||
|
||||
private _sortedUsers = memoizeOne((users: User[]) =>
|
||||
users.sort((a, b) =>
|
||||
stringCompare(a.name, b.name, this.hass.locale.language)
|
||||
)
|
||||
private _sortedUsers = memoizeOne((users: User[], language: string) =>
|
||||
users.sort((a, b) => stringCompare(a.name, b.name, language))
|
||||
);
|
||||
|
||||
protected async firstUpdated(changedProps: PropertyValues<this>) {
|
||||
@@ -54,7 +62,7 @@ export class HaCardConditionUser extends LitElement {
|
||||
}
|
||||
|
||||
private async _fetchUsers() {
|
||||
const users = await fetchUsers(this.hass.callWS);
|
||||
const users = await fetchUsers(this._api.callWS);
|
||||
this._users = users.filter((user) => !user.system_generated);
|
||||
}
|
||||
|
||||
@@ -64,13 +72,13 @@ export class HaCardConditionUser extends LitElement {
|
||||
return html`
|
||||
<ha-list-selectable
|
||||
multi
|
||||
aria-label=${this.hass.localize(
|
||||
aria-label=${this._i18n.localize(
|
||||
"ui.panel.lovelace.editor.condition-editor.condition.user.label"
|
||||
)}
|
||||
@ha-list-item-selected=${this._handleUserToggled}
|
||||
@ha-list-item-deselected=${this._handleUserToggled}
|
||||
>
|
||||
${this._sortedUsers(this._users).map(
|
||||
${this._sortedUsers(this._users, this._i18n.locale.language).map(
|
||||
(user) => html`
|
||||
<ha-list-item-option
|
||||
appearance="checkbox"
|
||||
|
||||
@@ -2,6 +2,10 @@ import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
@@ -10,7 +14,6 @@ import type {
|
||||
SchemaUnion,
|
||||
} from "../../../../components/ha-form/types";
|
||||
import { supportedAlarmModes } from "../../../../data/alarm_control_panel";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type {
|
||||
AlarmModesCardFeatureConfig,
|
||||
LovelaceCardFeatureContext,
|
||||
@@ -26,10 +29,16 @@ export class HuiAlarmModesCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
|
||||
private _stateObj?: HassEntity;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: AlarmModesCardFeatureConfig;
|
||||
|
||||
public setConfig(config: AlarmModesCardFeatureConfig): void {
|
||||
@@ -67,7 +76,7 @@ export class HuiAlarmModesCardFeatureEditor
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
@@ -76,15 +85,10 @@ export class HuiAlarmModesCardFeatureEditor
|
||||
customize_modes: this._config.modes !== undefined,
|
||||
};
|
||||
|
||||
const stateObj = this.context?.entity_id
|
||||
? this.hass.states[this.context?.entity_id]
|
||||
: undefined;
|
||||
|
||||
const schema = this._schema(this.hass.localize, stateObj);
|
||||
const schema = this._schema(this._localize, this._stateObj);
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -97,12 +101,10 @@ export class HuiAlarmModesCardFeatureEditor
|
||||
const { customize_modes, ...config } = ev.detail
|
||||
.value as AlarmModesCardFeatureData;
|
||||
|
||||
const stateObj = this.context?.entity_id
|
||||
? this.hass!.states[this.context?.entity_id]
|
||||
: undefined;
|
||||
|
||||
if (customize_modes && !config.modes) {
|
||||
config.modes = stateObj ? supportedAlarmModes(stateObj).reverse() : [];
|
||||
config.modes = this._stateObj
|
||||
? supportedAlarmModes(this._stateObj).reverse()
|
||||
: [];
|
||||
}
|
||||
if (!customize_modes && config.modes) {
|
||||
delete config.modes;
|
||||
@@ -117,7 +119,7 @@ export class HuiAlarmModesCardFeatureEditor
|
||||
switch (schema.name) {
|
||||
case "modes":
|
||||
case "customize_modes":
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.features.types.alarm-modes.${schema.name}`
|
||||
);
|
||||
default:
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { array, assert, assign, object, optional, string } from "superstruct";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import { supportsFeature } from "../../../../common/entity/supports-feature";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { SchemaUnion } from "../../../../components/ha-form/types";
|
||||
import { ALARM_MODES } from "../../../../data/alarm_control_panel";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import { statesContext } from "../../../../data/context";
|
||||
import {
|
||||
ALARM_MODE_STATE_MAP,
|
||||
DEFAULT_STATES,
|
||||
@@ -40,10 +46,19 @@ export class HuiAlarmPanelCardEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@state() private _config?: AlarmPanelCardConfig;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
|
||||
private _stateObj?: HassEntity;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
private _states?: ContextType<typeof statesContext>;
|
||||
|
||||
public setConfig(config: AlarmPanelCardConfig): void {
|
||||
assert(config, cardConfigStruct);
|
||||
this._config = config;
|
||||
@@ -93,22 +108,20 @@ export class HuiAlarmPanelCardEditor
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const stateObj = this.hass.states[this._config.entity];
|
||||
const defaultFilteredStates = filterSupportedAlarmStates(
|
||||
stateObj,
|
||||
this._stateObj,
|
||||
DEFAULT_STATES
|
||||
);
|
||||
const config = { states: defaultFilteredStates, ...this._config };
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${config}
|
||||
.schema=${this._schema(this.hass.localize, stateObj, config.states)}
|
||||
.schema=${this._schema(this._localize, this._stateObj, config.states)}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@value-changed=${this._valueChanged}
|
||||
></ha-form>
|
||||
@@ -126,7 +139,7 @@ export class HuiAlarmPanelCardEditor
|
||||
|
||||
// When changing entities, clear any states that the new entity does not support
|
||||
if (newConfig.states && newConfig.entity !== this._config?.entity) {
|
||||
const newStateObj = this.hass?.states[newConfig.entity];
|
||||
const newStateObj = this._states?.[newConfig.entity];
|
||||
if (newStateObj) {
|
||||
newConfig.states = filterSupportedAlarmStates(
|
||||
newStateObj,
|
||||
@@ -143,22 +156,18 @@ export class HuiAlarmPanelCardEditor
|
||||
) => {
|
||||
switch (schema.name) {
|
||||
case "entity":
|
||||
return this.hass!.localize(
|
||||
"ui.panel.lovelace.editor.card.generic.entity"
|
||||
);
|
||||
return this._localize("ui.panel.lovelace.editor.card.generic.entity");
|
||||
case "name":
|
||||
return this.hass!.localize(
|
||||
"ui.panel.lovelace.editor.card.generic.name"
|
||||
);
|
||||
return this._localize("ui.panel.lovelace.editor.card.generic.name");
|
||||
case "theme":
|
||||
return `${this.hass!.localize(
|
||||
return `${this._localize(
|
||||
"ui.panel.lovelace.editor.card.generic.theme"
|
||||
)} (${this.hass!.localize(
|
||||
)} (${this._localize(
|
||||
"ui.panel.lovelace.editor.card.config.optional"
|
||||
)})`;
|
||||
default:
|
||||
// "states"
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
"ui.panel.lovelace.editor.card.alarm-panel.available_states"
|
||||
);
|
||||
}
|
||||
|
||||
+53
-23
@@ -1,9 +1,17 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import { mdiDragHorizontalVariant } from "@mdi/js";
|
||||
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { repeat } from "lit/directives/repeat";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import {
|
||||
consumeEntityStates,
|
||||
consumeLocalize,
|
||||
} from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-area-controls-picker";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type {
|
||||
@@ -13,6 +21,11 @@ import type {
|
||||
import "../../../../components/chips/ha-input-chip";
|
||||
import "../../../../components/ha-sortable";
|
||||
import "../../../../components/ha-svg-icon";
|
||||
import {
|
||||
formattersContext,
|
||||
registriesContext,
|
||||
statesContext,
|
||||
} from "../../../../data/context";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import {
|
||||
getAreaControlEntities,
|
||||
@@ -37,14 +50,36 @@ export class HuiAreaControlsCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: AreaCardFeatureContext;
|
||||
|
||||
@state() private _config?: AreaControlsCardFeatureConfig;
|
||||
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
private _states?: HassEntities;
|
||||
|
||||
@state() protected _controlEntityIds: string[] = [];
|
||||
|
||||
@state()
|
||||
@consumeEntityStates({ entityIdPath: ["_controlEntityIds"] })
|
||||
private _controlEntityStates?: Record<string, HassEntity>;
|
||||
|
||||
@state()
|
||||
@consume({ context: registriesContext, subscribe: true })
|
||||
private _registries!: ContextType<typeof registriesContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
private _formatters!: ContextType<typeof formattersContext>;
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
public setConfig(config: AreaControlsCardFeatureConfig): void {
|
||||
this._config = config;
|
||||
this._controlEntityIds = (config.controls ?? []).flatMap((control) =>
|
||||
typeof control === "object" && "entity_id" in control
|
||||
? [control.entity_id]
|
||||
: []
|
||||
);
|
||||
}
|
||||
|
||||
private _schema = [
|
||||
@@ -73,7 +108,7 @@ export class HuiAreaControlsCardFeatureEditor
|
||||
);
|
||||
const controlEntities = getAreaControlEntities(
|
||||
areaEntities,
|
||||
this.hass!.states,
|
||||
this._states!,
|
||||
entities,
|
||||
devices,
|
||||
areas,
|
||||
@@ -87,23 +122,23 @@ export class HuiAreaControlsCardFeatureEditor
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config || !this.context?.area_id) {
|
||||
if (!this._states || !this._config || !this.context?.area_id) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const supportedControls = this._supportedControls(
|
||||
this.context.area_id,
|
||||
this.context.exclude_entities,
|
||||
this.hass.entities,
|
||||
this.hass.devices,
|
||||
this.hass.areas,
|
||||
this.hass.floors
|
||||
this._registries.entities,
|
||||
this._registries.devices,
|
||||
this._registries.areas,
|
||||
this._registries.floors
|
||||
);
|
||||
|
||||
if (supportedControls.length === 0) {
|
||||
return html`
|
||||
<ha-alert alert-type="warning">
|
||||
${this.hass.localize(
|
||||
${this._localize(
|
||||
"ui.panel.lovelace.editor.features.types.area-controls.no_compatible_controls"
|
||||
)}
|
||||
</ha-alert>
|
||||
@@ -122,7 +157,6 @@ export class HuiAreaControlsCardFeatureEditor
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${this._schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -172,7 +206,7 @@ export class HuiAreaControlsCardFeatureEditor
|
||||
.excludeEntities=${this.context.exclude_entities}
|
||||
.excludeValues=${excludeValues}
|
||||
.value=${""}
|
||||
.addButtonLabel=${this.hass.localize(
|
||||
.addButtonLabel=${this._localize(
|
||||
"ui.panel.lovelace.editor.features.types.area-controls.controls"
|
||||
)}
|
||||
@value-changed=${this._controlChanged}
|
||||
@@ -184,13 +218,9 @@ export class HuiAreaControlsCardFeatureEditor
|
||||
}
|
||||
|
||||
private _getItemLabel(item: AreaControl): string {
|
||||
if (!this.hass) {
|
||||
return typeof item === "string" ? item : JSON.stringify(item);
|
||||
}
|
||||
|
||||
if (typeof item === "string") {
|
||||
if (AREA_CONTROL_DOMAINS.includes(item as AreaControlDomain)) {
|
||||
return this.hass.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.features.types.area-controls.controls_options.${item}`
|
||||
);
|
||||
}
|
||||
@@ -199,9 +229,9 @@ export class HuiAreaControlsCardFeatureEditor
|
||||
}
|
||||
|
||||
if ("entity_id" in item) {
|
||||
const entityState = this.hass.states[item.entity_id];
|
||||
const entityState = this._controlEntityStates?.[item.entity_id];
|
||||
if (entityState) {
|
||||
return this.hass.formatEntityName(entityState);
|
||||
return this._formatters.formatEntityName(entityState);
|
||||
}
|
||||
return item.entity_id;
|
||||
}
|
||||
@@ -253,10 +283,10 @@ export class HuiAreaControlsCardFeatureEditor
|
||||
config.controls = this._supportedControls(
|
||||
this.context!.area_id!,
|
||||
this.context!.exclude_entities,
|
||||
this.hass!.entities,
|
||||
this.hass!.devices,
|
||||
this.hass!.areas,
|
||||
this.hass!.floors
|
||||
this._registries.entities,
|
||||
this._registries.devices,
|
||||
this._registries.areas,
|
||||
this._registries.floors
|
||||
).slice(0, MAX_DEFAULT_AREA_CONTROLS); // Limit to max default controls
|
||||
}
|
||||
|
||||
@@ -272,7 +302,7 @@ export class HuiAreaControlsCardFeatureEditor
|
||||
) => {
|
||||
switch (schema.name) {
|
||||
case "customize_controls":
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.features.types.area-controls.${schema.name}`
|
||||
);
|
||||
default:
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
@@ -8,7 +9,6 @@ import type {
|
||||
HaFormSchema,
|
||||
SchemaUnion,
|
||||
} from "../../../../components/ha-form/types";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type {
|
||||
BarGaugeCardFeatureConfig,
|
||||
LovelaceCardFeatureContext,
|
||||
@@ -26,10 +26,12 @@ export class HuiBarGaugeCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: BarGaugeCardFeatureConfig;
|
||||
|
||||
public setConfig(config: BarGaugeCardFeatureConfig): void {
|
||||
@@ -115,7 +117,7 @@ export class HuiBarGaugeCardFeatureEditor
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
@@ -127,9 +129,8 @@ export class HuiBarGaugeCardFeatureEditor
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${this._schema(this.hass.localize)}
|
||||
.schema=${this._schema(this._localize)}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@value-changed=${this._valueChanged}
|
||||
></ha-form>
|
||||
@@ -173,7 +174,7 @@ export class HuiBarGaugeCardFeatureEditor
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) =>
|
||||
this.hass!.localize(
|
||||
this._localize(
|
||||
`ui.panel.lovelace.editor.features.types.bar-gauge.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import {
|
||||
array,
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
union,
|
||||
literal,
|
||||
} from "superstruct";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/entity/ha-entities-picker";
|
||||
@@ -20,7 +21,6 @@ import type {
|
||||
HaFormSchema,
|
||||
SchemaUnion,
|
||||
} from "../../../../components/ha-form/types";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type { CalendarCardConfig } from "../../cards/types";
|
||||
import type { LovelaceCardEditor } from "../../types";
|
||||
import { baseLovelaceCardConfig } from "../structs/base-card-struct";
|
||||
@@ -49,7 +49,8 @@ export class HuiCalendarCardEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: CalendarCardConfig;
|
||||
|
||||
@@ -163,16 +164,15 @@ export class HuiCalendarCardEditor
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const schema = this._schema(this.hass.localize);
|
||||
const schema = this._schema(this._localize);
|
||||
const data = { initial_view: "dayGridMonth", ...this._config };
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -180,11 +180,11 @@ export class HuiCalendarCardEditor
|
||||
></ha-form>
|
||||
<h3>
|
||||
${
|
||||
this.hass.localize(
|
||||
this._localize(
|
||||
"ui.panel.lovelace.editor.card.calendar.calendar_entities"
|
||||
) +
|
||||
" (" +
|
||||
this.hass!.localize("ui.panel.lovelace.editor.card.config.required") +
|
||||
this._localize("ui.panel.lovelace.editor.card.config.required") +
|
||||
")"
|
||||
}
|
||||
</h3>
|
||||
@@ -211,18 +211,16 @@ export class HuiCalendarCardEditor
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) => {
|
||||
if (schema.name === "title") {
|
||||
return this.hass!.localize("ui.panel.lovelace.editor.card.generic.title");
|
||||
return this._localize("ui.panel.lovelace.editor.card.generic.title");
|
||||
}
|
||||
|
||||
if (schema.name === "theme") {
|
||||
return `${this.hass!.localize(
|
||||
return `${this._localize(
|
||||
"ui.panel.lovelace.editor.card.generic.theme"
|
||||
)} (${this.hass!.localize(
|
||||
"ui.panel.lovelace.editor.card.config.optional"
|
||||
)})`;
|
||||
)} (${this._localize("ui.panel.lovelace.editor.card.config.optional")})`;
|
||||
}
|
||||
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.card.calendar.${schema.name}`
|
||||
);
|
||||
};
|
||||
|
||||
+8
-7
@@ -1,8 +1,11 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import type {
|
||||
LocalizeFunc,
|
||||
LocalizeKeys,
|
||||
} from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-alert";
|
||||
import type { LocalizeKeys } from "../../../../common/translations/localize";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type {
|
||||
LovelaceCardFeatureConfig,
|
||||
LovelaceCardFeatureContext,
|
||||
@@ -14,7 +17,7 @@ export class HuiCardFeatureMoreInfoHintEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@@ -25,7 +28,7 @@ export class HuiCardFeatureMoreInfoHintEditor
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
@@ -33,9 +36,7 @@ export class HuiCardFeatureMoreInfoHintEditor
|
||||
`ui.panel.lovelace.editor.features.types.${this._config.type}.description` satisfies LocalizeKeys;
|
||||
|
||||
return html`
|
||||
<ha-alert alert-type="info">
|
||||
${this.hass.localize(descriptionKey)}
|
||||
</ha-alert>
|
||||
<ha-alert alert-type="info"> ${this._localize(descriptionKey)} </ha-alert>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -10,9 +10,9 @@ const DESCRIPTOR: EntityModesCardFeatureEditorDescriptor<ClimateFanModesCardFeat
|
||||
modeField: "fan_modes",
|
||||
defaultStyle: "dropdown",
|
||||
getAvailableModesOrdered: (s) => s?.attributes.fan_modes ?? [],
|
||||
getModeLabel: (hass, stateObj, mode) =>
|
||||
getModeLabel: (formatters, stateObj, mode) =>
|
||||
stateObj
|
||||
? hass.formatEntityAttributeValue(stateObj, "fan_mode", mode)
|
||||
? formatters.formatEntityAttributeValue(stateObj, "fan_mode", mode)
|
||||
: mode,
|
||||
};
|
||||
|
||||
|
||||
+2
-2
@@ -13,8 +13,8 @@ const DESCRIPTOR: EntityModesCardFeatureEditorDescriptor<ClimateHvacModesCardFea
|
||||
defaultStyle: "icons",
|
||||
getAvailableModesOrdered: (s) =>
|
||||
(s?.attributes.hvac_modes ?? []).concat().sort(compareClimateHvacModes),
|
||||
getModeLabel: (hass, stateObj, mode) =>
|
||||
stateObj ? hass.formatEntityState(stateObj, mode) : mode,
|
||||
getModeLabel: (formatters, stateObj, mode) =>
|
||||
stateObj ? formatters.formatEntityState(stateObj, mode) : mode,
|
||||
};
|
||||
|
||||
@customElement("hui-climate-hvac-modes-card-feature-editor")
|
||||
|
||||
+2
-2
@@ -10,9 +10,9 @@ const DESCRIPTOR: EntityModesCardFeatureEditorDescriptor<ClimatePresetModesCardF
|
||||
modeField: "preset_modes",
|
||||
defaultStyle: "dropdown",
|
||||
getAvailableModesOrdered: (s) => s?.attributes.preset_modes ?? [],
|
||||
getModeLabel: (hass, stateObj, mode) =>
|
||||
getModeLabel: (formatters, stateObj, mode) =>
|
||||
stateObj
|
||||
? hass.formatEntityAttributeValue(stateObj, "preset_mode", mode)
|
||||
? formatters.formatEntityAttributeValue(stateObj, "preset_mode", mode)
|
||||
: mode,
|
||||
};
|
||||
|
||||
|
||||
+2
-2
@@ -10,9 +10,9 @@ const DESCRIPTOR: EntityModesCardFeatureEditorDescriptor<ClimateSwingHorizontalM
|
||||
modeField: "swing_horizontal_modes",
|
||||
defaultStyle: "dropdown",
|
||||
getAvailableModesOrdered: (s) => s?.attributes.swing_horizontal_modes ?? [],
|
||||
getModeLabel: (hass, stateObj, mode) =>
|
||||
getModeLabel: (formatters, stateObj, mode) =>
|
||||
stateObj
|
||||
? hass.formatEntityAttributeValue(
|
||||
? formatters.formatEntityAttributeValue(
|
||||
stateObj,
|
||||
"swing_horizontal_mode",
|
||||
mode
|
||||
|
||||
+2
-2
@@ -10,9 +10,9 @@ const DESCRIPTOR: EntityModesCardFeatureEditorDescriptor<ClimateSwingModesCardFe
|
||||
modeField: "swing_modes",
|
||||
defaultStyle: "dropdown",
|
||||
getAvailableModesOrdered: (s) => s?.attributes.swing_modes ?? [],
|
||||
getModeLabel: (hass, stateObj, mode) =>
|
||||
getModeLabel: (formatters, stateObj, mode) =>
|
||||
stateObj
|
||||
? hass.formatEntityAttributeValue(stateObj, "swing_mode", mode)
|
||||
? formatters.formatEntityAttributeValue(stateObj, "swing_mode", mode)
|
||||
: mode,
|
||||
};
|
||||
|
||||
|
||||
+8
-7
@@ -1,11 +1,11 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import type { SchemaUnion } from "../../../../components/ha-form/types";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type {
|
||||
CounterActionsCardFeatureConfig,
|
||||
LovelaceCardFeatureContext,
|
||||
@@ -23,10 +23,12 @@ export class HuiCounterActionsCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: CounterActionsCardFeatureConfig;
|
||||
|
||||
public setConfig(config: CounterActionsCardFeatureConfig): void {
|
||||
@@ -46,16 +48,15 @@ export class HuiCounterActionsCardFeatureEditor
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const data = customizableListData(this._config, "actions");
|
||||
const schema = this._schema(this.hass.localize);
|
||||
const schema = this._schema(this._localize);
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -77,7 +78,7 @@ export class HuiCounterActionsCardFeatureEditor
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) =>
|
||||
this.hass!.localize(
|
||||
this._localize(
|
||||
`ui.panel.lovelace.editor.features.types.counter-actions.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import {
|
||||
assert,
|
||||
@@ -11,11 +11,11 @@ import {
|
||||
string,
|
||||
union,
|
||||
} from "superstruct";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { HaFormSchema } from "../../../../components/ha-form/types";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type { EnergyDateSelectorCardConfig } from "../../cards/types";
|
||||
import type { LovelaceCardEditor } from "../../types";
|
||||
import { baseLovelaceCardConfig } from "../structs/base-card-struct";
|
||||
@@ -53,7 +53,8 @@ export class HuiEnergyDateSelectionCardEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: EnergyDateSelectorCardConfig;
|
||||
|
||||
@@ -114,16 +115,15 @@ export class HuiEnergyDateSelectionCardEditor
|
||||
});
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const data = collectionKeyToFormData(this._config);
|
||||
|
||||
const schema = this._schema(this.hass.localize);
|
||||
const schema = this._schema(this._localize);
|
||||
|
||||
return html` <ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -141,7 +141,7 @@ export class HuiEnergyDateSelectionCardEditor
|
||||
private _computeHelperCallback = (schema) => {
|
||||
switch (schema.name) {
|
||||
case "collection_key":
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.card.generic.collection_key_description`
|
||||
);
|
||||
default:
|
||||
@@ -155,11 +155,11 @@ export class HuiEnergyDateSelectionCardEditor
|
||||
case "opening_direction":
|
||||
case "disable_compare":
|
||||
case "show_combine_sources":
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.card.energy-date-selection.${schema.name}`
|
||||
);
|
||||
default:
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.card.generic.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import {
|
||||
array,
|
||||
assert,
|
||||
@@ -13,11 +13,11 @@ import {
|
||||
union,
|
||||
} from "superstruct";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { HaFormSchema } from "../../../../components/ha-form/types";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type {
|
||||
EnergyCardConfig,
|
||||
EnergyDevicesDetailGraphCardConfig,
|
||||
@@ -61,7 +61,8 @@ export class HuiEnergyDevicesCardEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: EnergyDevicesCardConfig;
|
||||
|
||||
@@ -118,16 +119,15 @@ export class HuiEnergyDevicesCardEditor
|
||||
});
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const schema = this._schema(this.hass.localize);
|
||||
const schema = this._schema(this._localize);
|
||||
|
||||
const data = collectionKeyToFormData(this._config);
|
||||
|
||||
return html` <ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -145,7 +145,7 @@ export class HuiEnergyDevicesCardEditor
|
||||
private _computeHelperCallback = (schema) => {
|
||||
switch (schema.name) {
|
||||
case "collection_key":
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.card.generic.collection_key_description`
|
||||
);
|
||||
default:
|
||||
@@ -158,11 +158,11 @@ export class HuiEnergyDevicesCardEditor
|
||||
case "modes":
|
||||
case "max_devices":
|
||||
case "hide_compound_stats":
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.card.energy-devices-graph.${schema.name}`
|
||||
);
|
||||
default:
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.card.generic.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import {
|
||||
assert,
|
||||
assign,
|
||||
@@ -12,11 +12,11 @@ import {
|
||||
union,
|
||||
} from "superstruct";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { HaFormSchema } from "../../../../components/ha-form/types";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type { SankeyCardConfig } from "../../cards/types";
|
||||
import type { LovelaceCardEditor } from "../../types";
|
||||
import { baseLovelaceCardConfig } from "../structs/base-card-struct";
|
||||
@@ -57,7 +57,8 @@ export class HuiEnergySankeyCardEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: SankeyCardConfig;
|
||||
|
||||
@@ -127,16 +128,15 @@ export class HuiEnergySankeyCardEditor
|
||||
});
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const schema = this._schema(this.hass.localize, this._config.type);
|
||||
const schema = this._schema(this._localize, this._config.type);
|
||||
|
||||
const data = collectionKeyToFormData(this._config);
|
||||
|
||||
return html` <ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -154,11 +154,11 @@ export class HuiEnergySankeyCardEditor
|
||||
private _computeHelperCallback = (schema) => {
|
||||
switch (schema.name) {
|
||||
case "collection_key":
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.card.generic.collection_key_description`
|
||||
);
|
||||
case "max_devices":
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.card.energy-sankey.max_devices_description`
|
||||
);
|
||||
default:
|
||||
@@ -173,11 +173,11 @@ export class HuiEnergySankeyCardEditor
|
||||
case "group_by_area":
|
||||
case "max_devices":
|
||||
case "show_values":
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.card.energy-sankey.${schema.name}`
|
||||
);
|
||||
default:
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.card.generic.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -273,14 +273,12 @@ export class HuiEntitiesCardEditor
|
||||
@value-changed=${this._formChanged}
|
||||
></ha-form>
|
||||
<hui-header-footer-editor
|
||||
.hass=${this.hass}
|
||||
.configValue=${"header"}
|
||||
.config=${this._config.header}
|
||||
@value-changed=${this._valueChanged}
|
||||
@edit-detail-element=${this._editDetailElement}
|
||||
></hui-header-footer-editor>
|
||||
<hui-header-footer-editor
|
||||
.hass=${this.hass}
|
||||
.configValue=${"footer"}
|
||||
.config=${this._config.footer}
|
||||
@value-changed=${this._valueChanged}
|
||||
@@ -288,7 +286,6 @@ export class HuiEntitiesCardEditor
|
||||
></hui-header-footer-editor>
|
||||
</div>
|
||||
<hui-entities-card-row-editor
|
||||
.hass=${this.hass}
|
||||
.entities=${this._configEntities}
|
||||
@entities-changed=${this._valueChanged}
|
||||
@edit-detail-element=${this._editDetailElement}
|
||||
|
||||
+32
-19
@@ -2,6 +2,11 @@ import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
@@ -9,7 +14,8 @@ import type {
|
||||
HaFormSchema,
|
||||
SchemaUnion,
|
||||
} from "../../../../components/ha-form/types";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import { formattersContext } from "../../../../data/context";
|
||||
import type { HomeAssistantFormatters } from "../../../../types";
|
||||
import type {
|
||||
LovelaceCardFeatureConfig,
|
||||
LovelaceCardFeatureContext,
|
||||
@@ -34,7 +40,7 @@ export interface EntityModesCardFeatureEditorDescriptor<
|
||||
/** Modes shown in the multiselect and used when enabling customize without a prior selection. */
|
||||
getAvailableModesOrdered: (stateObj: HassEntity | undefined) => string[];
|
||||
getModeLabel: (
|
||||
hass: HomeAssistant,
|
||||
formatters: HomeAssistantFormatters,
|
||||
stateObj: HassEntity | undefined,
|
||||
mode: string
|
||||
) => string;
|
||||
@@ -60,10 +66,18 @@ export abstract class HuiEntityModesCardFeatureEditorBase<
|
||||
{
|
||||
protected abstract readonly descriptor: EntityModesCardFeatureEditorDescriptor<TConfig>;
|
||||
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
|
||||
private _stateObj?: HassEntity;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
private _formatters!: HomeAssistantFormatters;
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: TConfig;
|
||||
|
||||
public setConfig(config: LovelaceCardFeatureConfig): void {
|
||||
@@ -74,7 +88,11 @@ export abstract class HuiEntityModesCardFeatureEditorBase<
|
||||
}
|
||||
|
||||
private _schema = memoizeOne(
|
||||
(localize: LocalizeFunc, stateObj: HassEntity | undefined) => {
|
||||
(
|
||||
localize: LocalizeFunc,
|
||||
formatters: HomeAssistantFormatters,
|
||||
stateObj: HassEntity | undefined
|
||||
) => {
|
||||
const d = this.descriptor;
|
||||
const styleListId = d.styleListI18nFeatureId ?? d.i18nFeatureId;
|
||||
return [
|
||||
@@ -108,7 +126,7 @@ export abstract class HuiEntityModesCardFeatureEditorBase<
|
||||
multiple: true,
|
||||
options: d.getAvailableModesOrdered(stateObj).map((mode) => ({
|
||||
value: mode,
|
||||
label: d.getModeLabel(this.hass!, stateObj, mode),
|
||||
label: d.getModeLabel(formatters, stateObj, mode),
|
||||
})),
|
||||
},
|
||||
},
|
||||
@@ -118,14 +136,10 @@ export abstract class HuiEntityModesCardFeatureEditorBase<
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const stateObj = this.context?.entity_id
|
||||
? this.hass.states[this.context.entity_id]
|
||||
: undefined;
|
||||
|
||||
const { modeField, defaultStyle } = this.descriptor;
|
||||
|
||||
const data: EntityModesFormData<TConfig> = {
|
||||
@@ -134,11 +148,14 @@ export abstract class HuiEntityModesCardFeatureEditorBase<
|
||||
customize_modes: this._config[modeField as keyof TConfig] !== undefined,
|
||||
};
|
||||
|
||||
const schema = this._schema(this.hass.localize, stateObj);
|
||||
const schema = this._schema(
|
||||
this._localize,
|
||||
this._formatters,
|
||||
this._stateObj
|
||||
);
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -152,17 +169,13 @@ export abstract class HuiEntityModesCardFeatureEditorBase<
|
||||
const customize_modes = value.customize_modes;
|
||||
let cfg = stripCustomizeModes(value);
|
||||
|
||||
const stateObj = this.context?.entity_id
|
||||
? this.hass!.states[this.context.entity_id]
|
||||
: undefined;
|
||||
|
||||
const { modeField, getAvailableModesOrdered } = this.descriptor;
|
||||
const modeKey = modeField as keyof TConfig;
|
||||
|
||||
if (customize_modes && !cfg[modeKey]) {
|
||||
cfg = {
|
||||
...cfg,
|
||||
[modeField]: getAvailableModesOrdered(stateObj),
|
||||
[modeField]: getAvailableModesOrdered(this._stateObj),
|
||||
} as TConfig;
|
||||
}
|
||||
if (!customize_modes && cfg[modeKey] !== undefined) {
|
||||
@@ -182,7 +195,7 @@ export abstract class HuiEntityModesCardFeatureEditorBase<
|
||||
schema.name === "customize_modes" ||
|
||||
schema.name === modeField
|
||||
) {
|
||||
return this.hass!.localize(
|
||||
return this._localize(
|
||||
`ui.panel.lovelace.editor.features.types.${id}.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
+2
-2
@@ -10,9 +10,9 @@ const DESCRIPTOR: EntityModesCardFeatureEditorDescriptor<FanPresetModesCardFeatu
|
||||
modeField: "preset_modes",
|
||||
defaultStyle: "dropdown",
|
||||
getAvailableModesOrdered: (s) => s?.attributes.preset_modes ?? [],
|
||||
getModeLabel: (hass, stateObj, mode) =>
|
||||
getModeLabel: (formatters, stateObj, mode) =>
|
||||
stateObj
|
||||
? hass.formatEntityAttributeValue(stateObj, "preset_mode", mode)
|
||||
? formatters.formatEntityAttributeValue(stateObj, "preset_mode", mode)
|
||||
: mode,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { assert } from "superstruct";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import { computeDomain } from "../../../../common/entity/compute_domain";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { SchemaUnion } from "../../../../components/ha-form/types";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import { SENSOR_TIMESTAMP_DEVICE_CLASSES } from "../../../../data/sensor";
|
||||
import type { EntitiesCardEntityConfig } from "../../cards/types";
|
||||
import type { LovelaceRowEditor } from "../../types";
|
||||
@@ -20,12 +25,18 @@ export class HuiGenericEntityRowEditor
|
||||
extends LitElement
|
||||
implements LovelaceRowEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public schema?;
|
||||
|
||||
@state() private _config?: EntitiesCardEntityConfig;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["_config", "entity"] })
|
||||
private _stateObj?: HassEntity;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
public setConfig(config: EntitiesCardEntityConfig): void {
|
||||
assert(config, entitiesConfigStruct);
|
||||
this._config = config;
|
||||
@@ -85,7 +96,7 @@ export class HuiGenericEntityRowEditor
|
||||
});
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
@@ -100,7 +111,7 @@ export class HuiGenericEntityRowEditor
|
||||
(this._config.secondary_info &&
|
||||
stateContentHasTimestamp(
|
||||
entity,
|
||||
this.hass.states[entity],
|
||||
this._stateObj,
|
||||
this._config.secondary_info
|
||||
)) ||
|
||||
(simpleEntity
|
||||
@@ -108,17 +119,16 @@ export class HuiGenericEntityRowEditor
|
||||
: domain === "event" ||
|
||||
(domain === "sensor" &&
|
||||
SENSOR_TIMESTAMP_DEVICE_CLASSES.includes(
|
||||
this.hass.states[entity]?.attributes.device_class
|
||||
this._stateObj?.attributes.device_class
|
||||
)));
|
||||
schema = this._schema(showTimeFormat);
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${this._config}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
.computeLabel=${this._computeLabelCallback(this._localize)}
|
||||
@value-changed=${this._valueChanged}
|
||||
></ha-form>
|
||||
`;
|
||||
@@ -128,20 +138,13 @@ export class HuiGenericEntityRowEditor
|
||||
fireEvent(this, "config-changed", { config: ev.detail.value });
|
||||
}
|
||||
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) => {
|
||||
switch (schema.name) {
|
||||
case "secondary_info":
|
||||
return this.hass!.localize(
|
||||
`ui.panel.lovelace.editor.card.entity-row.${schema.name}`
|
||||
);
|
||||
default:
|
||||
return this.hass!.localize(
|
||||
`ui.panel.lovelace.editor.card.generic.${schema.name}`
|
||||
);
|
||||
}
|
||||
};
|
||||
private _computeLabelCallback = memoizeOne(
|
||||
(localize: LocalizeFunc) =>
|
||||
(schema: SchemaUnion<ReturnType<typeof this._schema>>) =>
|
||||
schema.name === "secondary_info"
|
||||
? localize(`ui.panel.lovelace.editor.card.entity-row.${schema.name}`)
|
||||
: localize(`ui.panel.lovelace.editor.card.generic.${schema.name}`)
|
||||
);
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import type { CSSResultGroup } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import { assert } from "superstruct";
|
||||
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/entity/ha-entity-picker";
|
||||
import "../../../../components/ha-switch";
|
||||
import "../../../../components/input/ha-input";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import { graphHeaderFooterConfigStruct } from "../../header-footer/structs";
|
||||
import type { GraphHeaderFooterConfig } from "../../header-footer/types";
|
||||
import type { LovelaceCardEditor } from "../../types";
|
||||
@@ -21,7 +22,7 @@ export class HuiGraphFooterEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: GraphHeaderFooterConfig;
|
||||
|
||||
@@ -43,14 +44,14 @@ export class HuiGraphFooterEditor
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="card-config">
|
||||
<ha-entity-picker
|
||||
.label=${this.hass.localize(
|
||||
.label=${this._localize(
|
||||
"ui.panel.lovelace.editor.card.generic.entity"
|
||||
)}
|
||||
.value=${this._entity}
|
||||
@@ -64,15 +65,15 @@ export class HuiGraphFooterEditor
|
||||
.checked=${this._detail === 2}
|
||||
.configValue=${"detail"}
|
||||
@change=${this._change}
|
||||
>${this.hass.localize(
|
||||
>${this._localize(
|
||||
"ui.panel.lovelace.editor.card.sensor.show_more_detail"
|
||||
)}</ha-switch
|
||||
>
|
||||
<ha-input
|
||||
type="number"
|
||||
.label="${this.hass.localize(
|
||||
.label="${this._localize(
|
||||
"ui.panel.lovelace.editor.card.generic.hours_to_show"
|
||||
)} (${this.hass.localize(
|
||||
)} (${this._localize(
|
||||
"ui.panel.lovelace.editor.card.config.optional"
|
||||
)})"
|
||||
.value=${String(this._hours_to_show)}
|
||||
@@ -86,7 +87,7 @@ export class HuiGraphFooterEditor
|
||||
}
|
||||
|
||||
private _change(ev: Event) {
|
||||
if (!this._config || !this.hass) {
|
||||
if (!this._config) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -105,7 +106,7 @@ export class HuiGraphFooterEditor
|
||||
}
|
||||
|
||||
private _valueChanged(ev: HASSDomEvent<EntitiesEditorEvent>): void {
|
||||
if (!this._config || !this.hass) {
|
||||
if (!this._config) {
|
||||
return;
|
||||
}
|
||||
const target = ev.target! as EditorTarget;
|
||||
|
||||
+4
-2
@@ -10,8 +10,10 @@ const DESCRIPTOR: EntityModesCardFeatureEditorDescriptor<HumidifierModesCardFeat
|
||||
modeField: "modes",
|
||||
defaultStyle: "dropdown",
|
||||
getAvailableModesOrdered: (s) => s?.attributes.available_modes ?? [],
|
||||
getModeLabel: (hass, stateObj, mode) =>
|
||||
stateObj ? hass.formatEntityAttributeValue(stateObj, "mode", mode) : mode,
|
||||
getModeLabel: (formatters, stateObj, mode) =>
|
||||
stateObj
|
||||
? formatters.formatEntityAttributeValue(stateObj, "mode", mode)
|
||||
: mode,
|
||||
};
|
||||
|
||||
@customElement("hui-humidifier-modes-card-feature-editor")
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { assert, assign, boolean, object, optional, string } from "superstruct";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { SchemaUnion } from "../../../../components/ha-form/types";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type { IframeCardConfig } from "../../cards/types";
|
||||
import type { LovelaceCardEditor } from "../../types";
|
||||
import { baseLovelaceCardConfig } from "../structs/base-card-struct";
|
||||
@@ -38,7 +40,8 @@ export class HuiIframeCardEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: IframeCardConfig;
|
||||
|
||||
@@ -48,17 +51,16 @@ export class HuiIframeCardEditor
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${this._config}
|
||||
.schema=${SCHEMA}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
.computeHelper=${this._computeHelperCallback}
|
||||
.computeLabel=${this._computeLabelCallback(this._localize)}
|
||||
.computeHelper=${this._computeHelperCallback(this._localize)}
|
||||
@value-changed=${this._valueChanged}
|
||||
></ha-form>
|
||||
`;
|
||||
@@ -68,29 +70,33 @@ export class HuiIframeCardEditor
|
||||
fireEvent(this, "config-changed", { config: ev.detail.value });
|
||||
}
|
||||
|
||||
private _computeLabelCallback = (schema: SchemaUnion<typeof SCHEMA>) => {
|
||||
switch (schema.name) {
|
||||
case "hide_background":
|
||||
return this.hass!.localize(
|
||||
"ui.panel.lovelace.editor.card.iframe.hide_background"
|
||||
);
|
||||
default:
|
||||
return this.hass!.localize(
|
||||
`ui.panel.lovelace.editor.card.generic.${schema.name}`
|
||||
);
|
||||
private _computeLabelCallback = memoizeOne(
|
||||
(localize: LocalizeFunc) => (schema: SchemaUnion<typeof SCHEMA>) => {
|
||||
switch (schema.name) {
|
||||
case "hide_background":
|
||||
return localize(
|
||||
"ui.panel.lovelace.editor.card.iframe.hide_background"
|
||||
);
|
||||
default:
|
||||
return localize(
|
||||
`ui.panel.lovelace.editor.card.generic.${schema.name}`
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
);
|
||||
|
||||
private _computeHelperCallback = (schema: SchemaUnion<typeof SCHEMA>) => {
|
||||
switch (schema.name) {
|
||||
case "hide_background":
|
||||
return this.hass!.localize(
|
||||
"ui.panel.lovelace.editor.card.iframe.hide_background_helper"
|
||||
);
|
||||
default:
|
||||
return "";
|
||||
private _computeHelperCallback = memoizeOne(
|
||||
(localize: LocalizeFunc) => (schema: SchemaUnion<typeof SCHEMA>) => {
|
||||
switch (schema.name) {
|
||||
case "hide_background":
|
||||
return localize(
|
||||
"ui.panel.lovelace.editor.card.iframe.hide_background_helper"
|
||||
);
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
};
|
||||
);
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
+30
-26
@@ -2,10 +2,14 @@ import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import type { SchemaUnion } from "../../../../components/ha-form/types";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import { supportsLawnMowerCommand } from "../../card-features/hui-lawn-mower-commands-card-feature";
|
||||
import type {
|
||||
LawnMowerCommandsCardFeatureConfig,
|
||||
@@ -24,45 +28,47 @@ export class HuiLawnMowerCommandsCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
|
||||
private _stateObj?: HassEntity;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: LawnMowerCommandsCardFeatureConfig;
|
||||
|
||||
public setConfig(config: LawnMowerCommandsCardFeatureConfig): void {
|
||||
this._config = config;
|
||||
}
|
||||
|
||||
private _schema = memoizeOne((stateObj: HassEntity | undefined) =>
|
||||
customizableListSchema({
|
||||
field: "commands",
|
||||
options: LAWN_MOWER_COMMANDS.filter(
|
||||
(command) => stateObj && supportsLawnMowerCommand(stateObj, command)
|
||||
).map((command) => ({
|
||||
value: command,
|
||||
label: this.hass!.localize(
|
||||
`ui.panel.lovelace.editor.features.types.lawn-mower-commands.commands_list.${command}`
|
||||
),
|
||||
})),
|
||||
})
|
||||
private _schema = memoizeOne(
|
||||
(localize: LocalizeFunc, stateObj: HassEntity | undefined) =>
|
||||
customizableListSchema({
|
||||
field: "commands",
|
||||
options: LAWN_MOWER_COMMANDS.filter(
|
||||
(command) => stateObj && supportsLawnMowerCommand(stateObj, command)
|
||||
).map((command) => ({
|
||||
value: command,
|
||||
label: localize(
|
||||
`ui.panel.lovelace.editor.features.types.lawn-mower-commands.commands_list.${command}`
|
||||
),
|
||||
})),
|
||||
})
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const stateObj = this.context?.entity_id
|
||||
? this.hass.states[this.context.entity_id]
|
||||
: undefined;
|
||||
|
||||
const data = customizableListData(this._config, "commands");
|
||||
const schema = this._schema(stateObj);
|
||||
const schema = this._schema(this._localize, this._stateObj);
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -72,9 +78,7 @@ export class HuiLawnMowerCommandsCardFeatureEditor
|
||||
}
|
||||
|
||||
private _valueChanged(ev: CustomEvent): void {
|
||||
const stateObj = this.context?.entity_id
|
||||
? this.hass!.states[this.context.entity_id]
|
||||
: undefined;
|
||||
const stateObj = this._stateObj;
|
||||
const defaults = LAWN_MOWER_COMMANDS.filter(
|
||||
(command) => stateObj && supportsLawnMowerCommand(stateObj, command)
|
||||
);
|
||||
@@ -90,7 +94,7 @@ export class HuiLawnMowerCommandsCardFeatureEditor
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) =>
|
||||
this.hass!.localize(
|
||||
this._localize(
|
||||
`ui.panel.lovelace.editor.features.types.lawn-mower-commands.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { SchemaUnion } from "../../../../components/ha-form/types";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import {
|
||||
DEFAULT_LIGHT_COLOR_CONTROLS,
|
||||
LIGHT_COLOR_CONTROLS,
|
||||
@@ -19,10 +19,12 @@ export class HuiLightColorCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: LightColorCardFeatureConfig;
|
||||
|
||||
public setConfig(config: LightColorCardFeatureConfig): void {
|
||||
@@ -51,7 +53,7 @@ export class HuiLightColorCardFeatureEditor
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
@@ -62,9 +64,8 @@ export class HuiLightColorCardFeatureEditor
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${this._schema(this.hass.localize)}
|
||||
.schema=${this._schema(this._localize)}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@value-changed=${this._valueChanged}
|
||||
></ha-form>
|
||||
@@ -78,7 +79,7 @@ export class HuiLightColorCardFeatureEditor
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) =>
|
||||
this.hass!.localize(
|
||||
this._localize(
|
||||
`ui.panel.lovelace.editor.features.types.light-color.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
+46
-28
@@ -1,11 +1,23 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../../common/decorators/transform";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { FormatEntityAttributeValueFunc } from "../../../../common/translations/entity-state";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { SchemaUnion } from "../../../../components/ha-form/types";
|
||||
import { formattersContext } from "../../../../data/context";
|
||||
import type { LightEntity } from "../../../../data/light";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
|
||||
import type {
|
||||
HomeAssistantFormatters,
|
||||
ValueChangedEvent,
|
||||
} from "../../../../types";
|
||||
import type {
|
||||
LightEffectCardFeatureConfig,
|
||||
LovelaceCardFeatureContext,
|
||||
@@ -22,46 +34,55 @@ export class HuiLightEffectCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
|
||||
private _stateObj?: LightEntity;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
@transform<HomeAssistantFormatters, FormatEntityAttributeValueFunc>({
|
||||
transformer: (formatters) => formatters?.formatEntityAttributeValue,
|
||||
})
|
||||
private _formatEntityAttributeValue!: FormatEntityAttributeValueFunc;
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: LightEffectCardFeatureConfig;
|
||||
|
||||
public setConfig(config: LightEffectCardFeatureConfig): void {
|
||||
this._config = config;
|
||||
}
|
||||
|
||||
private _schema = memoizeOne((stateObj: LightEntity | undefined) =>
|
||||
customizableListSchema({
|
||||
field: "effects",
|
||||
options:
|
||||
stateObj?.attributes.effect_list?.map((effect) => ({
|
||||
value: effect,
|
||||
label: this.hass!.formatEntityAttributeValue(
|
||||
stateObj,
|
||||
"effect",
|
||||
effect
|
||||
),
|
||||
})) ?? [],
|
||||
})
|
||||
private _schema = memoizeOne(
|
||||
(
|
||||
formatEntityAttributeValue: FormatEntityAttributeValueFunc,
|
||||
stateObj: LightEntity | undefined
|
||||
) =>
|
||||
customizableListSchema({
|
||||
field: "effects",
|
||||
options:
|
||||
stateObj?.attributes.effect_list?.map((effect) => ({
|
||||
value: effect,
|
||||
label: formatEntityAttributeValue(stateObj, "effect", effect),
|
||||
})) ?? [],
|
||||
})
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const stateObj = this.context?.entity_id
|
||||
? (this.hass.states[this.context.entity_id] as LightEntity | undefined)
|
||||
: undefined;
|
||||
|
||||
const data = customizableListData(this._config, "effects");
|
||||
const schema = this._schema(stateObj);
|
||||
const schema = this._schema(
|
||||
this._formatEntityAttributeValue,
|
||||
this._stateObj
|
||||
);
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -73,10 +94,7 @@ export class HuiLightEffectCardFeatureEditor
|
||||
private _valueChanged(
|
||||
ev: ValueChangedEvent<LightEffectCardFeatureConfig>
|
||||
): void {
|
||||
const stateObj = this.context?.entity_id
|
||||
? (this.hass!.states[this.context.entity_id] as LightEntity | undefined)
|
||||
: undefined;
|
||||
const defaults = stateObj?.attributes.effect_list ?? [];
|
||||
const defaults = this._stateObj?.attributes.effect_list ?? [];
|
||||
const config = processCustomizableListValue<LightEffectCardFeatureConfig>(
|
||||
ev.detail.value,
|
||||
"effects",
|
||||
@@ -88,7 +106,7 @@ export class HuiLightEffectCardFeatureEditor
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) =>
|
||||
this.hass!.localize(
|
||||
this._localize(
|
||||
`ui.panel.lovelace.editor.features.types.light-effect.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { assert, assign, object, optional, string } from "superstruct";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type {
|
||||
HaFormSchema,
|
||||
SchemaUnion,
|
||||
} from "../../../../components/ha-form/types";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type { MediaControlCardConfig } from "../../cards/types";
|
||||
import type { LovelaceCardEditor } from "../../types";
|
||||
import { baseLovelaceCardConfig } from "../structs/base-card-struct";
|
||||
@@ -44,7 +46,8 @@ export class HuiMediaControlCardEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: MediaControlCardConfig;
|
||||
|
||||
@@ -54,16 +57,15 @@ export class HuiMediaControlCardEditor
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${this._config}
|
||||
.schema=${SCHEMA}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
.computeLabel=${this._computeLabelCallback(this._localize)}
|
||||
@value-changed=${this._valueChanged}
|
||||
></ha-form>
|
||||
`;
|
||||
@@ -73,18 +75,16 @@ export class HuiMediaControlCardEditor
|
||||
fireEvent(this, "config-changed", { config: ev.detail.value });
|
||||
}
|
||||
|
||||
private _computeLabelCallback = (schema: SchemaUnion<typeof SCHEMA>) => {
|
||||
if (schema.name === "theme") {
|
||||
return `${this.hass!.localize(
|
||||
"ui.panel.lovelace.editor.card.generic.theme"
|
||||
)} (${this.hass!.localize(
|
||||
"ui.panel.lovelace.editor.card.config.optional"
|
||||
)})`;
|
||||
private _computeLabelCallback = memoizeOne(
|
||||
(localize: LocalizeFunc) => (schema: SchemaUnion<typeof SCHEMA>) => {
|
||||
if (schema.name === "theme") {
|
||||
return `${localize(
|
||||
"ui.panel.lovelace.editor.card.generic.theme"
|
||||
)} (${localize("ui.panel.lovelace.editor.card.config.optional")})`;
|
||||
}
|
||||
return localize(`ui.panel.lovelace.editor.card.generic.${schema.name}`);
|
||||
}
|
||||
return this.hass!.localize(
|
||||
`ui.panel.lovelace.editor.card.generic.${schema.name}`
|
||||
);
|
||||
};
|
||||
);
|
||||
|
||||
static styles = configElementStyle;
|
||||
}
|
||||
|
||||
+20
-19
@@ -1,11 +1,15 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import type { SchemaUnion } from "../../../../components/ha-form/types";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { MediaPlayerEntity } from "../../../../data/media-player";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import {
|
||||
getDefaultMediaPlayerControls,
|
||||
supportsMediaPlayerPlaybackControl,
|
||||
@@ -27,10 +31,16 @@ export class HuiMediaPlayerPlaybackCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
|
||||
private _stateObj?: MediaPlayerEntity;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: MediaPlayerPlaybackCardFeatureConfig;
|
||||
|
||||
public setConfig(config: MediaPlayerPlaybackCardFeatureConfig): void {
|
||||
@@ -38,7 +48,7 @@ export class HuiMediaPlayerPlaybackCardFeatureEditor
|
||||
}
|
||||
|
||||
private _schema = memoizeOne(
|
||||
(stateObj: MediaPlayerEntity | undefined) =>
|
||||
(localize: LocalizeFunc, stateObj: MediaPlayerEntity | undefined) =>
|
||||
[
|
||||
...customizableListSchema({
|
||||
field: "controls",
|
||||
@@ -47,7 +57,7 @@ export class HuiMediaPlayerPlaybackCardFeatureEditor
|
||||
stateObj && supportsMediaPlayerPlaybackControl(stateObj, control)
|
||||
).map((control) => ({
|
||||
value: control,
|
||||
label: this.hass!.localize(`ui.card.media_player.${control}`),
|
||||
label: localize(`ui.card.media_player.${control}`),
|
||||
})),
|
||||
}),
|
||||
{
|
||||
@@ -58,21 +68,15 @@ export class HuiMediaPlayerPlaybackCardFeatureEditor
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const stateObj = this.context?.entity_id
|
||||
? (this.hass.states[this.context.entity_id] as
|
||||
MediaPlayerEntity | undefined)
|
||||
: undefined;
|
||||
|
||||
const data = customizableListData(this._config, "controls");
|
||||
const schema = this._schema(stateObj);
|
||||
const schema = this._schema(this._localize, this._stateObj);
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -83,10 +87,7 @@ export class HuiMediaPlayerPlaybackCardFeatureEditor
|
||||
}
|
||||
|
||||
private _valueChanged(ev: CustomEvent): void {
|
||||
const stateObj = this.context?.entity_id
|
||||
? (this.hass!.states[this.context.entity_id] as
|
||||
MediaPlayerEntity | undefined)
|
||||
: undefined;
|
||||
const stateObj = this._stateObj;
|
||||
const defaults = getDefaultMediaPlayerControls(stateObj).filter(
|
||||
(control) =>
|
||||
stateObj && supportsMediaPlayerPlaybackControl(stateObj, control)
|
||||
@@ -103,7 +104,7 @@ export class HuiMediaPlayerPlaybackCardFeatureEditor
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) =>
|
||||
this.hass!.localize(
|
||||
this._localize(
|
||||
`ui.panel.lovelace.editor.features.types.media-player-playback.${schema.name}`
|
||||
);
|
||||
|
||||
@@ -111,7 +112,7 @@ export class HuiMediaPlayerPlaybackCardFeatureEditor
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) =>
|
||||
schema.name === "hide_disabled_controls"
|
||||
? this.hass!.localize(
|
||||
? this._localize(
|
||||
"ui.panel.lovelace.editor.features.types.media-player-playback.hide_disabled_controls_helper"
|
||||
)
|
||||
: undefined;
|
||||
|
||||
+46
-30
@@ -1,11 +1,23 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../../common/decorators/transform";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { FormatEntityAttributeValueFunc } from "../../../../common/translations/entity-state";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { SchemaUnion } from "../../../../components/ha-form/types";
|
||||
import { formattersContext } from "../../../../data/context";
|
||||
import type { MediaPlayerEntity } from "../../../../data/media-player";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
|
||||
import type {
|
||||
HomeAssistantFormatters,
|
||||
ValueChangedEvent,
|
||||
} from "../../../../types";
|
||||
import type {
|
||||
LovelaceCardFeatureContext,
|
||||
MediaPlayerSoundModeCardFeatureConfig,
|
||||
@@ -22,47 +34,55 @@ export class HuiMediaPlayerSoundModeCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
|
||||
private _stateObj?: MediaPlayerEntity;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
@transform<HomeAssistantFormatters, FormatEntityAttributeValueFunc>({
|
||||
transformer: (formatters) => formatters?.formatEntityAttributeValue,
|
||||
})
|
||||
private _formatEntityAttributeValue!: FormatEntityAttributeValueFunc;
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: MediaPlayerSoundModeCardFeatureConfig;
|
||||
|
||||
public setConfig(config: MediaPlayerSoundModeCardFeatureConfig): void {
|
||||
this._config = config;
|
||||
}
|
||||
|
||||
private _schema = memoizeOne((stateObj: MediaPlayerEntity | undefined) =>
|
||||
customizableListSchema({
|
||||
field: "sound_modes",
|
||||
options:
|
||||
stateObj?.attributes.sound_mode_list?.map((mode) => ({
|
||||
value: mode,
|
||||
label: this.hass!.formatEntityAttributeValue(
|
||||
stateObj,
|
||||
"sound_mode",
|
||||
mode
|
||||
),
|
||||
})) ?? [],
|
||||
})
|
||||
private _schema = memoizeOne(
|
||||
(
|
||||
formatEntityAttributeValue: FormatEntityAttributeValueFunc,
|
||||
stateObj: MediaPlayerEntity | undefined
|
||||
) =>
|
||||
customizableListSchema({
|
||||
field: "sound_modes",
|
||||
options:
|
||||
stateObj?.attributes.sound_mode_list?.map((mode) => ({
|
||||
value: mode,
|
||||
label: formatEntityAttributeValue(stateObj, "sound_mode", mode),
|
||||
})) ?? [],
|
||||
})
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const stateObj = this.context?.entity_id
|
||||
? (this.hass.states[this.context.entity_id] as
|
||||
MediaPlayerEntity | undefined)
|
||||
: undefined;
|
||||
|
||||
const data = customizableListData(this._config, "sound_modes");
|
||||
const schema = this._schema(stateObj);
|
||||
const schema = this._schema(
|
||||
this._formatEntityAttributeValue,
|
||||
this._stateObj
|
||||
);
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -74,11 +94,7 @@ export class HuiMediaPlayerSoundModeCardFeatureEditor
|
||||
private _valueChanged(
|
||||
ev: ValueChangedEvent<MediaPlayerSoundModeCardFeatureConfig>
|
||||
): void {
|
||||
const stateObj = this.context?.entity_id
|
||||
? (this.hass!.states[this.context.entity_id] as
|
||||
MediaPlayerEntity | undefined)
|
||||
: undefined;
|
||||
const defaults = stateObj?.attributes.sound_mode_list ?? [];
|
||||
const defaults = this._stateObj?.attributes.sound_mode_list ?? [];
|
||||
const config =
|
||||
processCustomizableListValue<MediaPlayerSoundModeCardFeatureConfig>(
|
||||
ev.detail.value,
|
||||
@@ -91,7 +107,7 @@ export class HuiMediaPlayerSoundModeCardFeatureEditor
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) =>
|
||||
this.hass!.localize(
|
||||
this._localize(
|
||||
`ui.panel.lovelace.editor.features.types.media-player-sound-mode.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
+46
-30
@@ -1,11 +1,23 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../../common/decorators/transform";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { FormatEntityAttributeValueFunc } from "../../../../common/translations/entity-state";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { SchemaUnion } from "../../../../components/ha-form/types";
|
||||
import { formattersContext } from "../../../../data/context";
|
||||
import type { MediaPlayerEntity } from "../../../../data/media-player";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
|
||||
import type {
|
||||
HomeAssistantFormatters,
|
||||
ValueChangedEvent,
|
||||
} from "../../../../types";
|
||||
import type {
|
||||
LovelaceCardFeatureContext,
|
||||
MediaPlayerSourceCardFeatureConfig,
|
||||
@@ -22,47 +34,55 @@ export class HuiMediaPlayerSourceCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
|
||||
private _stateObj?: MediaPlayerEntity;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
@transform<HomeAssistantFormatters, FormatEntityAttributeValueFunc>({
|
||||
transformer: (formatters) => formatters?.formatEntityAttributeValue,
|
||||
})
|
||||
private _formatEntityAttributeValue!: FormatEntityAttributeValueFunc;
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: MediaPlayerSourceCardFeatureConfig;
|
||||
|
||||
public setConfig(config: MediaPlayerSourceCardFeatureConfig): void {
|
||||
this._config = config;
|
||||
}
|
||||
|
||||
private _schema = memoizeOne((stateObj: MediaPlayerEntity | undefined) =>
|
||||
customizableListSchema({
|
||||
field: "sources",
|
||||
options:
|
||||
stateObj?.attributes.source_list?.map((source) => ({
|
||||
value: source,
|
||||
label: this.hass!.formatEntityAttributeValue(
|
||||
stateObj,
|
||||
"source",
|
||||
source
|
||||
),
|
||||
})) ?? [],
|
||||
})
|
||||
private _schema = memoizeOne(
|
||||
(
|
||||
formatEntityAttributeValue: FormatEntityAttributeValueFunc,
|
||||
stateObj: MediaPlayerEntity | undefined
|
||||
) =>
|
||||
customizableListSchema({
|
||||
field: "sources",
|
||||
options:
|
||||
stateObj?.attributes.source_list?.map((source) => ({
|
||||
value: source,
|
||||
label: formatEntityAttributeValue(stateObj, "source", source),
|
||||
})) ?? [],
|
||||
})
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const stateObj = this.context?.entity_id
|
||||
? (this.hass.states[this.context.entity_id] as
|
||||
MediaPlayerEntity | undefined)
|
||||
: undefined;
|
||||
|
||||
const data = customizableListData(this._config, "sources");
|
||||
const schema = this._schema(stateObj);
|
||||
const schema = this._schema(
|
||||
this._formatEntityAttributeValue,
|
||||
this._stateObj
|
||||
);
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@@ -74,11 +94,7 @@ export class HuiMediaPlayerSourceCardFeatureEditor
|
||||
private _valueChanged(
|
||||
ev: ValueChangedEvent<MediaPlayerSourceCardFeatureConfig>
|
||||
): void {
|
||||
const stateObj = this.context?.entity_id
|
||||
? (this.hass!.states[this.context.entity_id] as
|
||||
MediaPlayerEntity | undefined)
|
||||
: undefined;
|
||||
const defaults = stateObj?.attributes.source_list ?? [];
|
||||
const defaults = this._stateObj?.attributes.source_list ?? [];
|
||||
const config =
|
||||
processCustomizableListValue<MediaPlayerSourceCardFeatureConfig>(
|
||||
ev.detail.value,
|
||||
@@ -91,7 +107,7 @@ export class HuiMediaPlayerSourceCardFeatureEditor
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) =>
|
||||
this.hass!.localize(
|
||||
this._localize(
|
||||
`ui.panel.lovelace.editor.features.types.media-player-source.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
+25
-17
@@ -1,12 +1,17 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { SchemaUnion } from "../../../../components/ha-form/types";
|
||||
import { supportsFeature } from "../../../../common/entity/supports-feature";
|
||||
import { MediaPlayerEntityFeature } from "../../../../data/media-player";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type {
|
||||
LovelaceCardFeatureContext,
|
||||
MediaPlayerVolumeButtonsCardFeatureConfig,
|
||||
@@ -18,10 +23,16 @@ export class HuiMediaPlayerVolumeButtonsCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
|
||||
private _stateObj?: HassEntity;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: MediaPlayerVolumeButtonsCardFeatureConfig;
|
||||
|
||||
public setConfig(config: MediaPlayerVolumeButtonsCardFeatureConfig): void {
|
||||
@@ -52,16 +63,13 @@ export class HuiMediaPlayerVolumeButtonsCardFeatureEditor
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const stateObj = this.context?.entity_id
|
||||
? this.hass.states[this.context.entity_id]
|
||||
: undefined;
|
||||
const supportsMute =
|
||||
!!stateObj &&
|
||||
supportsFeature(stateObj, MediaPlayerEntityFeature.VOLUME_MUTE);
|
||||
!!this._stateObj &&
|
||||
supportsFeature(this._stateObj, MediaPlayerEntityFeature.VOLUME_MUTE);
|
||||
|
||||
const data: MediaPlayerVolumeButtonsCardFeatureConfig = {
|
||||
type: "media-player-volume-buttons",
|
||||
@@ -73,10 +81,9 @@ export class HuiMediaPlayerVolumeButtonsCardFeatureEditor
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
.computeLabel=${this._computeLabelCallback(this._localize)}
|
||||
@value-changed=${this._valueChanged}
|
||||
></ha-form>
|
||||
`;
|
||||
@@ -86,12 +93,13 @@ export class HuiMediaPlayerVolumeButtonsCardFeatureEditor
|
||||
fireEvent(this, "config-changed", { config: ev.detail.value });
|
||||
}
|
||||
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) =>
|
||||
this.hass!.localize(
|
||||
`ui.panel.lovelace.editor.features.types.media-player-volume-buttons.${schema.name}`
|
||||
);
|
||||
private _computeLabelCallback = memoizeOne(
|
||||
(localize: LocalizeFunc) =>
|
||||
(schema: SchemaUnion<ReturnType<typeof this._schema>>) =>
|
||||
localize(
|
||||
`ui.panel.lovelace.editor.features.types.media-player-volume-buttons.${schema.name}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
+26
-17
@@ -1,12 +1,18 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type { SchemaUnion } from "../../../../components/ha-form/types";
|
||||
import { supportsFeature } from "../../../../common/entity/supports-feature";
|
||||
import { MediaPlayerEntityFeature } from "../../../../data/media-player";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
|
||||
import type { ValueChangedEvent } from "../../../../types";
|
||||
import type {
|
||||
LovelaceCardFeatureContext,
|
||||
MediaPlayerVolumeSliderCardFeatureConfig,
|
||||
@@ -18,10 +24,16 @@ export class HuiMediaPlayerVolumeSliderCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
|
||||
private _stateObj?: HassEntity;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _config?: MediaPlayerVolumeSliderCardFeatureConfig;
|
||||
|
||||
public setConfig(config: MediaPlayerVolumeSliderCardFeatureConfig): void {
|
||||
@@ -40,16 +52,13 @@ export class HuiMediaPlayerVolumeSliderCardFeatureEditor
|
||||
);
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const stateObj = this.context?.entity_id
|
||||
? this.hass.states[this.context.entity_id]
|
||||
: undefined;
|
||||
const supportsMute =
|
||||
!!stateObj &&
|
||||
supportsFeature(stateObj, MediaPlayerEntityFeature.VOLUME_MUTE);
|
||||
!!this._stateObj &&
|
||||
supportsFeature(this._stateObj, MediaPlayerEntityFeature.VOLUME_MUTE);
|
||||
|
||||
const data: MediaPlayerVolumeSliderCardFeatureConfig = {
|
||||
type: "media-player-volume-slider",
|
||||
@@ -60,10 +69,9 @@ export class HuiMediaPlayerVolumeSliderCardFeatureEditor
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${data}
|
||||
.schema=${schema}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
.computeLabel=${this._computeLabelCallback(this._localize)}
|
||||
@value-changed=${this._valueChanged}
|
||||
></ha-form>
|
||||
`;
|
||||
@@ -75,12 +83,13 @@ export class HuiMediaPlayerVolumeSliderCardFeatureEditor
|
||||
fireEvent(this, "config-changed", { config: ev.detail.value });
|
||||
}
|
||||
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
) =>
|
||||
this.hass!.localize(
|
||||
`ui.panel.lovelace.editor.features.types.media-player-volume-slider.${schema.name}`
|
||||
);
|
||||
private _computeLabelCallback = memoizeOne(
|
||||
(localize: LocalizeFunc) =>
|
||||
(schema: SchemaUnion<ReturnType<typeof this._schema>>) =>
|
||||
localize(
|
||||
`ui.panel.lovelace.editor.features.types.media-player-volume-slider.${schema.name}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user