Compare commits

..
Author SHA1 Message Date
Petar Petrov 8a194ef1e6 Drop a stale auth callback instead of retrying it on every reload 2026-11-18 07:59:22 +01:00
Jan-Philipp BeneckeandCopilot Autofix powered by AI 04ab43929e Show update release notes messages in the more info dialog (#55388)
* Show update release notes messages in the more info dialog

* Replace message display with ha-markdown component

Co-authored-by: Copilot Autofix powered by AI <[email protected]>

* Add RTL support for message display in ha-markdown component

* Add language parameter to updateReleaseNotes function

* Fix position

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-18 06:47:54 +01:00
Erwin Douna 10b7f5ffb6 Move database analyze to the Storage page toolbar (#55982)
* Move database analyze to the Storage page toolbar

* Load the database report once recorder is available
2026-11-18 00:10:47 -05:00
Erwin Douna cce6a720f3 Show integration icons in the startup details (#55981)
* Show integration icons in the startup details

* Use ha-domain-icon in startup details
2026-11-17 14:10:45 +01:00
Maarten Lakerveld c8f6a9ef77 Revert "Let users hide entities from the maintenance page (#55610)" (#55979)
This reverts commit 49e5220634.
2026-11-17 12:27:02 +01:00
Raman GuptaandClaude Opus 5.5 94bd98d78d Call debounce immediately on the first call after cancel (#55963)
cancel() cleared the timer but kept its id, so with immediate=true the
next call saw a pending timer and was delayed by the wait instead of
firing on the leading edge.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 11:53:06 +01:00
Erwin Douna 0904c2a547 Show startup progress while Home Assistant starts (#55834)
* Show startup progress while Home Assistant starts

Replace the startup toast that named the longest running integration with a compact progress card: phase, integrations set up out of scheduled, and expandable details for active, failed and retrying integrations. Completion is only shown once Core is running.

* Address startup progress review feedback

Use a native toggle button with aria-expanded, mirror the centering in RTL, raise secondary text contrast, consume localize from context and keep listening after dismiss so the completion toast is accurate.

* Keep startup progress clear of toasts

Only offer the integrations action to admins, announce only phase and issues, lift the toast stack above the card and reattach the card after the launch screen swap.

* Move startup details into a dialog

* Handle older cores and late snapshots in startup progress

* Follow the new startup progress payload

* Make the startup toast minimal

* Add fallbacks to the startup toast
2026-11-17 11:39:36 +01:00
Raman GuptaandClaude Opus 5.5 2fd66939e7 Limit fraction digits in formatNumber to what Intl supports (#55968)
To keep trailing zeros, a numeric string's decimal places were used as
the fraction digits, and Intl.NumberFormat throws a RangeError for more
than 100. Cap them at 100.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 11:31:46 +01:00
Matthias AlphartandClaude Fable 5.2 5e340cb4e5 Fix automation editor crash when a condition row holds a service action (#55959)
Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-17 11:29:28 +01:00
Raman GuptaandClaude Opus 5.5 8b2dc28d0f Fix groupBy for keys that exist on Object.prototype (#55964)
Grouping into a plain object made `key in result` true for keys such as
constructor or toString, so push was called on the inherited function
and threw, and a __proto__ key replaced the result's prototype. Group
into a Map and convert it with Object.fromEntries instead.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 09:28:36 +01:00
Paul Bottein 8d933e85d4 Add range selection and highlight to charts (#55472)
* Add range selection and highlight to charts

* Keep range selection on release outside the chart and simplify the highlight

* Add range selection examples to the statistics chart gallery page

* Unify chart selection with a fade mask and a clear button in the gallery

* Move chart selection and highlight into ha-chart-base

* Clear stale chart masks after a data update

* Make chart selection opt-in with select-mode and cache the mask color

* Keep drag to zoom when the chart select mode is point

* Only add empty chart mask areas once a mask was shown

* Set the mask flag where the mask is applied and skip hidden statistics when snapping
2026-11-17 08:50:22 +01:00
Raman GuptaandClaude Opus 5.5 b93869e668 Fix IP address validation for leading zeros and embedded IPv4 (#55972)
IPv4 octets accepted leading zeros such as 010.1.1.1, which the backend
rejects. The IPv6 pattern also missed addresses ending in dotted IPv4
after five or six groups, such as 1:2:3:4:5:6:1.2.3.4. Build the IPv6
pattern from the RFC 3986 grammar, which covers every IPv4 suffix form
and reuses the stricter IPv4 octet.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 09:13:01 +02:00
Raman GuptaandClaude Opus 5.5 bfd511deaf Quote CSV values that contain line breaks (#55965)
csvSafeString only quoted values containing a comma or quote, so a
logbook message or state with a line break split its row in the
exported CSV.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 09:08:56 +02:00
Raman GuptaandClaude Opus 5.5 eeec2d4662 Ignore unparsable date query params (#55971)
A history or logbook URL with a start_date or end_date that couldn't be
parsed decoded to an Invalid Date, and createHistoryLogbookUrl threw a
RangeError calling toISOString on it. Leave such dates out so the panel
uses its default range.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 09:08:17 +02:00
renovate[bot] 500249d996 Update pnpm to v12.21.0 (#55978)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-17 08:31:11 +02:00
Norbert Rittel a4157a490d Change "Power sources (graph)" to "Power profile (graph)" (#55951)
Change "power sources (graph)" to "power profile (graph)"
2026-11-17 08:18:59 +02:00
Raman GuptaandClaude Opus 5.5 d24ec6d34f Parse animation duration units regardless of case (#55970)
CSS units are case-insensitive, but only lowercase s and ms were
recognized, so 3S was read as 3 ms and 300Ms as 300 seconds.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 07:07:54 +01:00
Thomas van TilburgandCopilot Autofix powered by AI bef72ec5da Allow selecting a sensor for battery capacity (#55713)
* Allow selecting a sensor for battery capacity

* Update accessible label for battery capacity input

Co-authored-by: Copilot Autofix powered by AI <[email protected]>

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-17 08:07:40 +02:00
Raman GuptaandClaude Opus 5.5 87add82ad0 Uppercase first letters outside the BMP in capitalizeFirstLetter (#55967)
charAt(0) returns only the high surrogate of a letter outside the BMP,
which has no uppercase form, so the letter was left unchanged. Use the
first code point instead.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 07:06:27 +01:00
Raman GuptaandClaude Opus 5.5 eb70761886 Show the next unit in bytesToString when rounding reaches it (#55974)
The unit was picked before rounding, so a value just below a unit
boundary, such as 1048575 bytes, rounded to 1024 KB instead of 1 MB.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 07:05:05 +01:00
Raman GuptaandClaude Opus 5.5 74a2d3636b Transliterate Cyrillic х as kh in slugify (#55973)
х was also listed in the single-character map, which runs first and
replaced it with h, so its kh entry in complex_cyrillic was never used.
Remove it from the single-character map.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-17 07:03:22 +01:00
renovate[bot] f03740c446 Update Playwright (#55976)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-17 07:00:37 +01:00
renovate[bot] 4873df0df6 Update dependency eslint to v10.15.0 (#55977)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-17 07:00:21 +01:00
Erwin Douna d08b734afd Add database usage card to the storage page (#55659)
* Add database usage card to the storage page

* Address database usage card review feedback

* Open settings for disabled entities and use theme color variables

* Address review feedback on the database card

* Analyze the database on request

Follow the reworked recorder/database_usage response: separate entities and statistics, nullable tables, free and WAL bytes.

* Only make rows with entity settings clickable
2026-11-16 21:21:35 +01:00
renovate[bot] 4d1fc1225d Update dependency serve to v14.2.8 (#55956)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-16 20:33:48 +02:00
Dusan Cervenka 18bcddaa20 Use each light's Kelvin range in the service color temperature slider (#55947)
* Use each light's Kelvin range in the service color temperature slider

The light turn-on action advertised one 2000-6500 K slider for every
light, so a device with a different range could not be set from the
automation editor. The slider now follows the targeted lights.

* Limit the Kelvin slider to the lights an action actually calls.

The optional color temperature field now starts inside that range. The adjustment stays on light.color_temp_kelvin, and an area target no longer includes a light assigned to another area.

* Ignore secondary lights and normalize entity ids in the Kelvin range.

Service calls skip hidden and categorized lights reached only through an area or device, and legacy entity ids can be comma-separated or mixed-case.

* Use targeted entity ranges inside the color temperature selector.

The service form already supplies those entities, so the slider no longer resolves targets on its own.

* Leave the stored color temperature when the slider range changes.

The selector shows the targeted lights' Kelvin bounds, and core already clamps the value a light can produce.

* Start an optional Kelvin value inside the targeted lights' range.

Checking the field creates the stored value, so it matches the slider. Later light updates leave that value alone.

* Move the optional Kelvin default into a follow-up.

The selector change stands on its own.
2026-11-16 19:04:07 +01:00
73 changed files with 3227 additions and 1070 deletions

No files matched your search

+4 -4
View File
@@ -38,7 +38,7 @@ jobs:
name: Prepare container dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
options: --user 1001
defaults:
run:
@@ -155,7 +155,7 @@ jobs:
- prepare-container-dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
options: --user 1001 --ipc=host
defaults:
run:
@@ -207,7 +207,7 @@ jobs:
- prepare-container-dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
options: --user 1001 --ipc=host
defaults:
run:
@@ -261,7 +261,7 @@ jobs:
- prepare-container-dependencies
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
options: --user 1001 --ipc=host
defaults:
run:
+19
View File
@@ -0,0 +1,19 @@
import type { ReactiveElement } from "lit";
import { ContextSubscriptionController } from "../../../src/common/decorators/consume";
import { uiContext } from "../../../src/data/context";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
// A demo that provides its own hass hides the gallery theme from its children,
// so pass the gallery light or dark mode on to it.
export const followGalleryTheme = (
host: ReactiveElement,
hass: MockHomeAssistant
) =>
new ContextSubscriptionController(host, uiContext, (ui) => {
if (ui) {
hass.updateHass({
themes: ui.themes,
selectedTheme: ui.selectedTheme,
});
}
});
@@ -10,6 +10,7 @@ import type {
} from "../../../../src/data/history";
import { provideHass } from "../../../../src/fake_data/provide_hass";
import type { HomeAssistant } from "../../../../src/types";
import { followGalleryTheme } from "../../data/follow-gallery-theme";
const HOUR = 60 * 60 * 1000;
const HOURS = 48;
@@ -166,6 +167,7 @@ export class DemoStateHistoryCharts extends LitElement {
super.firstUpdated(changedProps);
const hass = provideHass(this);
hass.updateTranslations(null, "en");
followGalleryTheme(this, hass);
hass.addEntities(ENTITIES);
}
@@ -1,7 +1,9 @@
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 type { ChartSelectMode } from "../../../../src/components/chart/ha-chart-base";
import "../../../../src/components/chart/statistics-chart";
import "../../../../src/components/ha-button";
import "../../../../src/components/ha-card";
import type {
Statistics,
@@ -11,7 +13,9 @@ import type {
} from "../../../../src/data/recorder";
import { StatisticMeanType } from "../../../../src/data/recorder";
import { provideHass } from "../../../../src/fake_data/provide_hass";
import type { HASSDomEvent } from "../../../../src/common/dom/fire_event";
import type { HomeAssistant } from "../../../../src/types";
import { followGalleryTheme } from "../../data/follow-gallery-theme";
const HOUR = 60 * 60 * 1000;
const HOURS = 48;
@@ -108,6 +112,64 @@ interface Example {
height?: string;
}
interface TimeRange {
start: number;
end: number;
}
interface RangeExample {
id: string;
title: string;
description: string;
statistics: Statistics;
statTypes: StatisticType[];
chartType: "line" | "bar";
unit: string;
selectMode: ChartSelectMode;
hint: string;
}
const RANGE_EXAMPLES: RangeExample[] = [
{
id: "point",
title: "Point selection",
description:
"With select-mode set to point, a click selects the hour that contains it, and everything outside fades. Dragging still zooms.",
statistics: { [HEAT_PUMP_ID]: HEAT_PUMP },
statTypes: ["change"],
chartType: "bar",
unit: "kWh",
selectMode: "point",
hint: "Click on a bar to select its hour.",
},
{
id: "range-bar",
title: "Range selection on bars",
description:
"With select-mode set to range, dragging selects a time range instead of zooming, so several bars can be selected at once. A click still selects one bar.",
statistics: { [HEAT_PUMP_ID]: HEAT_PUMP },
statTypes: ["change"],
chartType: "bar",
unit: "kWh",
selectMode: "range",
hint: "Click or drag on the chart to select one or more bars.",
},
{
id: "range",
title: "Range selection on lines",
description: "The same on a line chart.",
statistics: { [LIVING_ROOM_ID]: LIVING_ROOM },
statTypes: ["mean", "min", "max"],
chartType: "line",
unit: "°C",
selectMode: "range",
hint: "Click or drag on the chart to select a period.",
},
];
const formatRange = (range: TimeRange) =>
`${new Date(range.start).toLocaleString()} to ${new Date(range.end).toLocaleString()}`;
const EXAMPLES: Example[] = [
{
title: "Sum as bars",
@@ -159,17 +221,20 @@ const EXAMPLES: Example[] = [
export class DemoStatisticsChart extends LitElement {
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _selections: Record<string, TimeRange | undefined> = {};
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
const hass = provideHass(this);
hass.updateTranslations(null, "en");
followGalleryTheme(this, hass);
}
protected render() {
if (!this.hass) {
return nothing;
}
return EXAMPLES.map(
return html`${EXAMPLES.map(
(example) => html`
<ha-card header=${example.title}>
<div class="card-content">
@@ -191,7 +256,66 @@ export class DemoStatisticsChart extends LitElement {
</div>
</ha-card>
`
);
)}
${RANGE_EXAMPLES.map((example) => this._renderRangeExample(example))}`;
}
private _renderRangeExample(example: RangeExample) {
const selection = this._selections[example.id];
return html`
<ha-card header=${example.title}>
<div class="card-content">
<p>${example.description}</p>
<statistics-chart
.statisticsData=${example.statistics}
.metadata=${METADATA}
.names=${NAMES}
.statTypes=${example.statTypes}
.chartType=${example.chartType}
period="hour"
.unit=${example.unit}
.startTime=${START}
.endTime=${END}
.highlight=${selection}
.clickForMoreInfo=${false}
data-example=${example.id}
.selectMode=${example.selectMode}
hide-legend
@chart-select=${this._rangeSelected}
></statistics-chart>
<div class="selection">
${
selection
? html`
<span>${formatRange(selection)}</span>
<ha-button
appearance="plain"
size="s"
data-example=${example.id}
@click=${this._clearSelection}
>
Clear
</ha-button>
`
: html`<span class="hint">${example.hint}</span>`
}
</div>
</div>
</ha-card>
`;
}
private _rangeSelected(ev: HASSDomEvent<HASSDomEvents["chart-select"]>) {
const id = (ev.currentTarget as HTMLElement).dataset.example!;
this._selections = {
...this._selections,
[id]: ev.detail,
};
}
private _clearSelection(ev: Event) {
const id = (ev.currentTarget as HTMLElement).dataset.example!;
this._selections = { ...this._selections, [id]: undefined };
}
static styles = css`
@@ -202,6 +326,20 @@ export class DemoStatisticsChart extends LitElement {
p {
margin-top: 0;
}
.selection {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--ha-space-2);
min-height: 48px;
margin-top: var(--ha-space-2);
padding: 0 var(--ha-space-2) 0 var(--ha-space-4);
border-radius: var(--ha-border-radius-lg);
background-color: var(--secondary-background-color);
}
.hint {
color: var(--secondary-text-color);
}
`;
}
+11 -2
View File
@@ -250,7 +250,16 @@ class DemoMoreInfoUpdate extends LitElement {
"update/release_notes",
(msg: { type: string; entity_id: string }) => {
if (msg.entity_id === "update.update16") {
return LONG_TEXT;
return {
release_notes: LONG_TEXT,
messages: [
{
severity: "warning",
message:
"Do not restart, remove power from, or otherwise interrupt the device while the update is in progress.",
},
],
};
}
if (msg.entity_id === "update.update17") {
return Promise.reject({
@@ -261,7 +270,7 @@ class DemoMoreInfoUpdate extends LitElement {
if (msg.entity_id === "update.update18") {
return undefined;
}
return null;
return { release_notes: null, messages: [] };
}
);
}
+4 -4
View File
@@ -151,7 +151,7 @@
"@lokalise/node-api": "17.0.1",
"@octokit/auth-oauth-device": "8.0.5",
"@octokit/rest": "22.0.1",
"@playwright/test": "1.65.0",
"@playwright/test": "1.65.1",
"@rsdoctor/rspack-plugin": "1.6.5",
"@rspack/core": "2.3.2",
"@rspack/dev-server": "2.2.2",
@@ -177,7 +177,7 @@
"browserslist-useragent-regexp": "4.1.4",
"core-js-compat": "3.51.0",
"del": "9.0.1",
"eslint": "10.14.0",
"eslint": "10.15.0",
"eslint-config-prettier": "10.1.8",
"eslint-import-resolver-webpack": "0.13.11",
"eslint-plugin-import-x": "4.18.1",
@@ -208,7 +208,7 @@
"pinst": "3.0.0",
"prettier": "3.10.1",
"rspack-manifest-plugin": "5.2.2",
"serve": "14.2.7",
"serve": "14.2.8",
"sinon": "22.1.0",
"tar": "7.5.23",
"terser-webpack-plugin": "5.6.1",
@@ -222,7 +222,7 @@
"webpackbar": "7.0.0",
"workbox-build": "7.4.1"
},
"packageManager": "[email protected]0.0",
"packageManager": "[email protected]1.0",
"volta": {
"node": "24.22.3"
}
+154 -147
View File
@@ -7,162 +7,162 @@ importers:
configDependencies: {}
packageManagerDependencies:
pnpm:
specifier: 12.20.0
version: 12.20.0
specifier: 12.21.0
version: 12.21.0
packages:
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-cRn0gBik+J8jjtio12bMRSRGsO/xBvy87rtldEY53rU+G1YY+MJb5tykWNfQJM9ZMTgpXFecYOd3dokT081N0w==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-iaWidxR5B9NUBpwMznCQu1yUpKB6BjTY5BYX2lORj76VsfINdj8Z8XWSzSNrGI8qlxa28Jzdp5fiaspzOaJZlA==}
cpu: [arm64]
os: [android]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-GRLjYtnDzwThGIqEAM5IwtbB95R9GopWXZ+136h1M7EUGTLkY5rD9veL7Xpg82PjEsFerdYK1cGzRGUBaXRi4g==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-35e5v3wlwjIYxDywq+R6/z8CE4gLOEgRxt18yqz1tMRLmx2mnW+CFJI2Q8+srTNjn7gykXUC0x1k195JNikC5A==}
cpu: [x64]
os: [android]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-W1/HpqljOibAKfiZWGugHBrsYSVIw7VOOle/zkRIMK49S4PUdJw0Fnpv0Xummo5RE59TLFWvEHYzsfOCd8yfBg==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-F5OyMX/6zLSowpTZEQRojbCmPS1Pq+fyRaIinslsIe6Glh3qbyQ52u+Fe0eEzSaRuIbWZkXmAAXSWh6Q5Wrlgg==}
cpu: [arm64]
os: [darwin]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-OU+Mfuk+pJQwnWSveYDbBRHPfOIILk24cn/Mrzg6rvf6CSAXnQEiUqwJYfokB3wDCw0s8N+q/AszVusc9CihIQ==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-EzpvcsaE6hrrgYeEiAFYd2rSgFybYyxXhkAY7K3y6Hg3loVfcyJ81hHczpFzi8lW5RXtUlFECRPZ8ZAMRFQYYg==}
cpu: [x64]
os: [darwin]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-GMizEmKm/90zRw48YpYcydkc95IM9+BwvfG7RYYnby70JKxklCIAayG/IyykpbBrQfl2wpxZSVok8Xw+tu+SDA==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-wNjuEnmdLks4aayPu/QZWQ5tQM9Jn+odUp/vwQM8BXRYoulkTZhtZTHoD60N6mUdLWef1hgUeUh8llNGEUsimw==}
cpu: [x64]
os: [freebsd]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-sNhQjnRnpoFSQFiQ8N9ktQuLF7t9e8IB4DB3YAK9CvY+mw6P63IAEeBJPKj+pox0nN8UdlTFHAkLWtuHN/q+yw==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-Ceit9zn4g5ZqCJtx1fV8eJE7p8aeXMrGZ+Dc01vRqZLIUNgNeI+Ur0ruyqxtsnJx6rGADyXzohumxPLHjaJ5AQ==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-g8rFjUHaNKEkuQSqMCu+sA5PldhfMdQDc088H1H/SEV01vlCsJXXoGK4vLKSefEmgzVmgsG+9ozqeMmDDBE3Xw==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-4Oj/iF2TDCe2lcH0n4TupPR5sSdrNLclJB6xBElLMPCUOAvBhdf2rRlSaO5M4erJ6g4Fyy7YTXTpcmfFsKyxEA==}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-oUTewHLppAqn5CvyPqKkgFWXpZj2Z0QjViilgU8DaYoStRHFojRJK26z7xklyEy9uTLnrkJHA5/hp6KUKIHllw==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-s2o7rdSDeUTBFsNqxptpZXlTgT6cojmMVUOvTQvFNSv6Easian02ha4tR32fwwD97Au4YzIIjMCwywCF4D82Sw==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-WrihJXJQQaFWz0IFSaWNQht1c+8c7QVyReHGdwL/In1/ql5cizUMxzXOcoy6GyPs+h1UvvNUTaflMLA0cE1oLg==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-EYv3GzxeBTITCuM3yGHHbpRFpUvyulkXpQ6LsjKAQNL3iaba1E6h9iDmlouLb3Io4AMMsfdk0/uG6poQ41uewA==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-58HYnkciIaxScbGXASyJiYaKAfOb2MrQ5Ed+OKG7bxPhfe/fV7NZTNKdgxHoxKgO3jrso9mZaLnKHvbb7lGWCw==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-8VXGNGVNEfs7pL9GTZOzFxjFEnMt4WL3rLOADR5/kPQ7ROTV9GfpVI2DPO/zArXFSkvfc9Zad/WypHLbvzoaTQ==}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-DHS61C8f5Yjt4X3R4HnfTtihVPCC3vpCgE3zLIfUAyy1J5Gh4sgZSMGII6V595X7W29mH4kUjKrCiR0A6atzTg==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-MnC5vpIXYubhDZCgCwlfJMg7Cg6HupN2IuouT9gD/tUmOfVdQYqeyYccWbthyo/Jeto8de1oQlxeRN1+1Hl2DQ==}
cpu: [x64]
os: [linux]
libc: [musl]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-FQlCX0bSn8CBQQodfWYIv9Nq98/Zpxaoj5onCzHuSdfaO7bGXUDZAtscaaEuJnxkIQOle7mVOLssoEy4Gp9shA==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-8eufCjHXspKbNS/kh8q4Q0gqJoOuvC4Q5pgos6XS8By/nAMtP+jf8F1Cw9er840kfAX+PJ/ts+A9qnLE91rvXQ==}
cpu: [x64]
os: [linux]
libc: [glibc]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-i9ZzFiiMovsgHIuQ8/i384O1fsWJ87GwzLeV+hFI1uDpFO88kPODtijMbi8UBUNhlpP4X/T9QDiy7/mdI4mHgA==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-eyh1M8hQZCkLWxuva7S/fc1SbFbgqg0/5di0dgWmyiuc2Io3dbWVihDun8X+XM8zsR5uhIDvvZpbS9aZQbCovg==}
cpu: [x64]
os: [netbsd]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-ghB0EKw7PHwTwB72c4nfPJmIPSbTJr/VpG2FBBckgMBLMVSj3xK9n12euTTSfAL6cABdBrtCwsXjjYs52BJexw==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-7xTxxUXo/grRLivSeIl6B21gnsz7ooe5EMPcJmQqwxc8WLJVReN8MzrlHru8bqXfVr4X3+6ZGZscntKenlCBqQ==}
cpu: [arm64]
os: [win32]
'@pnpm/[email protected]0.0':
resolution: {integrity: sha512-VJxSNS89UWgkDLdI5K2oW009V63mtJn1LB5+G5a3jXG9IYc79U9lEvDEmFU4/LNGhfWwkvx7b40UtIqNewwp4A==}
'@pnpm/[email protected]1.0':
resolution: {integrity: sha512-9TpkJemVApxJ1Z1w0ZFGN+AuSx4nJOqXSJUqMqDvaXTYwGOzvBiiWdFP9GN0ketiWCQS1Q0/pza2E7I3pP0OBQ==}
cpu: [x64]
os: [win32]
[email protected]0.0:
resolution: {integrity: sha512-bMx0mXzO9OZ5mXiOGNv7+lg+KoSWaGaNtHB7aoMGZi9HFW5lAjKphb0+wkz5NkwaoVTTflHteqxiwc0eOvyAww==}
[email protected]1.0:
resolution: {integrity: sha512-Zv2CeO4ok1zpUXktNDZ/869cQyonVkRYIwKVM4NbjaUpu+C+UTCv1W7QcT+4eJ5Hutgtk71a4v5UsVVi1idu8A==}
engines: {node: '>=18'}
hasBin: true
snapshots:
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
'@pnpm/[email protected]0.0':
'@pnpm/[email protected]1.0':
optional: true
[email protected]0.0:
[email protected]1.0:
optionalDependencies:
'@pnpm/exe.android-arm64': 12.20.0
'@pnpm/exe.android-x64': 12.20.0
'@pnpm/exe.darwin-arm64': 12.20.0
'@pnpm/exe.darwin-x64': 12.20.0
'@pnpm/exe.freebsd-x64': 12.20.0
'@pnpm/exe.linux-arm64': 12.20.0
'@pnpm/exe.linux-arm64-musl': 12.20.0
'@pnpm/exe.linux-ppc64': 12.20.0
'@pnpm/exe.linux-riscv64': 12.20.0
'@pnpm/exe.linux-s390x': 12.20.0
'@pnpm/exe.linux-x64': 12.20.0
'@pnpm/exe.linux-x64-musl': 12.20.0
'@pnpm/exe.netbsd-x64': 12.20.0
'@pnpm/exe.win32-arm64': 12.20.0
'@pnpm/exe.win32-x64': 12.20.0
'@pnpm/exe.android-arm64': 12.21.0
'@pnpm/exe.android-x64': 12.21.0
'@pnpm/exe.darwin-arm64': 12.21.0
'@pnpm/exe.darwin-x64': 12.21.0
'@pnpm/exe.freebsd-x64': 12.21.0
'@pnpm/exe.linux-arm64': 12.21.0
'@pnpm/exe.linux-arm64-musl': 12.21.0
'@pnpm/exe.linux-ppc64': 12.21.0
'@pnpm/exe.linux-riscv64': 12.21.0
'@pnpm/exe.linux-s390x': 12.21.0
'@pnpm/exe.linux-x64': 12.21.0
'@pnpm/exe.linux-x64-musl': 12.21.0
'@pnpm/exe.netbsd-x64': 12.21.0
'@pnpm/exe.win32-arm64': 12.21.0
'@pnpm/exe.win32-x64': 12.21.0
---
lockfileVersion: '9.0'
@@ -497,7 +497,7 @@ importers:
version: 4.23.1([email protected])
'@eslint/js':
specifier: 10.0.1
version: 10.0.1([email protected]4.0([email protected]))
version: 10.0.1([email protected]5.0([email protected]))
'@gfx/zopfli':
specifier: 1.0.15
version: 1.0.15
@@ -506,7 +506,7 @@ importers:
version: link:packages/components
'@html-eslint/eslint-plugin':
specifier: 0.68.0
version: 0.68.0([email protected]4.0([email protected]))
version: 0.68.0([email protected]5.0([email protected]))
'@lokalise/node-api':
specifier: 17.0.1
version: 17.0.1
@@ -517,8 +517,8 @@ importers:
specifier: 22.0.1
version: 22.0.1
'@playwright/test':
specifier: 1.65.0
version: 1.65.0
specifier: 1.65.1
version: 1.65.1
'@rsdoctor/rspack-plugin':
specifier: 1.6.5
version: 1.6.5(@emnapi/[email protected])(@emnapi/[email protected])(@rsbuild/[email protected]([email protected]))(@rspack/[email protected](@swc/[email protected]))([email protected])
@@ -595,29 +595,29 @@ importers:
specifier: 9.0.1
version: 9.0.1
eslint:
specifier: 10.14.0
version: 10.14.0([email protected])
specifier: 10.15.0
version: 10.15.0([email protected])
eslint-config-prettier:
specifier: 10.1.8
version: 10.1.8([email protected]4.0([email protected]))
version: 10.1.8([email protected]5.0([email protected]))
eslint-import-resolver-webpack:
specifier: 0.13.11
version: 0.13.11([email protected])
eslint-plugin-import-x:
specifier: 4.18.1
version: 4.18.1(@typescript-eslint/[email protected]([email protected]4.0([email protected]))([email protected])([email protected]))([email protected]4.0([email protected]))([email protected])
version: 4.18.1(@typescript-eslint/[email protected]([email protected]5.0([email protected]))([email protected])([email protected]))([email protected]5.0([email protected]))([email protected])
eslint-plugin-lit:
specifier: 2.3.1
version: 2.3.1([email protected]4.0([email protected]))
version: 2.3.1([email protected]5.0([email protected]))
eslint-plugin-lit-a11y:
specifier: 5.1.3
version: 5.1.3([email protected]4.0([email protected]))
version: 5.1.3([email protected]5.0([email protected]))
eslint-plugin-unused-imports:
specifier: 4.4.1
version: 4.4.1(@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]4.0([email protected]))([email protected])([email protected]))([email protected]4.0([email protected]))([email protected])([email protected]))([email protected]4.0([email protected]))
version: 4.4.1(@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]5.0([email protected]))([email protected])([email protected]))([email protected]5.0([email protected]))([email protected])([email protected]))([email protected]5.0([email protected]))
eslint-plugin-wc:
specifier: 3.1.0
version: 3.1.0([email protected]4.0([email protected]))
version: 3.1.0([email protected]5.0([email protected]))
fancy-log:
specifier: 2.0.0
version: 2.0.0
@@ -688,8 +688,8 @@ importers:
specifier: 5.2.2
version: 5.2.2(@rspack/[email protected](@swc/[email protected]))
serve:
specifier: 14.2.7
version: 14.2.7([email protected])
specifier: 14.2.8
version: 14.2.8([email protected])
sinon:
specifier: 22.1.0
version: 22.1.0
@@ -707,7 +707,7 @@ importers:
version: 6.0.3
typescript-eslint:
specifier: 8.72.2
version: 8.72.2([email protected]4.0([email protected]))([email protected])([email protected])
version: 8.72.2([email protected]5.0([email protected]))([email protected])([email protected])
vite:
specifier: 8.3.8
version: 8.3.8(@types/[email protected])([email protected])([email protected])
@@ -1960,8 +1960,8 @@ packages:
resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==}
engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0}
'@eslint/[email protected].5':
resolution: {integrity: sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==}
'@eslint/[email protected].6':
resolution: {integrity: sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
'@eslint/[email protected]':
@@ -2685,8 +2685,8 @@ packages:
'@parse5/[email protected]':
resolution: {integrity: sha512-zxRyTHkqb7WQMV8kTNBKWb1BeOFUKXBXTBWuxg9H9hfvQB3IwP6Iw2U75Ia5eyRxPNltmY7E8YAlz6zWwUnjKg==}
'@playwright/[email protected].0':
resolution: {integrity: sha512-iGURLGuKDLakSEl7Pgfv8h7f+XLT+V861Wfhz0zlEl5nyFuKUopdkFBPKqTllTUp06aOwPuH8iuUEb3yp3MpbQ==}
'@playwright/[email protected].1':
resolution: {integrity: sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==}
engines: {node: '>=20'}
hasBin: true
@@ -4561,8 +4561,8 @@ packages:
resolution: {integrity: sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==}
engines: {node: '>= 0.6'}
[email protected].1:
resolution: {integrity: sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==}
[email protected].2:
resolution: {integrity: sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==}
engines: {node: '>= 0.8.0'}
[email protected]:
@@ -4764,6 +4764,10 @@ packages:
resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}
engines: {node: '>=6'}
[email protected]:
resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==}
engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}
[email protected]:
resolution: {integrity: sha512-DtCOLG98P007x7wiiOmfI0fi3eIKyWiLTGJ2MDnVi/E04lWGbf+JzrRHMm0rgIIZJGtHpKpbVgLWHrv8xXpc3Q==}
engines: {node: '>=0.10.0'}
@@ -5051,8 +5055,8 @@ packages:
resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
[email protected]4.0:
resolution: {integrity: sha512-T0pNsxkb9IKmtQjhpK3d7nWOpFv+YHuMbTJnSVMoQblF0onvXfErrtp4V1jHtsQPan7dKaGVD0q1WCXnzMF31A==}
[email protected]5.0:
resolution: {integrity: sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
hasBin: true
peerDependencies:
@@ -6675,13 +6679,13 @@ packages:
resolution: {integrity: sha512-J8B6xqiO37sU/gkcMglv6h5Jbd9xNER7aHzpfRdNmV4IbQBzBpe4l9XmbG+xPF/znacgu2jfEw+wHffaq/YkXA==}
hasBin: true
[email protected].0:
resolution: {integrity: sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==}
[email protected].1:
resolution: {integrity: sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==}
engines: {node: '>=20'}
hasBin: true
[email protected].0:
resolution: {integrity: sha512-F3AMWcR44qMBt4kq+6Kb6mX7bjGXshktKFOPULd7reED6ZJWevjbNRqysP7q+AATE9kdPEZBibex1BYsvpVoeA==}
[email protected].1:
resolution: {integrity: sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==}
engines: {node: '>=20'}
hasBin: true
@@ -7050,8 +7054,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-CinAq1xWb0vR3twAv9evEU8cNWkXCb9kd5ePAHUKJBkOsUpR1wt/CvGdeca7vqumL1U5cSaeVQ6zZMxiJ3yWsg==}
[email protected].7:
resolution: {integrity: sha512-mTJ9LAyBwHhO2T/PNaI0oWxmKl7FFuJ+ZEHKL1rRO69fWV1Y4qcsFB3gpuD2HfHvJCwvJq5ChibjjAGe0wc0vw==}
[email protected].8:
resolution: {integrity: sha512-7or7YqR3zXwHhiBGj40l9yODyQY146O+hXKaEAfQYQkcvHtMDdX95K96xr50qL9EjXScyYVJb1NIgVE8F0i5cA==}
engines: {node: '>= 14'}
hasBin: true
@@ -9707,18 +9711,18 @@ snapshots:
tslib: 2.9.1
optional: true
'@eslint-community/[email protected]([email protected]4.0([email protected]))':
'@eslint-community/[email protected]([email protected]5.0([email protected]))':
dependencies:
eslint: 10.14.0([email protected])
eslint: 10.15.0([email protected])
eslint-visitor-keys: 3.4.3
'@eslint-community/[email protected]': {}
'@eslint/[email protected].5([email protected])':
'@eslint/[email protected].6([email protected])':
dependencies:
'@eslint/object-schema': 3.0.5
debug: 4.4.3([email protected])
minimatch: 10.2.6
minimatch: 11.0.5
transitivePeerDependencies:
- supports-color
@@ -9734,9 +9738,9 @@ snapshots:
dependencies:
'@types/json-schema': 7.0.15
'@eslint/[email protected]([email protected]4.0([email protected]))':
'@eslint/[email protected]([email protected]5.0([email protected]))':
optionalDependencies:
eslint: 10.14.0([email protected])
eslint: 10.15.0([email protected])
'@eslint/[email protected]': {}
@@ -9904,7 +9908,7 @@ snapshots:
'@html-eslint/types': 0.68.0
html-standard: 0.0.13
'@html-eslint/[email protected]([email protected]4.0([email protected]))':
'@html-eslint/[email protected]([email protected]5.0([email protected]))':
dependencies:
'@eslint/plugin-kit': 0.4.1
'@html-eslint/core': 0.68.0
@@ -9913,7 +9917,7 @@ snapshots:
'@html-eslint/template-syntax-parser': 0.68.0
'@html-eslint/types': 0.68.0
'@rviscomi/capo.js': 2.2.1
eslint: 10.14.0([email protected])
eslint: 10.15.0([email protected])
html-standard: 0.0.13
'@html-eslint/[email protected]':
@@ -10644,9 +10648,9 @@ snapshots:
dependencies:
parse5: 7.3.0
'@playwright/[email protected].0':
'@playwright/[email protected].1':
dependencies:
playwright: 1.65.0
playwright: 1.65.1
'@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
@@ -11401,15 +11405,15 @@ snapshots:
dependencies:
'@types/node': 24.19.2
'@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]4.0([email protected]))([email protected])([email protected]))([email protected]4.0([email protected]))([email protected])([email protected])':
'@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]5.0([email protected]))([email protected])([email protected]))([email protected]5.0([email protected]))([email protected])([email protected])':
dependencies:
'@eslint-community/regexpp': 4.12.2
'@typescript-eslint/parser': 8.72.2([email protected]4.0([email protected]))([email protected])([email protected])
'@typescript-eslint/parser': 8.72.2([email protected]5.0([email protected]))([email protected])([email protected])
'@typescript-eslint/scope-manager': 8.72.2
'@typescript-eslint/type-utils': 8.72.2([email protected]4.0([email protected]))([email protected])([email protected])
'@typescript-eslint/utils': 8.72.2([email protected]4.0([email protected]))([email protected])([email protected])
'@typescript-eslint/type-utils': 8.72.2([email protected]5.0([email protected]))([email protected])([email protected])
'@typescript-eslint/utils': 8.72.2([email protected]5.0([email protected]))([email protected])([email protected])
'@typescript-eslint/visitor-keys': 8.72.2
eslint: 10.14.0([email protected])
eslint: 10.15.0([email protected])
ignore: 7.0.6
natural-compare: 1.4.0
ts-api-utils: 2.5.0([email protected])
@@ -11417,14 +11421,14 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@typescript-eslint/[email protected]([email protected]4.0([email protected]))([email protected])([email protected])':
'@typescript-eslint/[email protected]([email protected]5.0([email protected]))([email protected])([email protected])':
dependencies:
'@typescript-eslint/scope-manager': 8.72.2
'@typescript-eslint/types': 8.72.2
'@typescript-eslint/typescript-estree': 8.72.2([email protected])([email protected])
'@typescript-eslint/visitor-keys': 8.72.2
debug: 4.4.3([email protected])
eslint: 10.14.0([email protected])
eslint: 10.15.0([email protected])
typescript: 6.0.3
transitivePeerDependencies:
- supports-color
@@ -11447,13 +11451,13 @@ snapshots:
dependencies:
typescript: 6.0.3
'@typescript-eslint/[email protected]([email protected]4.0([email protected]))([email protected])([email protected])':
'@typescript-eslint/[email protected]([email protected]5.0([email protected]))([email protected])([email protected])':
dependencies:
'@typescript-eslint/types': 8.72.2
'@typescript-eslint/typescript-estree': 8.72.2([email protected])([email protected])
'@typescript-eslint/utils': 8.72.2([email protected]4.0([email protected]))([email protected])([email protected])
'@typescript-eslint/utils': 8.72.2([email protected]5.0([email protected]))([email protected])([email protected])
debug: 4.4.3([email protected])
eslint: 10.14.0([email protected])
eslint: 10.15.0([email protected])
ts-api-utils: 2.5.0([email protected])
typescript: 6.0.3
transitivePeerDependencies:
@@ -11476,13 +11480,13 @@ snapshots:
transitivePeerDependencies:
- supports-color
'@typescript-eslint/[email protected]([email protected]4.0([email protected]))([email protected])([email protected])':
'@typescript-eslint/[email protected]([email protected]5.0([email protected]))([email protected])([email protected])':
dependencies:
'@eslint-community/eslint-utils': 4.10.1([email protected]4.0([email protected]))
'@eslint-community/eslint-utils': 4.10.1([email protected]5.0([email protected]))
'@typescript-eslint/scope-manager': 8.72.2
'@typescript-eslint/types': 8.72.2
'@typescript-eslint/typescript-estree': 8.72.2([email protected])([email protected])
eslint: 10.14.0([email protected])
eslint: 10.15.0([email protected])
typescript: 6.0.3
transitivePeerDependencies:
- supports-color
@@ -12333,11 +12337,12 @@ snapshots:
dependencies:
mime-db: 1.54.0
[email protected].1([email protected]):
[email protected].2([email protected]):
dependencies:
bytes: 3.1.2
compressible: 2.0.18
debug: 2.6.9([email protected])
destroy: 1.2.0
negotiator: 0.6.4
on-headers: 1.1.0
safe-buffer: 5.2.1
@@ -12528,6 +12533,8 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
@@ -12793,9 +12800,9 @@ snapshots:
[email protected]: {}
[email protected]([email protected]4.0([email protected])):
[email protected]([email protected]5.0([email protected])):
dependencies:
eslint: 10.14.0([email protected])
eslint: 10.15.0([email protected])
[email protected]([email protected]):
dependencies:
@@ -12819,14 +12826,14 @@ snapshots:
transitivePeerDependencies:
- supports-color
[email protected](@typescript-eslint/[email protected]([email protected]4.0([email protected]))([email protected])([email protected]))([email protected]4.0([email protected]))([email protected]):
[email protected](@typescript-eslint/[email protected]([email protected]5.0([email protected]))([email protected])([email protected]))([email protected]5.0([email protected]))([email protected]):
dependencies:
'@typescript-eslint/types': 8.72.2
cjs-module-lexer: 2.3.0
comment-parser: 1.4.8
debug: 4.4.3([email protected])
es-module-lexer: 3.0.4
eslint: 10.14.0([email protected])
eslint: 10.15.0([email protected])
eslint-import-context: 0.1.9([email protected])
is-glob: 4.0.3
minimatch: 11.0.5
@@ -12834,39 +12841,39 @@ snapshots:
stable-hash-x: 0.2.0
unrs-resolver: 1.12.2
optionalDependencies:
'@typescript-eslint/utils': 8.72.2([email protected]4.0([email protected]))([email protected])([email protected])
'@typescript-eslint/utils': 8.72.2([email protected]5.0([email protected]))([email protected])([email protected])
transitivePeerDependencies:
- supports-color
[email protected]([email protected]4.0([email protected])):
[email protected]([email protected]5.0([email protected])):
dependencies:
'@thepassle/axobject-query': 4.0.0
aria-query: 5.3.2
axe-core: 4.13.0
dom5: 3.0.1
emoji-regex: 10.6.0
eslint: 10.14.0([email protected])
eslint-plugin-lit: 2.3.1([email protected]4.0([email protected]))
eslint: 10.15.0([email protected])
eslint-plugin-lit: 2.3.1([email protected]5.0([email protected]))
eslint-rule-extender: 0.0.1
language-tags: 1.0.9
parse5: 7.3.0
parse5-htmlparser2-tree-adapter: 6.0.1
[email protected]([email protected]4.0([email protected])):
[email protected]([email protected]5.0([email protected])):
dependencies:
eslint: 10.14.0([email protected])
eslint: 10.15.0([email protected])
parse5: 8.1.0
parse5-htmlparser2-tree-adapter: 8.0.1
[email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]4.0([email protected]))([email protected])([email protected]))([email protected]4.0([email protected]))([email protected])([email protected]))([email protected]4.0([email protected])):
[email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]5.0([email protected]))([email protected])([email protected]))([email protected]5.0([email protected]))([email protected])([email protected]))([email protected]5.0([email protected])):
dependencies:
eslint: 10.14.0([email protected])
eslint: 10.15.0([email protected])
optionalDependencies:
'@typescript-eslint/eslint-plugin': 8.72.2(@typescript-eslint/[email protected]([email protected]4.0([email protected]))([email protected])([email protected]))([email protected]4.0([email protected]))([email protected])([email protected])
'@typescript-eslint/eslint-plugin': 8.72.2(@typescript-eslint/[email protected]([email protected]5.0([email protected]))([email protected])([email protected]))([email protected]5.0([email protected]))([email protected])([email protected])
[email protected]([email protected]4.0([email protected])):
[email protected]([email protected]5.0([email protected])):
dependencies:
eslint: 10.14.0([email protected])
eslint: 10.15.0([email protected])
is-valid-element-name: 1.0.0
js-levenshtein-esm: 2.0.0
@@ -12883,11 +12890,11 @@ snapshots:
[email protected]: {}
[email protected]4.0([email protected]):
[email protected]5.0([email protected]):
dependencies:
'@eslint-community/eslint-utils': 4.10.1([email protected]4.0([email protected]))
'@eslint-community/eslint-utils': 4.10.1([email protected]5.0([email protected]))
'@eslint-community/regexpp': 4.12.2
'@eslint/config-array': 0.23.5([email protected])
'@eslint/config-array': 0.23.6([email protected])
'@eslint/config-helpers': 0.7.0
'@eslint/core': 1.2.1
'@eslint/plugin-kit': 0.7.3
@@ -12912,7 +12919,7 @@ snapshots:
imurmurhash: 0.1.4
is-glob: 4.0.3
json-stable-stringify-without-jsonify: 1.0.1
minimatch: 10.2.6
minimatch: 11.0.5
natural-compare: 1.4.0
optionator: 0.9.4
transitivePeerDependencies:
@@ -14695,11 +14702,11 @@ snapshots:
dependencies:
pngjs: 3.4.0
[email protected].0: {}
[email protected].1: {}
[email protected].0:
[email protected].1:
dependencies:
playwright-core: 1.65.0
playwright-core: 1.65.1
[email protected]:
dependencies:
@@ -15086,7 +15093,7 @@ snapshots:
path-to-regexp: 3.3.0
range-parser: 1.2.0
[email protected].7([email protected]):
[email protected].8([email protected]):
dependencies:
'@zeit/schemas': 2.36.0
ajv: 8.18.0
@@ -15094,7 +15101,7 @@ snapshots:
boxen: 7.0.0
chalk: 5.0.1
chalk-template: 0.4.0
compression: 1.8.1([email protected])
compression: 1.8.2([email protected])
is-port-reachable: 4.0.0
serve-handler: 6.1.7
tinyclip: 0.1.15
@@ -15691,13 +15698,13 @@ snapshots:
possible-typed-array-names: 1.1.0
reflect.getprototypeof: 1.0.10
[email protected]([email protected]4.0([email protected]))([email protected])([email protected]):
[email protected]([email protected]5.0([email protected]))([email protected])([email protected]):
dependencies:
'@typescript-eslint/eslint-plugin': 8.72.2(@typescript-eslint/[email protected]([email protected]4.0([email protected]))([email protected])([email protected]))([email protected]4.0([email protected]))([email protected])([email protected])
'@typescript-eslint/parser': 8.72.2([email protected]4.0([email protected]))([email protected])([email protected])
'@typescript-eslint/eslint-plugin': 8.72.2(@typescript-eslint/[email protected]([email protected]5.0([email protected]))([email protected])([email protected]))([email protected]5.0([email protected]))([email protected])([email protected])
'@typescript-eslint/parser': 8.72.2([email protected]5.0([email protected]))([email protected])([email protected])
'@typescript-eslint/typescript-estree': 8.72.2([email protected])([email protected])
'@typescript-eslint/utils': 8.72.2([email protected]4.0([email protected]))([email protected])([email protected])
eslint: 10.14.0([email protected])
'@typescript-eslint/utils': 8.72.2([email protected]5.0([email protected]))([email protected])([email protected])
eslint: 10.15.0([email protected])
typescript: 6.0.3
transitivePeerDependencies:
- supports-color
@@ -0,0 +1,55 @@
interface EntityWithColorTemp {
attributes?: Record<string, unknown>;
}
const finiteRange = (
min: unknown,
max: unknown
): { min: number; max: number } | undefined => {
if (typeof min !== "number" || typeof max !== "number") {
return undefined;
}
if (!Number.isFinite(min) || !Number.isFinite(max) || min > max) {
return undefined;
}
return { min, max };
};
/**
* Kelvin bounds reported by the given entity states.
*
* Several lights use the overlap of their ranges, because one
* `color_temp_kelvin` value is sent to every target. When the ranges do not
* overlap, the result spans the widest range so it still has a valid min and
* max. Entities without a finite range are ignored. Returns undefined when
* nothing reports a range, so the caller keeps the selector min and max.
*/
export const kelvinRangeFromEntityStates = (
states: Readonly<Record<string, EntityWithColorTemp | undefined>> | undefined
): { min: number; max: number } | undefined => {
if (!states) {
return undefined;
}
const ranges: { min: number; max: number }[] = [];
for (const state of Object.values(states)) {
const range = finiteRange(
state?.attributes?.min_color_temp_kelvin,
state?.attributes?.max_color_temp_kelvin
);
if (range) {
ranges.push(range);
}
}
if (!ranges.length) {
return undefined;
}
let min = Math.max(...ranges.map((range) => range.min));
let max = Math.min(...ranges.map((range) => range.max));
if (min > max) {
min = Math.min(...ranges.map((range) => range.min));
max = Math.max(...ranges.map((range) => range.max));
}
return { min, max };
};
+2 -17
View File
@@ -163,21 +163,9 @@ export const findEntities = (
return results;
};
export const excludeEntities = (
entityIds: string[],
excludedEntityIds?: string[]
): string[] => {
if (!excludedEntityIds?.length) {
return entityIds;
}
const excluded = new Set(excludedEntityIds);
return entityIds.filter((entityId) => !excluded.has(entityId));
};
export const findFilteredEntities = (
sources: EntityFilterSources,
filters: EntityFilter[],
excludedEntityIds?: string[]
filters: EntityFilter[]
): string[] => {
const filterFuncs = filters.map((filter) =>
generateEntityFilter(
@@ -189,8 +177,5 @@ export const findFilteredEntities = (
filter
)
);
return excludeEntities(
findEntities(Object.keys(sources.states), filterFuncs),
excludedEntityIds
);
return findEntities(Object.keys(sources.states), filterFuncs);
};
+7 -1
View File
@@ -161,6 +161,9 @@ export const getNumberFormatOptions = (
return undefined;
};
// Intl.NumberFormat throws a RangeError for more fraction digits than this.
const MAX_FRACTION_DIGITS = 100;
/**
* Generates default options for Intl.NumberFormat
* @param num The number to be formatted
@@ -185,7 +188,10 @@ export const getDefaultFormatOptions = (
(options.minimumFractionDigits === undefined &&
options.maximumFractionDigits === undefined)
) {
const digits = num.indexOf(".") > -1 ? num.split(".")[1].length : 0;
const digits = Math.min(
num.indexOf(".") > -1 ? num.split(".")[1].length : 0,
MAX_FRACTION_DIGITS
);
defaultOptions.minimumFractionDigits = digits;
defaultOptions.maximumFractionDigits = digits;
}
+10 -2
View File
@@ -1,2 +1,10 @@
export const capitalizeFirstLetter = (str: string) =>
str.charAt(0).toUpperCase() + str.slice(1);
export const capitalizeFirstLetter = (str: string) => {
// Take the first code point, not code unit, so letters outside the BMP
// (stored as a surrogate pair) are uppercased too.
const first = str.codePointAt(0);
if (first === undefined) {
return str;
}
const firstLetter = String.fromCodePoint(first);
return firstLetter.toUpperCase() + str.slice(firstLetter.length);
};
+20 -4
View File
@@ -1,11 +1,27 @@
// Unanchored regex fragments, shared as the single source of truth for both
// the boolean validators below and the HTML `pattern` attribute (the browser
// anchors a pattern as `^(?:…)$`).
const IPV4 =
"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
const IPV6 =
"(?:([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))";
// Decimal octet 0-255 without leading zeros.
const DEC_OCTET = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])";
const IPV4 = `(?:${DEC_OCTET}\\.){3}${DEC_OCTET}`;
// IPv6 grammar from RFC 3986, section 3.2.2.
const H16 = "[0-9a-fA-F]{1,4}";
const LS32 = `(?:${H16}:${H16}|${IPV4})`;
const IPV6 = `(?:${[
`(?:${H16}:){6}${LS32}`,
`::(?:${H16}:){5}${LS32}`,
`(?:${H16})?::(?:${H16}:){4}${LS32}`,
`(?:(?:${H16}:){0,1}${H16})?::(?:${H16}:){3}${LS32}`,
`(?:(?:${H16}:){0,2}${H16})?::(?:${H16}:){2}${LS32}`,
`(?:(?:${H16}:){0,3}${H16})?::${H16}:${LS32}`,
`(?:(?:${H16}:){0,4}${H16})?::${LS32}`,
`(?:(?:${H16}:){0,5}${H16})?::${H16}`,
`(?:(?:${H16}:){0,6}${H16})?::`,
].join("|")})`;
// CIDR prefix lengths: 0-32 for IPv4, 0-128 for IPv6.
const IPV4_PREFIX = "(?:3[0-2]|[12]?[0-9])";
+2 -2
View File
@@ -1,8 +1,8 @@
// https://gist.github.com/hagemann/382adfc57adbd5af078dc93feef01fe1
export const slugify = (value: string, delimiter = "_") => {
const a =
"àáâäæãåāăąабçćčđďдèéêëēėęěеёэфğǵгḧхîïíīįìıİийкłлḿмñńǹňнôöòóœøōõőоṕпŕřрßśšşșсťțтûüùúūǘůűųувẃẍÿýыžźżз·";
const b = `aaaaaaaaaaabcccdddeeeeeeeeeeefggghhiiiiiiiiijkllmmnnnnnoooooooooopprrrsssssstttuuuuuuuuuuvwxyyyzzzz${delimiter}`;
"àáâäæãåāăąабçćčđďдèéêëēėęěеёэфğǵгḧîïíīįìıİийкłлḿмñńǹňнôöòóœøōõőоṕпŕřрßśšşșсťțтûüùúūǘůűųувẃẍÿýыžźżз·";
const b = `aaaaaaaaaaabcccdddeeeeeeeeeeefggghiiiiiiiiijkllmmnnnnnoooooooooopprrrsssssstttuuuuuuuuuuvwxyyyzzzz${delimiter}`;
const p = new RegExp(a.split("").join("|"), "g");
const complex_cyrillic = {
ж: "zh",
+5 -1
View File
@@ -82,7 +82,11 @@ export function decodeQueryParams(
for (const key of config.date ?? []) {
const value = getSearchParam(searchParams, key);
if (value) {
params[key] = new Date(value);
const date = new Date(value);
// Leave out dates that can't be parsed, like a missing value.
if (!Number.isNaN(date.getTime())) {
params[key] = date;
}
}
}
for (const { key, trueValue } of config.boolean ?? []) {
+1
View File
@@ -37,6 +37,7 @@ export const debounce = <T extends any[]>(
debouncedFunc.cancel = () => {
clearTimeout(timeout);
timeout = undefined;
trailingArgs = undefined;
};
+8 -5
View File
@@ -2,14 +2,17 @@ export const groupBy = <T>(
list: T[],
keySelector: (item: T) => string
): Record<string, T[]> => {
const result = {};
// Group in a Map so keys like `constructor` or `__proto__` don't collide
// with Object.prototype.
const groups = new Map<string, T[]>();
for (const item of list) {
const key = keySelector(item);
if (key in result) {
result[key].push(item);
const group = groups.get(key);
if (group) {
group.push(item);
} else {
result[key] = [item];
groups.set(key, [item]);
}
}
return result;
return Object.fromEntries(groups);
};
+2 -1
View File
@@ -11,7 +11,8 @@
* parseAnimationDuration("invalid") // Returns 0
*/
export const parseAnimationDuration = (duration: string): number => {
const trimmed = duration.trim();
// CSS units are case-insensitive, e.g. "3S" is the same as "3s".
const trimmed = duration.trim().toLowerCase();
let value: number;
let multiplier: number;
+195 -4
View File
@@ -7,7 +7,10 @@ import {
mdiRestart,
} from "@mdi/js";
import { differenceInMinutes } from "date-fns";
import type { DataZoomComponentOption } from "echarts/components";
import type {
DataZoomComponentOption,
MarkAreaComponentOption,
} from "echarts/components";
import type { EChartsType } from "echarts/core";
import type {
ECElementEvent,
@@ -90,14 +93,29 @@ export const DEFAULT_CHART_WIDTH = 500;
// is short enough for a whole screenful; on a desktop that would cover the page.
const VISIBILITY_ROOT_MARGIN_NARROW = "100%";
const VISIBILITY_ROOT_MARGIN = "300px";
const CLICK_DRAG_TOLERANCE = 4;
// The selection is shown by the mask, not by the brush
const BRUSH_STYLE = {
color: "rgba(0, 0, 0, 0)",
borderColor: "rgba(0, 0, 0, 0)",
};
export type ZoomSliderMode = "auto" | "always" | "never";
export type ChartSelectMode = "none" | "point" | "range";
const DEFERRED_PROPS = [
"options",
"data",
"_hiddenDatasets",
"_isZoomed",
"highlight",
] as const;
const MASK_OPACITY = 0.7;
export interface ChartTimeRange {
start: number;
end: number;
}
type RawSeriesOption = Exclude<
NonNullable<ECOption["series"]>,
@@ -176,6 +194,18 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
@property({ attribute: "grow-for-zoom-slider", type: Boolean })
public growForZoomSlider = false;
// "point" selects on click, "range" also selects on drag instead of zooming
@property({ attribute: "select-mode" })
public selectMode: ChartSelectMode = "none";
// Everything outside this time range fades
@property({ attribute: false }) public highlight?: ChartTimeRange;
// Rounds a selection to the periods of the data, or drops it
@property({ attribute: false }) public snapSelection?: (
range: ChartTimeRange
) => ChartTimeRange | undefined;
// extraComponents is not reactive and should not trigger updates
public extraComponents?: any[];
@@ -201,6 +231,14 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
@state() private _isZoomed = false;
private _pointerDownX?: number;
private _selectingRange?: ChartTimeRange;
private _maskColor = "";
private _maskShown = false;
// Separate from _isZoomed, whose touch handling reruns graph layouts
@state() private _isGraphRoamed = false;
@@ -454,6 +492,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
if (!this.chart) {
return;
}
if (changedProps.has("selectMode")) {
this._updateSelectMode();
}
const themeChanged = changedProps.has("_themes") && this.hasUpdated;
if (!themeChanged && !DEFERRED_PROPS.some((p) => changedProps.has(p))) {
return;
@@ -499,6 +540,8 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
) {
this._disposeSonification();
}
} else if (changedProps.has("highlight")) {
this._updateMask();
}
if (changedProps.has("options")) {
chartOptions = { ...chartOptions, ...this._createOptions() };
@@ -888,6 +931,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
const style = getComputedStyle(this);
echarts.registerTheme("custom", this._createTheme(style));
this._maskColor =
style.getPropertyValue("--card-background-color").trim() ||
style.getPropertyValue("--primary-background-color").trim();
this.chart = echarts.init(this._chartContainer!, "custom");
this._dragToZoom = false;
@@ -970,6 +1016,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
this._legendItemCount = this._getLegendItems()?.length;
this._updateSankeyRoam();
this._updateDragToZoom();
if (this.selectMode !== "none") {
this._updateSelectMode();
}
if (zoomStart !== 0 || zoomEnd !== 100) {
this.zoom(zoomStart, zoomEnd, true);
}
@@ -1021,7 +1070,10 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
// A chart can switch type (e.g. pie and bar) without being rebuilt
private _updateDragToZoom() {
const active = !this._touchInput && this._hasZoomableXAxis();
const active =
!this._touchInput &&
this._hasZoomableXAxis() &&
this.selectMode !== "range";
if (!this.chart || active === this._dragToZoom) {
return;
}
@@ -1033,6 +1085,130 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
});
}
private _snapRange(range: ChartTimeRange) {
return this.snapSelection ? this.snapSelection(range) : range;
}
private _getMaskArea(): MarkAreaComponentOption | undefined {
const range = this._selectingRange ?? this.highlight;
if (!range) {
return undefined;
}
return {
silent: true,
z: 10,
itemStyle: {
color: this._maskColor,
opacity: MASK_OPACITY,
},
data: [
[{ xAxis: -Infinity }, { xAxis: range.start }],
[{ xAxis: range.end }, { xAxis: Infinity }],
],
};
}
// Only the first series carries the mask, merged in without resending data
private _updateMask() {
const maskArea = this._getMaskArea();
if (maskArea) {
this._maskShown = true;
}
this.chart?.setOption({
series: [{ markArea: maskArea ?? { data: [] } }],
});
}
private _handleSelectPointerDown = (e: ECElementEvent) => {
this._pointerDownX = e.offsetX;
};
private _handleSelectClick = (e: ECElementEvent) => {
const point = [e.offsetX, e.offsetY];
// A drag that ends on the plot is not a click
const dragged =
this._pointerDownX !== undefined &&
Math.abs(e.offsetX - this._pointerDownX) > CLICK_DRAG_TOLERANCE;
if (dragged || !this.chart?.containPixel("grid", point)) {
return;
}
const [x] = this.chart.convertFromPixel("grid", point) as number[];
const selection = this._snapRange({ start: x, end: x });
if (selection) {
fireEvent(this, "chart-select", selection);
}
};
private _handleBrush = (e: any) => {
const range = e.areas?.[0]?.coordRange as number[] | undefined;
if (range) {
this._selectingRange = this._snapRange({
start: range[0],
end: range[1],
});
this._updateMask();
}
};
private _handleBrushEnd = (e: any) => {
const range = e.areas?.[0]?.coordRange as number[] | undefined;
this.chart?.dispatchAction({ type: "brush", areas: [] });
this._selectingRange = undefined;
this._updateMask();
const selection =
range && this._snapRange({ start: range[0], end: range[1] });
if (selection) {
fireEvent(this, "chart-select", selection);
}
};
private _updateSelectMode() {
if (!this.chart) {
return;
}
const zr = this.chart.getZr();
zr.off("mousedown", this._handleSelectPointerDown);
zr.off("click", this._handleSelectClick);
this.chart.off("brush", this._handleBrush);
this.chart.off("brushEnd", this._handleBrushEnd);
if (this.selectMode !== "none") {
zr.on("mousedown", this._handleSelectPointerDown);
zr.on("click", this._handleSelectClick);
}
const selectRange = this.selectMode === "range";
if (selectRange) {
this.chart.on("brush", this._handleBrush);
this.chart.on("brushEnd", this._handleBrushEnd);
this.chart.setOption({
brush: {
xAxisIndex: 0,
// Only measures the range, the mask fades what is outside
seriesIndex: [],
transformable: false,
brushStyle: BRUSH_STYLE,
},
});
}
const brushCursor = {
type: "takeGlobalCursor",
key: "brush",
brushOption: {
brushType: selectRange ? "lineX" : false,
brushMode: "single",
brushStyle: BRUSH_STYLE,
},
};
// Brush and drag to zoom share the global cursor, the last one taken wins
if (selectRange) {
this._updateDragToZoom();
this.chart.dispatchAction(brushCursor);
} else {
this.chart.dispatchAction(brushCursor);
this._dragToZoom = false;
this._updateDragToZoom();
}
}
private _hasZoomableXAxis() {
const xAxis = ensureArray(this.options?.xAxis)?.[0] as
XAXisOption | undefined;
@@ -1475,7 +1651,11 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
private _getSeries() {
const xAxis = (this.options?.xAxis?.[0] ?? this.options?.xAxis) as
XAXisOption | undefined;
const series = ensureArray(this.data).map((s) => {
const maskArea = this._getMaskArea();
if (maskArea) {
this._maskShown = true;
}
const series = ensureArray(this.data).map((s, index) => {
const data = this._hiddenDatasets.has(String(s.id ?? s.name))
? undefined
: s.data;
@@ -1513,6 +1693,16 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
} as HaECSeriesItem;
}
}
// ECharts merges series by id and would keep a mask left out here
if (this._maskShown && (s.type === "line" || s.type === "bar")) {
result = {
...result,
markArea:
index === 0 && maskArea
? maskArea
: ((s as LineSeriesOption).markArea ?? { data: [] }),
} as HaECSeriesItem;
}
return processSeriesTooltipFormatter(result);
});
return series as ECOption["series"];
@@ -1762,7 +1952,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
// it, so a quick drag out would lose the release and its selection
if (
ev.type === "pointerdown" &&
this._dragToZoom &&
(this._dragToZoom || this.selectMode === "range") &&
this._isZoomPress(ev)
) {
this.chart
@@ -2337,6 +2527,7 @@ declare global {
"dataset-hidden": { id: string };
"dataset-unhidden": { id: string };
"chart-click": ECElementEvent;
"chart-select": ChartTimeRange;
"legend-label-click": { id: string };
"chart-zoom": {
start: number;
+55 -2
View File
@@ -5,7 +5,7 @@ import type {
import type { HassConfig, HassEntities } from "home-assistant-js-websocket";
import type { PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, property, query, state } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { isComponentLoaded } from "../../common/config/is_component_loaded";
@@ -49,7 +49,13 @@ import type {
HomeAssistantUI,
} from "../../types";
import { getPeriodicAxisLabelConfig } from "./axis-label";
import type { CustomLegendOption } from "./ha-chart-base";
import type {
ChartSelectMode,
ChartTimeRange,
CustomLegendOption,
HaChartBase,
ZoomSliderMode,
} from "./ha-chart-base";
import "./ha-chart-base";
import { sideTooltipPosition } from "./chart-tooltip-position";
import "./ha-chart-tooltip-marker";
@@ -128,6 +134,16 @@ export class StatisticsChart extends LitElement {
@property({ attribute: "expand-legend", type: Boolean })
public expandLegend?: boolean;
@property({ attribute: "select-mode" })
public selectMode: ChartSelectMode = "none";
@property({ attribute: "zoom-slider" })
public zoomSlider: ZoomSliderMode = "auto";
@property({ attribute: false }) public highlight?: ChartTimeRange;
@query("ha-chart-base") private _chartBase?: HaChartBase;
@state() private _chartData: (LineSeriesOption | BarSeriesOption)[] = [];
@state() private _legendData: CustomLegendOption["data"];
@@ -244,8 +260,12 @@ export class StatisticsChart extends LitElement {
return html`
<ha-chart-base
.data=${this._chartData}
.highlight=${this.highlight}
.snapSelection=${this._snapSelection}
.options=${this._chartOptions}
.height=${this.height}
.selectMode=${this.selectMode}
.zoomSlider=${this.zoomSlider}
style=${styleMap({ height: this.height })}
@dataset-hidden=${this._datasetHidden}
@dataset-unhidden=${this._datasetUnhidden}
@@ -259,6 +279,39 @@ export class StatisticsChart extends LitElement {
`;
}
public resetZoom() {
this._chartBase?.zoom(0, 100);
}
// A click selects the period that contains it, a drag every period it
// touches
private _snapSelection = (
range: ChartTimeRange
): ChartTimeRange | undefined => {
let start: number | undefined;
let end: number | undefined;
Object.entries(this.statisticsData ?? {}).forEach(
([statisticId, values]) => {
if (this._hiddenStats.has(statisticId)) {
return;
}
values.forEach((value) => {
const touched =
range.start === range.end
? value.start <= range.start && range.start < value.end
: value.start < range.end && value.end > range.start;
if (touched) {
start = Math.min(start ?? value.start, value.start);
end = Math.max(end ?? value.end, value.end);
}
});
}
);
return start === undefined || end === undefined
? undefined
: { start, end };
};
private _datasetHidden(ev: HASSDomEvent<HASSDomEvents["dataset-hidden"]>) {
this._hiddenStats.add(ev.detail.id);
this.requestUpdate("_hiddenStats");
+2 -1
View File
@@ -1663,7 +1663,8 @@ export class HaDataTable extends LitElement {
}
.mdc-data-table__row ~ .mdc-data-table__row {
border-top: 1px solid var(--divider-color);
border-top: var(--data-table-row-border-width, 1px) solid
var(--divider-color);
}
.mdc-data-table__row.clickable:not(
@@ -1,22 +1,25 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { html, LitElement } 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 { fireEvent, type HASSDomEvent } from "../../common/dom/fire_event";
import type { ColorTempSelector } from "../../data/selector";
import "../ha-labeled-slider";
import { generateColorTemperatureGradient } from "../../dialogs/more-info/components/lights/light-color-temp-picker";
import { kelvinRangeFromEntityStates } from "../../common/color/color-temp-selector-range";
import {
DEFAULT_MAX_KELVIN,
DEFAULT_MIN_KELVIN,
mired2kelvin,
} from "../../common/color/convert-light-color";
import { consumeEntityStates } from "../../common/decorators/consume-context-entry";
import { fireEvent, type HASSDomEvent } from "../../common/dom/fire_event";
import type { ColorTempSelector } from "../../data/selector";
import { generateColorTemperatureGradient } from "../../dialogs/more-info/components/lights/light-color-temp-picker";
import "../ha-labeled-slider";
@customElement("ha-selector-color_temp")
export class HaColorTempSelector extends LitElement {
@property({ attribute: false }) public selector!: ColorTempSelector;
@property() public value?: string;
@property() public value?: string | number;
@property() public label?: string;
@@ -26,27 +29,16 @@ export class HaColorTempSelector extends LitElement {
@property({ type: Boolean }) public required = true;
protected render() {
let min: number;
let max: number;
@property({ attribute: false }) public context?: {
filter_entity?: string | string[];
};
switch (this.selector.color_temp?.unit) {
case "kelvin":
min = this.selector.color_temp?.min ?? DEFAULT_MIN_KELVIN;
max = this.selector.color_temp?.max ?? DEFAULT_MAX_KELVIN;
break;
case "mired":
default:
min =
this.selector.color_temp?.min ??
this.selector.color_temp?.min_mireds ??
153;
max =
this.selector.color_temp?.max ??
this.selector.color_temp?.max_mireds ??
500;
break;
}
@state()
@consumeEntityStates({ entityIdPath: ["context", "filter_entity"] })
private _filterEntityStates?: Record<string, HassEntity>;
protected render() {
const { min, max } = this._bounds();
const gradient = this._generateTemperatureGradient(
this.selector.color_temp?.unit ?? "mired",
min,
@@ -72,6 +64,30 @@ export class HaColorTempSelector extends LitElement {
`;
}
private _bounds(): { min: number; max: number } {
switch (this.selector.color_temp?.unit) {
case "kelvin":
return (
kelvinRangeFromEntityStates(this._filterEntityStates) ?? {
min: this.selector.color_temp?.min ?? DEFAULT_MIN_KELVIN,
max: this.selector.color_temp?.max ?? DEFAULT_MAX_KELVIN,
}
);
case "mired":
default:
return {
min:
this.selector.color_temp?.min ??
this.selector.color_temp?.min_mireds ??
153,
max:
this.selector.color_temp?.max ??
this.selector.color_temp?.max_mireds ??
500,
};
}
}
private _generateTemperatureGradient = memoizeOne(
(unit: "kelvin" | "mired", min: number, max: number) => {
let gradient;
+117
View File
@@ -0,0 +1,117 @@
import { mdiClose, mdiInformationOutline } from "@mdi/js";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { fireEvent } from "../common/dom/fire_event";
import type { LocalizeFunc } from "../common/translations/localize";
import { showStartupProgressDialog } from "../dialogs/startup-progress/show-dialog-startup-progress";
import "./ha-icon-button";
@customElement("ha-startup-progress")
export class HaStartupProgress extends LitElement {
// The launch screen render swap would remove a dialog opened before it.
@property({ attribute: false }) public detailsAvailable = false;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
// Fallbacks cover the first render, before the core translations have loaded.
protected render() {
const localize = this._localize;
return html`
<div class="card">
<div class="text" role="status">
<span class="title">
${
localize("ui.startup_progress.starting") ||
"Home Assistant is starting"
}
</span>
<span class="secondary">
${
localize("ui.startup_progress.starting_secondary") ||
"Some features may not be available yet"
}
</span>
</div>
${
this.detailsAvailable
? html`<ha-icon-button
.label=${
localize("ui.startup_progress.details") || "Startup details"
}
.path=${mdiInformationOutline}
@click=${this._showDetails}
></ha-icon-button>`
: nothing
}
<ha-icon-button
.label=${localize("ui.notification_toast.dismiss") || "Dismiss"}
.path=${mdiClose}
@click=${this._dismiss}
></ha-icon-button>
</div>
`;
}
private _showDetails() {
showStartupProgressDialog(this);
}
private _dismiss() {
fireEvent(this, "startup-progress-dismissed");
}
static styles = css`
:host {
position: fixed;
inset-inline-start: 50%;
inset-block-end: calc(
var(--safe-area-inset-bottom, 0px) + var(--ha-space-4)
);
transform: translateX(calc(-50% * var(--scale-direction, 1)));
/* Above the launch screen, which can still be fading out. */
z-index: 101;
width: min(420px, calc(100vw - var(--ha-space-8)));
}
.card {
display: flex;
align-items: center;
gap: var(--ha-space-2);
padding: var(--ha-space-3) var(--ha-space-2) var(--ha-space-3)
var(--ha-space-4);
color: var(--ha-color-on-neutral-loud);
background-color: var(--ha-color-neutral-10);
border-radius: var(--ha-border-radius-sm);
box-shadow: var(--wa-shadow-l);
}
.text {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
}
.title {
font-weight: var(--ha-font-weight-medium);
}
.secondary {
/* The card is dark in both themes, so the themed quiet color lacks contrast. */
color: var(--ha-color-neutral-70);
font-size: var(--ha-font-size-s);
}
ha-icon-button {
--mdc-icon-button-size: 36px;
color: var(--ha-color-on-neutral-loud);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-startup-progress": HaStartupProgress;
}
interface HASSDomEvents {
"startup-progress-dismissed": undefined;
}
}
+107 -14
View File
@@ -1,18 +1,111 @@
import type { HomeAssistant } from "../types";
import type { Connection, UnsubscribeFunc } from "home-assistant-js-websocket";
import {
STATE_NOT_RUNNING,
STATE_RUNNING,
STATE_STARTING,
} from "home-assistant-js-websocket";
export type BootstrapIntegrationsTimings = Record<string, number>;
export type BootstrapPhase =
"preparing" | "setup" | "wrap_up" | "starting" | "running";
export const subscribeBootstrapIntegrations = (
hass: HomeAssistant,
callback: (message: BootstrapIntegrationsTimings) => void
) => {
const unsubProm =
hass.connection.subscribeMessage<BootstrapIntegrationsTimings>(
(message) => callback(message),
{
type: "subscribe_bootstrap_integrations",
}
);
export interface BootstrapProgress {
phase: BootstrapPhase;
// Seconds since integration setup started.
elapsed: number;
integrations: {
// Integrations scheduled by bootstrap, including dependencies. Null while resolving.
total: number | null;
// Integrations whose setup attempt finished, successful or not.
done: number;
failed: string[];
};
// Domain to seconds since its oldest pending setup started.
active: Record<string, number>;
}
return unsubProm;
export interface StartupProgressView {
phase: BootstrapPhase;
// Share of scheduled integrations that finished setup, not of startup time.
// Undefined when the indicator must be indeterminate.
percent?: number;
done: number;
total: number | null;
elapsed?: number;
active: [domain: string, seconds: number][];
failed: string[];
finished: boolean;
}
export type StartupTransition = "show" | "finish" | "none";
export const subscribeBootstrapProgress = (
connection: Connection,
callback: (message: BootstrapProgress) => void
): Promise<UnsubscribeFunc> =>
connection.subscribeMessage<BootstrapProgress>(callback, {
type: "subscribe_bootstrap_progress",
});
const PHASE_ORDER: BootstrapPhase[] = [
"preparing",
"setup",
"wrap_up",
"starting",
"running",
];
export const computeStartupProgress = (
progress: BootstrapProgress | undefined,
coreState: string
): StartupProgressView => {
// The core state is authoritative; progress messages can lag behind it.
const statePhase: BootstrapPhase | undefined =
coreState === STATE_RUNNING
? "running"
: coreState === STATE_STARTING
? "starting"
: undefined;
const messagePhase = progress?.phase ?? "preparing";
const phase =
statePhase &&
PHASE_ORDER.indexOf(statePhase) > PHASE_ORDER.indexOf(messagePhase)
? statePhase
: messagePhase;
const total = progress?.integrations.total ?? null;
const done = progress?.integrations.done ?? 0;
return {
phase,
percent:
phase === "setup" && total
? Math.min(100, Math.round((done / total) * 100))
: undefined,
done,
total,
elapsed: progress?.elapsed,
active: Object.entries(progress?.active ?? {}).sort(
([, a], [, b]) => b - a
),
failed: progress?.integrations.failed ?? [],
finished: coreState === STATE_RUNNING,
};
};
export const startupTransition = (
oldState: string | undefined,
newState: string
): StartupTransition => {
if (oldState === newState) {
return "none";
}
if (newState === STATE_NOT_RUNNING || newState === STATE_STARTING) {
// Startup is not finished in STARTING, so keep the indicator from NOT_RUNNING.
return oldState === STATE_NOT_RUNNING ? "none" : "show";
}
if (
newState === STATE_RUNNING &&
(oldState === STATE_NOT_RUNNING || oldState === STATE_STARTING)
) {
return "finish";
}
return "none";
};
+29
View File
@@ -0,0 +1,29 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { BatterySourceTypeEnergyPreference } from "./energy";
const capacityUnitFactors: Record<string, number> = {
Wh: 0.001,
kWh: 1,
MWh: 1000,
};
export const batteryCapacityUnits = Object.keys(capacityUnitFactors);
export const getBatteryCapacity = (
source: BatterySourceTypeEnergyPreference,
states: Record<string, HassEntity | undefined> | undefined
): number | undefined => {
let capacity = source.capacity;
if (source.entity_capacity) {
const entity = states?.[source.entity_capacity];
const unit = entity?.attributes.unit_of_measurement;
const factor =
unit && Object.prototype.hasOwnProperty.call(capacityUnitFactors, unit)
? capacityUnitFactors[unit]
: undefined;
capacity = entity && factor ? Number(entity.state) * factor : undefined;
}
return capacity != null && Number.isFinite(capacity) && capacity > 0
? capacity
: undefined;
};
+2
View File
@@ -189,6 +189,7 @@ export interface BatteryTotalsSourceTypeEnergyPreference {
power_config?: PowerConfig;
stat_soc?: string;
capacity?: number; // usable capacity in kWh, used to weight the combined SOC
entity_capacity?: string; // sensor reporting usable capacity in an energy unit
name?: string;
}
@@ -215,6 +216,7 @@ export interface BatteryDirectionsSourceTypeEnergyPreference {
power_config?: BatteryDirectionsPowerConfig;
stat_soc?: string;
capacity?: number;
entity_capacity?: string;
name?: string;
}
-31
View File
@@ -51,10 +51,6 @@ export interface SecurityFrontendSystemData {
favorite_entities?: string[];
}
export interface MaintenanceFrontendSystemData {
hidden_entities?: string[];
}
export interface EnergyFrontendSystemData {
// Stable "<view>.<card-type>" keys of energy dashboard cards the user has
// hidden. An absent key or array means nothing is hidden (all cards visible),
@@ -73,7 +69,6 @@ declare global {
home: HomeFrontendSystemData;
energy: EnergyFrontendSystemData;
security: SecurityFrontendSystemData;
maintenance: MaintenanceFrontendSystemData;
}
}
@@ -150,32 +145,6 @@ export const saveFrontendSystemData = async <
value,
});
const pendingSystemDataSaves = new Map<ValidSystemDataKey, Promise<void>>();
export const queueFrontendSystemDataSave = <
SystemDataKey extends ValidSystemDataKey,
>(
conn: Connection,
key: SystemDataKey,
value: FrontendSystemData[SystemDataKey]
): Promise<void> => {
const save = (pendingSystemDataSaves.get(key) ?? Promise.resolve())
.catch(() => undefined)
.then(() => saveFrontendSystemData(conn, key, value));
pendingSystemDataSaves.set(key, save);
return save;
};
export const fetchFrontendSystemDataAfterSaves = async <
SystemDataKey extends ValidSystemDataKey,
>(
conn: Connection,
key: SystemDataKey
): Promise<FrontendSystemData[SystemDataKey] | null> => {
await pendingSystemDataSaves.get(key)?.catch(() => undefined);
return fetchFrontendSystemData(conn, key);
};
export const subscribeFrontendSystemData = <
SystemDataKey extends ValidSystemDataKey,
>(
+47 -1
View File
@@ -1,7 +1,7 @@
import type { Connection } from "home-assistant-js-websocket";
import { DEFAULT_ENTITY_NAME } from "../common/entity/entity_name_config";
import type { HaDurationData } from "../components/ha-duration-input";
import type { HomeAssistant } from "../types";
import type { HomeAssistant, HomeAssistantApi } from "../types";
import { firstWeekday } from "../common/datetime/first_weekday";
export interface RecorderInfo {
@@ -163,6 +163,52 @@ export const getRecorderInfo = (conn: Connection) =>
type: "recorder/info",
});
export interface RecorderTableUsage {
table: string;
bytes: number;
}
// Byte figures are null when the database cannot report table sizes.
export interface RecorderEntityUsage {
// null collects rows without a known entity
entity_id: string | null;
states: number;
states_bytes: number | null;
attributes_bytes: number | null;
}
export interface RecorderStatisticUsage {
// null collects rows without a known statistic
statistic_id: string | null;
source: string | null;
statistics: number;
statistics_short_term: number;
statistics_bytes: number | null;
statistics_short_term_bytes: number | null;
}
export interface RecorderDatabaseUsage {
generated_at: string;
duration: number;
total_bytes: number;
free_bytes: number | null;
// SQLite write-ahead log, not part of total_bytes
wal_bytes: number | null;
tables: RecorderTableUsage[] | null;
entities: RecorderEntityUsage[];
statistics: RecorderStatisticUsage[];
}
// Without refresh this returns the last report of the past hour, or null.
export const fetchRecorderDatabaseUsage = (
api: Pick<HomeAssistantApi, "callWS">,
refresh = false
) =>
api.callWS<RecorderDatabaseUsage | null>({
type: "recorder/database_usage",
refresh,
});
export type EntityRecordingDisabler = "user";
export interface RecorderEntityOptions {
+5
View File
@@ -185,6 +185,11 @@ export interface ColorRGBSelector {
export interface ColorTempSelector {
color_temp: {
unit?: "kelvin" | "mired";
/**
* Slider bounds. For `unit: "kelvin"` these apply only when no entity in
* the selector context `filter_entity` reports `min_color_temp_kelvin`
* and `max_color_temp_kelvin`.
*/
min?: number;
max?: number;
min_mireds?: number;
+14 -2
View File
@@ -79,13 +79,25 @@ export const updateButtonIsDisabled = (entity: UpdateEntity): boolean =>
export const updateIsInstalling = (entity: UpdateEntity): boolean =>
!!entity.attributes.in_progress;
export interface UpdateReleaseNotesMessage {
severity: "info" | "warning" | "error";
message: string;
}
export interface UpdateReleaseNotes {
release_notes: string | null;
messages: UpdateReleaseNotesMessage[];
}
export const updateReleaseNotes = (
hass: Pick<HomeAssistant, "callWS">,
entityId: string
entityId: string,
language: string
) =>
hass.callWS<string | null>({
hass.callWS<UpdateReleaseNotes>({
type: "update/release_notes",
entity_id: entityId,
language,
});
const HOME_ASSISTANT_CORE_TITLE = "Home Assistant Core";
@@ -2,6 +2,7 @@ import type { ContextType } from "@lit/context";
import type { HassConfig, UnsubscribeFunc } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import { consume } from "../../../common/decorators/consume";
import { BINARY_STATE_OFF } from "../../../common/const";
@@ -13,6 +14,7 @@ import { transform } from "../../../common/decorators/transform";
import { supportsFeature } from "../../../common/entity/supports-feature";
import type { LocalizeFunc } from "../../../common/translations/localize";
import { sanitizeHttpUrl } from "../../../common/url/sanitize-http-url";
import { estimateDirection } from "../../../common/util/estimate-direction";
import { closestWithProperty } from "../../../common/dom/ancestors-with-property";
import "../../../components/ha-alert";
import "../../../components/ha-button";
@@ -31,7 +33,7 @@ import {
} from "../../../data/context";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import type { EntityRegistryDisplayEntry } from "../../../data/entity/entity_registry";
import type { UpdateEntity } from "../../../data/update";
import type { UpdateEntity, UpdateReleaseNotes } from "../../../data/update";
import {
latestVersionIsSkipped,
updateButtonIsDisabled,
@@ -97,7 +99,7 @@ class MoreInfoUpdate extends LitElement {
})
private _user?: CurrentUser;
@state() private _releaseNotes?: string | null;
@state() private _releaseNotes?: UpdateReleaseNotes;
@state() private _error?: string;
@@ -261,15 +263,41 @@ class MoreInfoUpdate extends LitElement {
<hr />
${this._markdownLoading ? this._renderLoader() : nothing}
`
: this._releaseNotes
: this._releaseNotes.messages.length ||
this._releaseNotes.release_notes
? html`
<hr />
<ha-markdown
@content-resize=${this._markdownLoaded}
.content=${this._releaseNotes}
class=${this._markdownLoading ? "hidden" : ""}
></ha-markdown>
${this._markdownLoading ? this._renderLoader() : nothing}
${this._releaseNotes.messages.map(
(message) => html`
<ha-alert
class="release-notes-message"
alert-type=${message.severity}
>
<ha-markdown
class=${classMap({
rtl: estimateDirection(message.message) === "rtl",
})}
.content=${message.message}
></ha-markdown>
</ha-alert>
`
)}
${
this._releaseNotes.release_notes
? html`
<ha-markdown
@content-resize=${this._markdownLoaded}
.content=${this._releaseNotes.release_notes}
class=${this._markdownLoading ? "hidden" : ""}
></ha-markdown>
${
this._markdownLoading
? this._renderLoader()
: nothing
}
`
: nothing
}
`
: nothing
: this.stateObj.attributes.release_summary
@@ -393,7 +421,8 @@ class MoreInfoUpdate extends LitElement {
try {
this._releaseNotes = await updateReleaseNotes(
this._api,
this.stateObj!.entity_id
this.stateObj!.entity_id,
this._i18n.language
);
} catch (err: any) {
this._error = err.message;
@@ -583,6 +612,11 @@ class MoreInfoUpdate extends LitElement {
margin-bottom: var(--ha-space-4);
}
.release-notes-message {
display: block;
margin-bottom: var(--ha-space-4);
}
.row {
margin: 0;
display: flex;
@@ -642,6 +676,12 @@ class MoreInfoUpdate extends LitElement {
padding-bottom: var(--ha-space-4);
box-sizing: border-box;
}
.release-notes-message ha-markdown {
padding-bottom: 0;
}
ha-markdown.rtl {
direction: rtl;
}
ha-markdown.hidden {
display: none;
}
@@ -0,0 +1,303 @@
import { mdiAlertCircle } from "@mdi/js";
import type { ContextType } from "@lit/context";
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import { STATE_RUNNING } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consume } from "../../common/decorators/consume";
import { navigate } from "../../common/navigate";
import "../../components/ha-alert";
import "../../components/ha-button";
import "../../components/ha-dialog";
import "../../components/ha-dialog-footer";
import "../../components/ha-domain-icon";
import "../../components/ha-spinner";
import "../../components/ha-svg-icon";
import "../../components/item/ha-list-item-base";
import "../../components/list/ha-list-base";
import "../../components/progress/ha-progress-bar";
import type {
BootstrapProgress,
StartupProgressView,
} from "../../data/bootstrap_integrations";
import {
computeStartupProgress,
subscribeBootstrapProgress,
} from "../../data/bootstrap_integrations";
import {
apiContext,
configContext,
connectionContext,
internationalizationContext,
} from "../../data/context";
import type { IntegrationSetup } from "../../data/integration";
import { domainToName, fetchIntegrationSetups } from "../../data/integration";
import { haStyleDialog } from "../../resources/styles";
import { DialogMixin } from "../dialog-mixin";
const MAX_SLOWEST = 10;
@customElement("dialog-startup-progress")
class DialogStartupProgress extends DialogMixin(LitElement) {
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@consume({ context: connectionContext, subscribe: true })
private _connection!: ContextType<typeof connectionContext>;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@state()
@consume({ context: configContext, subscribe: true })
private _config!: ContextType<typeof configContext>;
@state() private _progress?: BootstrapProgress;
@state() private _setups?: IntegrationSetup[];
private _unsubProgress?: Promise<UnsubscribeFunc>;
private _computeProgress = memoizeOne(computeStartupProgress);
connectedCallback() {
super.connectedCallback();
// Core sends the current progress on subscribe.
this._unsubProgress = subscribeBootstrapProgress(
this._connection.connection,
(progress) => {
this._progress = progress;
}
);
}
disconnectedCallback() {
super.disconnectedCallback();
this._unsubProgress?.then((unsub) => unsub());
this._unsubProgress = undefined;
}
protected willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
if (
!this._setups &&
changedProps.has("_config") &&
this._config.config.state === STATE_RUNNING
) {
this._setups = [];
fetchIntegrationSetups(this._api.callWS).then((setups) => {
this._setups = setups
.filter((setup) => setup.seconds !== undefined)
.sort((a, b) => b.seconds! - a.seconds!)
.slice(0, MAX_SLOWEST);
});
}
}
protected render() {
const localize = this._i18n.localize;
const progress = this._progress
? this._computeProgress(this._progress, this._config.config.state)
: undefined;
const issues = progress?.failed.length ?? 0;
return html`
<ha-dialog open header-title=${localize("ui.startup_progress.details")}>
${
!progress
? html`<ha-spinner></ha-spinner>`
: progress.finished
? this._renderSummary(progress.elapsed, issues)
: this._renderLive(progress)
}
${progress ? this._renderFailed(progress.failed) : nothing}
${progress?.finished ? this._renderSlowest() : nothing}
<ha-dialog-footer slot="footer">
${
issues && this._config.user?.is_admin
? html`<ha-button
slot="secondaryAction"
appearance="plain"
@click=${this._openIntegrations}
>
${localize("ui.startup_progress.open_integrations")}
</ha-button>`
: nothing
}
<ha-button slot="primaryAction" @click=${this.closeDialog}>
${localize("ui.common.close")}
</ha-button>
</ha-dialog-footer>
</ha-dialog>
`;
}
private _renderLive(progress: StartupProgressView) {
const localize = this._i18n.localize;
const phase = localize(`ui.startup_progress.phase.${progress.phase}`);
return html`
<div class="status">
<span class="phase">${phase}</span>
<span class="secondary">
${
progress.total === null
? localize("ui.startup_progress.integrations_unknown")
: localize("ui.startup_progress.integrations", {
done: progress.done,
total: progress.total,
})
}
${
progress.elapsed
? html` ·
${localize("ui.startup_progress.elapsed", {
seconds: Math.round(progress.elapsed),
})}`
: nothing
}
</span>
<ha-progress-bar
.value=${progress.percent ?? 0}
.indeterminate=${progress.percent === undefined}
.label=${phase}
></ha-progress-bar>
</div>
${
progress.active.length
? html`
<h3>${localize("ui.startup_progress.active")}</h3>
<ha-list-base>
${progress.active.map(([domain, seconds]) =>
this._row(domain, seconds)
)}
</ha-list-base>
`
: nothing
}
`;
}
private _renderSummary(elapsed: number | undefined, issues: number) {
const localize = this._i18n.localize;
const seconds = Math.round(elapsed ?? 0);
return html`
<ha-alert .alertType=${issues ? "warning" : "success"}>
${
!elapsed
? localize(`ui.startup_progress.phase.running`)
: issues
? localize("ui.startup_progress.started_with_issues", {
seconds,
count: issues,
})
: localize("ui.startup_progress.started", { seconds })
}
</ha-alert>
`;
}
private _renderSlowest() {
if (!this._setups?.length) {
return nothing;
}
return html`
<h3>${this._i18n.localize("ui.startup_progress.slowest")}</h3>
<ha-list-base>
${this._setups.map((setup) => this._row(setup.domain, setup.seconds!))}
</ha-list-base>
`;
}
private _renderFailed(domains: string[]) {
if (!domains.length) {
return nothing;
}
return html`
<h3>${this._i18n.localize("ui.startup_progress.failed")}</h3>
<ha-list-base>
${domains.map(
(domain) => html`
<ha-list-item-base>
<ha-domain-icon
slot="start"
.domain=${domain}
brand-fallback
></ha-domain-icon>
<span slot="headline">
${domainToName(this._i18n.localize, domain)}
</span>
<ha-svg-icon slot="end" .path=${mdiAlertCircle}></ha-svg-icon>
</ha-list-item-base>
`
)}
</ha-list-base>
`;
}
private _row(domain: string, seconds: number) {
return html`
<ha-list-item-base>
<ha-domain-icon
slot="start"
.domain=${domain}
brand-fallback
></ha-domain-icon>
<span slot="headline">
${domainToName(this._i18n.localize, domain)}
</span>
<span slot="end" class="secondary">
${this._i18n.localize("ui.startup_progress.seconds", {
seconds: seconds.toFixed(1),
})}
</span>
</ha-list-item-base>
`;
}
private _openIntegrations() {
navigate("/config/integrations/dashboard");
this.closeDialog();
}
static styles = [
haStyleDialog,
css`
ha-spinner {
display: block;
margin: var(--ha-space-6) auto;
}
.status {
display: flex;
flex-direction: column;
gap: var(--ha-space-1);
}
.phase {
font-weight: var(--ha-font-weight-medium);
}
.secondary {
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
}
ha-progress-bar {
margin-top: var(--ha-space-1);
}
h3 {
margin: var(--ha-space-4) 0 0;
font-size: var(--ha-font-size-m);
font-weight: var(--ha-font-weight-medium);
}
ha-svg-icon {
flex-shrink: 0;
color: var(--error-color);
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
"dialog-startup-progress": DialogStartupProgress;
}
}
@@ -0,0 +1,9 @@
import { fireEvent } from "../../common/dom/fire_event";
export const showStartupProgressDialog = (element: HTMLElement): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-startup-progress",
dialogImport: () => import("./dialog-startup-progress"),
dialogParams: {},
});
};
+45 -19
View File
@@ -2,6 +2,7 @@ import type { Auth, Connection } from "home-assistant-js-websocket";
import {
createConnection,
ERR_INVALID_AUTH,
ERR_INVALID_AUTH_CALLBACK,
getAuth,
subscribeConfig,
subscribeEntities,
@@ -36,17 +37,30 @@ declare global {
}
}
const replaceUrlParams = (searchParams: URLSearchParams) => {
const search = searchParams.toString();
history.replaceState(
null,
"",
`${location.pathname}${search ? `?${search}` : ""}`
);
};
const deleteAuthCallbackParams = (searchParams: URLSearchParams) => {
// https://github.com/home-assistant/home-assistant-js-websocket/blob/master/lib/auth.ts
// Remove all data from QueryCallbackData type
searchParams.delete("auth_callback");
searchParams.delete("code");
searchParams.delete("state");
searchParams.delete("storeToken");
};
const clearUrlParams = () => {
const searchParams = new URLSearchParams(location.search);
let changed = false;
// Clear auth data from url if we have been able to establish a connection
if (location.search.includes("auth_callback=1")) {
// https://github.com/home-assistant/home-assistant-js-websocket/blob/master/lib/auth.ts
// Remove all data from QueryCallbackData type
searchParams.delete("auth_callback");
searchParams.delete("code");
searchParams.delete("state");
searchParams.delete("storeToken");
deleteAuthCallbackParams(searchParams);
changed = true;
}
// Remove the cache-busting param added by the stale-index recovery guard in
@@ -57,12 +71,30 @@ const clearUrlParams = () => {
changed = true;
}
if (changed) {
const search = searchParams.toString();
history.replaceState(
null,
"",
`${location.pathname}${search ? `?${search}` : ""}`
);
replaceUrlParams(searchParams);
}
};
const authOptions = {
hassUrl,
limitHassInstance: true,
saveTokens,
loadTokens: () => Promise.resolve(loadTokens()),
};
const getAuthDroppingStaleCallback = async () => {
try {
return await getAuth(authOptions);
} catch (err: unknown) {
if (err !== ERR_INVALID_AUTH && err !== ERR_INVALID_AUTH_CALLBACK) {
throw err;
}
// The auth callback in the URL was used or has expired. Drop it so a
// reload does not replay it, and fall back to stored tokens or a new login.
const searchParams = new URLSearchParams(location.search);
deleteAuthCallbackParams(searchParams);
replaceUrlParams(searchParams);
return getAuth(authOptions);
}
};
@@ -71,13 +103,7 @@ const authProm = isExternal
import("../external_app/external_auth").then(({ createExternalAuth }) =>
createExternalAuth(hassUrl)
)
: () =>
getAuth({
hassUrl,
limitHassInstance: true,
saveTokens,
loadTokens: () => Promise.resolve(loadTokens()),
});
: getAuthDroppingStaleCallback;
const connProm = async (auth) => {
try {
+2 -1
View File
@@ -292,7 +292,8 @@ class NotificationManager extends LitElement {
inset-inline-end: auto;
inset-block-end: calc(
var(--safe-area-inset-bottom, 0px) + var(--ha-space-4) +
var(--notification-stack-bottom-offset, 0px)
var(--notification-stack-bottom-offset, 0px) +
var(--ha-startup-progress-offset, 0px)
);
inset-inline-start: 50%;
margin: 0;
@@ -153,12 +153,15 @@ export class AutomationTriggerController implements ReactiveController {
return false;
}
const config = sidebarConfig.config as
{ condition?: unknown } | { action?: { condition?: unknown } };
{ condition?: unknown } | { action?: unknown };
if ("condition" in config && config.condition === "trigger") {
return true;
}
// A row can hold any YAML, so `action` may be a service name instead of
// the wrapped action of an action sidebar.
return !!(
"action" in config &&
typeof config.action === "object" &&
config.action &&
"condition" in config.action &&
config.action.condition === "trigger"
+1 -1
View File
@@ -597,7 +597,7 @@ export const configSections: Record<string, PageNavigation[]> = {
translationKey: "storage",
iconPath: mdiDatabase,
iconColor: "#518C43",
component: "hassio",
component: ["hassio", "recorder"],
adminOnly: true,
},
{
@@ -16,9 +16,13 @@ import type {
HASSDomCurrentTargetEvent,
HASSDomEvent,
} from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-entity-picker";
import "../../../../components/entity/ha-statistic-picker";
import type { HaStatisticPicker } from "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-alert";
import "../../../../components/radio/ha-radio-group";
import type { HaRadioGroup } from "../../../../components/radio/ha-radio-group";
import "../../../../components/radio/ha-radio-option";
import "../../../../components/ha-select";
import type { HaSelectSelectEvent } from "../../../../components/ha-select";
import "../../../../components/input/ha-input";
@@ -36,6 +40,7 @@ import {
getBatteryPrimaryStat,
isBatteryDirections,
} from "../../../../data/energy";
import { batteryCapacityUnits } from "../../../../data/energy-battery";
import {
getStatisticLabel,
getStatisticMetadata,
@@ -89,9 +94,11 @@ type BatteryEnergyKey =
type BatteryDraft = Partial<Record<BatteryEnergyKey, string>> &
Pick<
BatteryTotalsSourceTypeEnergyPreference,
"name" | "stat_soc" | "capacity"
"name" | "stat_soc" | "capacity" | "entity_capacity"
>;
type CapacityType = "manual" | "sensor";
interface BatteryPower {
powerType: PowerType;
powerConfig: PowerConfig;
@@ -100,6 +107,7 @@ interface BatteryPower {
interface BatteryFormState {
mode?: BatteryMode;
capacityType: CapacityType;
powerType?: PowerType;
source?: BatterySourceTypeEnergyPreference;
}
@@ -108,6 +116,7 @@ const energyUnitClasses = ["energy"];
const powerUnitClasses = ["power"];
const socStatisticsUnits = ["%"];
const socDeviceClass = "battery";
const capacitySensorDomains = ["sensor"];
const ENERGY_NAME_KEYS: Record<BatteryEnergyKey, LocalizeKeys> = {
stat_energy_from:
@@ -157,6 +166,7 @@ const toDraft = (source?: BatterySourceTypeEnergyPreference): BatteryDraft => {
name: source.name,
stat_soc: source.stat_soc,
capacity: source.capacity,
entity_capacity: source.entity_capacity,
};
if (isBatteryDirections(source)) {
BATTERY_DIRECTIONS.forEach(({ energy }) => {
@@ -174,11 +184,13 @@ const activeEnergyKeys = (mode: BatteryMode): BatteryEnergyKey[] =>
? ["stat_energy_from", "stat_energy_to"]
: BATTERY_DIRECTIONS.map(({ energy }) => energy);
// Only the active mode's fields are saved. The backend writes stat_rate itself.
// Only the active mode's fields and the selected capacity source are saved.
// The backend writes stat_rate itself.
const toSource = (
draft: BatteryDraft,
mode: BatteryMode,
power: BatteryPower
power: BatteryPower,
capacityType: CapacityType
): BatterySourceTypeEnergyPreference => {
let source: BatterySourceTypeEnergyPreference;
if (mode === "total") {
@@ -214,7 +226,11 @@ const toSource = (
if (draft.stat_soc) {
source.stat_soc = draft.stat_soc;
}
if (draft.capacity != null) {
if (capacityType === "sensor") {
if (draft.entity_capacity) {
source.entity_capacity = draft.entity_capacity;
}
} else if (draft.capacity != null) {
source.capacity = draft.capacity;
}
return source;
@@ -297,6 +313,8 @@ export class HaEnergyBatterySourceEditor extends EnergyEditorMixin(
@state() private _source?: BatteryDraft;
@state() private _capacityType: CapacityType = "manual";
@state() private _powerType: PowerType = "none";
@state() private _powerConfig: PowerConfig = {};
@@ -329,6 +347,7 @@ export class HaEnergyBatterySourceEditor extends EnergyEditorMixin(
this._saving = false;
this._mode = getBatteryMode(saved);
this._source = toDraft(saved);
this._capacityType = saved?.entity_capacity ? "sensor" : "manual";
const totals = saved && !isBatteryDirections(saved) ? saved : undefined;
this._powerType = getPowerTypeFromConfig(
@@ -372,9 +391,15 @@ export class HaEnergyBatterySourceEditor extends EnergyEditorMixin(
private _formState(): BatteryFormState {
return {
mode: this._mode,
capacityType: this._capacityType,
powerType: this._mode === "total" ? this._powerType : undefined,
source: this._mode
? toSource(this._source ?? {}, this._mode, this._power)
? toSource(
this._source ?? {},
this._mode,
this._power,
this._capacityType
)
: undefined,
};
}
@@ -515,7 +540,9 @@ export class HaEnergyBatterySourceEditor extends EnergyEditorMixin(
private _renderDirections(pending: PowerIntegral<BatteryEnergyKey>[]) {
const source = this._source!;
const labelStatistic =
getBatteryPrimaryStat(toSource(source, "directions", this._power)) ||
getBatteryPrimaryStat(
toSource(source, "directions", this._power, this._capacityType)
) ||
pending[0]?.rate ||
BATTERY_DIRECTIONS.map(({ power }) => this._directionPower[power]).find(
Boolean
@@ -687,22 +714,62 @@ export class HaEnergyBatterySourceEditor extends EnergyEditorMixin(
@value-changed=${this._statisticSocChanged}
.disabled=${this._saving}
></ha-statistic-picker>
<ha-input
.value=${source.capacity != null ? String(source.capacity) : ""}
<ha-radio-group
.label=${this._localize(
"ui.panel.config.energy.battery.dialog.capacity"
)}
.hint=${this._localize(
"ui.panel.config.energy.battery.dialog.capacity_helper"
)}
type="number"
step="any"
min="0"
@input=${this._capacityChanged}
.value=${this._capacityType}
.disabled=${this._saving}
@change=${this._capacityTypeChanged}
>
<span slot="end">kWh</span>
</ha-input>
<ha-radio-option value="manual">
${this._localize(
"ui.panel.config.energy.battery.dialog.capacity_manual"
)}
</ha-radio-option>
<ha-radio-option value="sensor">
${this._localize(
"ui.panel.config.energy.battery.dialog.capacity_use_sensor"
)}
</ha-radio-option>
</ha-radio-group>
${
this._capacityType === "sensor"
? html`
<ha-entity-picker
.value=${source.entity_capacity}
.includeDomains=${capacitySensorDomains}
.includeUnitOfMeasurement=${batteryCapacityUnits}
.label=${this._localize(
"ui.panel.config.energy.battery.dialog.capacity_sensor"
)}
.helper=${this._localize(
"ui.panel.config.energy.battery.dialog.capacity_sensor_helper"
)}
.disabled=${this._saving}
required
@value-changed=${this._capacitySensorChanged}
></ha-entity-picker>
`
: html`
<ha-input
.accessibleLabel=${this._localize(
"ui.panel.config.energy.battery.dialog.capacity"
)}
.value=${source.capacity != null ? String(source.capacity) : ""}
.hint=${this._localize(
"ui.panel.config.energy.battery.dialog.capacity_helper"
)}
type="number"
step="any"
min="0"
@input=${this._capacityChanged}
.disabled=${this._saving}
>
<span slot="end">kWh</span>
</ha-input>
`
}
`;
}
@@ -730,6 +797,9 @@ export class HaEnergyBatterySourceEditor extends EnergyEditorMixin(
if (!source || !this._mode) {
return false;
}
if (this._capacityType === "sensor" && !source.entity_capacity) {
return false;
}
// Energy fields can be provided by power sensors
const isProvided = (energy: BatteryEnergyKey) =>
!!source[energy] || pending.some((item) => item.energy === energy);
@@ -878,6 +948,23 @@ export class HaEnergyBatterySourceEditor extends EnergyEditorMixin(
this._updateDirtyState(this._formState());
}
private _capacityTypeChanged(ev: HASSDomCurrentTargetEvent<HaRadioGroup>) {
const value = ev.currentTarget.value;
if (value !== "manual" && value !== "sensor") {
return;
}
this._capacityType = value;
this._updateFormDirtyState();
}
private _capacitySensorChanged(ev: ValueChangedEvent<string>) {
this._source = {
...this._source!,
entity_capacity: ev.detail.value || undefined,
};
this._updateFormDirtyState();
}
private _capacityChanged(ev: InputEvent) {
const rawValue = (ev.target as HaInput).value;
const value = rawValue ? parseFloat(rawValue) : NaN;
@@ -900,6 +987,7 @@ export class HaEnergyBatterySourceEditor extends EnergyEditorMixin(
// be saved with the submitted source
const params = this.params;
const power = this._power;
const capacityType = this._capacityType;
let draft = this._source!;
const isCurrent = () => this.params === params && this.isConnected;
this._error = undefined;
@@ -922,7 +1010,7 @@ export class HaEnergyBatterySourceEditor extends EnergyEditorMixin(
}
}
await params.saveCallback(toSource(draft, mode, power));
await params.saveCallback(toSource(draft, mode, power, capacityType));
if (isCurrent()) {
this._markDirtyStateClean();
}
@@ -221,7 +221,9 @@ const computeDeviceClassOptions = (
const groups: string[][] = OVERRIDE_DEVICE_CLASSES[domain];
for (const group of groups) {
if (originalDeviceClass && group.includes(originalDeviceClass)) {
related.push(...group);
related.push(
...group.filter((deviceClass) => deviceClass !== originalDeviceClass)
);
} else {
others.push(...group);
}
@@ -343,7 +345,10 @@ export class EntityRegistrySettingsEditor extends LitElement {
this._name = this.entry.name || this._originalName;
this._isMainEntity = !!this._device && !this._entryName;
this._icon = this.entry.icon || "";
this._deviceClass = this.entry.device_class ?? null;
this._deviceClass =
this.entry.device_class === this._originalDeviceClass
? null
: (this.entry.device_class ?? null);
this._origEntityId = this.entry.entity_id;
this._areaId = this.entry.area_id;
this._mainEntityWithOwnArea = this._isMainEntity && !!this.entry.area_id;
@@ -5,6 +5,7 @@ import {
mdiNas,
mdiPencil,
mdiPlayBox,
mdiRefresh,
mdiReload,
} from "@mdi/js";
import type { PropertyValues, TemplateResult } from "lit";
@@ -32,6 +33,8 @@ import {
fetchHassioHostInfo,
fetchHostDisksUsage,
} from "../../../data/hassio/host";
import type { RecorderDatabaseUsage } from "../../../data/recorder";
import { fetchRecorderDatabaseUsage } from "../../../data/recorder";
import type {
SupervisorMount,
SupervisorMounts,
@@ -52,6 +55,7 @@ import { bytesToString } from "../../../util/bytes-to-string";
import { showMoveDatadiskDialog } from "./show-dialog-move-datadisk";
import { showMountViewDialog } from "./show-dialog-view-mount";
import "./storage-breakdown-chart";
import "./storage-database-card";
@customElement("ha-config-section-storage")
class HaConfigSectionStorage extends LitElement {
@@ -76,6 +80,17 @@ class HaConfigSectionStorage extends LitElement {
// Guards against a slow response from a previous reload landing in a newer one.
private _mountUsageGeneration = 0;
// Undefined until loaded, null when no recent report exists.
@state() private _databaseUsage?: RecorderDatabaseUsage | null;
@state() private _databaseLoading = false;
@state() private _databaseAnalyzing = false;
@state() private _databaseError?: string;
private _databaseRequested = false;
protected async firstUpdated(
changedProps: PropertyValues<this>
): Promise<void> {
@@ -88,6 +103,19 @@ class HaConfigSectionStorage extends LitElement {
await panelIsReady(this);
}
protected willUpdate(changedProps: PropertyValues<this>): void {
super.willUpdate(changedProps);
// Recorder can finish loading after the page mounted during startup
if (
changedProps.has("hass") &&
!this._databaseRequested &&
isComponentLoaded(this.hass.config, "recorder")
) {
this._databaseRequested = true;
this._loadDatabaseUsage();
}
}
protected render(): TemplateResult | typeof nothing {
if (this._mountsInfo === undefined) {
return nothing;
@@ -100,6 +128,7 @@ class HaConfigSectionStorage extends LitElement {
].includes(mount.type)
);
const isHAOS = this._hostInfo?.features.includes("haos");
const hasRecorder = isComponentLoaded(this.hass.config, "recorder");
return html`
<hass-subpage
back-path="/config/system"
@@ -107,6 +136,19 @@ class HaConfigSectionStorage extends LitElement {
.narrow=${this.narrow}
.header=${this.hass.localize("ui.panel.config.storage.caption")}
>
${
hasRecorder
? html`<ha-icon-button
slot="toolbar-icon"
.disabled=${this._databaseLoading || this._databaseAnalyzing}
.path=${mdiRefresh}
.label=${this.hass.localize(
"ui.panel.config.storage.database.analyze"
)}
@click=${this._analyzeDatabase}
></ha-icon-button>`
: nothing
}
<div class="content">
${
this._error
@@ -152,104 +194,126 @@ class HaConfigSectionStorage extends LitElement {
`
: ""
}
<ha-card
outlined
.header=${this.hass.localize(
"ui.panel.config.storage.network_mounts.title"
)}
>
${
this._mountsInfo === null
? html`<ha-alert
class="mounts-not-supported"
alert-type="warning"
.title=${this.hass.localize(
"ui.panel.config.storage.network_mounts.not_supported.title"
)}
>
${
isHAOS
? html`${this.hass.localize(
"ui.panel.config.storage.network_mounts.not_supported.os",
{ version: "10.2" }
)}
<ha-button
appearance="plain"
slot="action"
@click=${this._navigateToUpdates}
>
${this.hass.localize(
"ui.panel.config.storage.network_mounts.not_supported.navigate_to_updates"
)}
</ha-button>`
: this.hass.localize(
"ui.panel.config.storage.network_mounts.not_supported.supervised"
)
}
</ha-alert>`
: validMounts?.length
? html`<ha-list-base
aria-label=${this.hass.localize(
"ui.panel.config.storage.network_mounts.title"
)}
>
${validMounts.map((mount) =>
mount.state === SupervisorMountState.ACTIVE
? html`<ha-list-item-button
.mount=${mount}
@click=${this._changeMount}
>
${this._renderMountContent(mount)}
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`
: html`<ha-list-item-base>
${this._renderMountContent(mount)}
<div slot="end" class="mount-actions">
<ha-icon-button
.mount=${mount}
.label=${this.hass.localize(
"ui.panel.config.storage.network_mounts.reload"
)}
@click=${this._reloadMount}
.path=${mdiReload}
></ha-icon-button>
<ha-icon-button
.mount=${mount}
.label=${this.hass.localize("ui.common.edit")}
@click=${this._changeMount}
.path=${mdiPencil}
></ha-icon-button>
</div>
</ha-list-item-base>`
)}
</ha-list-base>`
: html`<div class="no-mounts">
<ha-svg-icon .path=${mdiNas}></ha-svg-icon>
<p>
${this.hass.localize(
"ui.panel.config.storage.network_mounts.no_mounts"
)}
</p>
</div>`
}
${
this._mountsInfo !== null
? html`<div class="card-actions">
<ha-button appearance="plain" @click=${this._addMount}>
${this.hass.localize(
"ui.panel.config.storage.network_mounts.add_title"
)}
</ha-button>
</div>`
: nothing
}
</ha-card>
${
hasRecorder
? html`<storage-database-card
.narrow=${this.narrow}
.usage=${this._databaseUsage}
.analyzing=${this._databaseAnalyzing}
.error=${this._databaseError}
></storage-database-card>`
: nothing
}
${
isComponentLoaded(this.hass.config, "hassio")
? this._renderMounts(validMounts, isHAOS)
: nothing
}
</div>
</hass-subpage>
`;
}
private _renderMounts(
validMounts: SupervisorMount[] | undefined,
isHAOS: boolean | undefined
) {
return html`
<ha-card
outlined
.header=${this.hass.localize(
"ui.panel.config.storage.network_mounts.title"
)}
>
${
this._mountsInfo === null
? html`<ha-alert
class="mounts-not-supported"
alert-type="warning"
.title=${this.hass.localize(
"ui.panel.config.storage.network_mounts.not_supported.title"
)}
>
${
isHAOS
? html`${this.hass.localize(
"ui.panel.config.storage.network_mounts.not_supported.os",
{ version: "10.2" }
)}
<ha-button
appearance="plain"
slot="action"
@click=${this._navigateToUpdates}
>
${this.hass.localize(
"ui.panel.config.storage.network_mounts.not_supported.navigate_to_updates"
)}
</ha-button>`
: this.hass.localize(
"ui.panel.config.storage.network_mounts.not_supported.supervised"
)
}
</ha-alert>`
: validMounts?.length
? html`<ha-list-base
aria-label=${this.hass.localize(
"ui.panel.config.storage.network_mounts.title"
)}
>
${validMounts.map((mount) =>
mount.state === SupervisorMountState.ACTIVE
? html`<ha-list-item-button
.mount=${mount}
@click=${this._changeMount}
>
${this._renderMountContent(mount)}
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`
: html`<ha-list-item-base>
${this._renderMountContent(mount)}
<div slot="end" class="mount-actions">
<ha-icon-button
.mount=${mount}
.label=${this.hass.localize(
"ui.panel.config.storage.network_mounts.reload"
)}
@click=${this._reloadMount}
.path=${mdiReload}
></ha-icon-button>
<ha-icon-button
.mount=${mount}
.label=${this.hass.localize("ui.common.edit")}
@click=${this._changeMount}
.path=${mdiPencil}
></ha-icon-button>
</div>
</ha-list-item-base>`
)}
</ha-list-base>`
: html`<div class="no-mounts">
<ha-svg-icon .path=${mdiNas}></ha-svg-icon>
<p>
${this.hass.localize(
"ui.panel.config.storage.network_mounts.no_mounts"
)}
</p>
</div>`
}
${
this._mountsInfo !== null
? html`<div class="card-actions">
<ha-button appearance="plain" @click=${this._addMount}>
${this.hass.localize(
"ui.panel.config.storage.network_mounts.add_title"
)}
</ha-button>
</div>`
: nothing
}
</ha-card>
`;
}
private _renderDiskLifeTime(diskLifeTime: number | null) {
if (diskLifeTime === null) {
return nothing;
@@ -376,6 +440,45 @@ class HaConfigSectionStorage extends LitElement {
}
}
private async _loadDatabaseUsage(): Promise<void> {
this._databaseLoading = true;
this._databaseError = undefined;
try {
this._databaseUsage = await fetchRecorderDatabaseUsage(this.hass);
} catch (err: any) {
this._databaseError = this._databaseErrorMessage(err);
} finally {
this._databaseLoading = false;
}
}
private async _analyzeDatabase(): Promise<void> {
this._databaseAnalyzing = true;
this._databaseError = undefined;
try {
this._databaseUsage = await fetchRecorderDatabaseUsage(this.hass, true);
} catch (err: any) {
this._databaseError = this._databaseErrorMessage(err);
} finally {
this._databaseAnalyzing = false;
}
}
private _databaseErrorMessage(err: any): string {
switch (err.code) {
case "recorder_not_ready":
return this.hass.localize(
"ui.panel.config.storage.database.errors.recorder_not_ready"
);
case "migration_in_progress":
return this.hass.localize(
"ui.panel.config.storage.database.errors.migration_in_progress"
);
default:
return err.message || err.code || String(err);
}
}
private _moveDatadisk(): void {
showMoveDatadiskDialog(this, {
hostInfo: this._hostInfo!,
@@ -0,0 +1,492 @@
import type { TemplateResult } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import type { HassConfig } from "home-assistant-js-websocket";
import memoizeOne from "memoize-one";
import { getGraphColorByIndex } from "../../../common/color/colors";
import { formatDateTime } from "../../../common/datetime/format_date_time";
import { consume } from "../../../common/decorators/consume";
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import type { HASSDomCurrentTargetEvent } from "../../../common/dom/fire_event";
import { computeStateName } from "../../../common/entity/compute_state_name";
import { formatNumber } from "../../../common/number/format_number";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/data-table/ha-data-table";
import type {
DataTableColumnContainer,
DataTableRowData,
} from "../../../components/data-table/ha-data-table";
import "../../../components/ha-alert";
import "../../../components/ha-card";
import "../../../components/ha-segmented-bar";
import type { Segment } from "../../../components/ha-segmented-bar";
import "../../../components/ha-spinner";
import {
configContext,
fullEntitiesContext,
internationalizationContext,
statesContext,
uiContext,
} from "../../../data/context";
import type {
RecorderDatabaseUsage,
RecorderTableUsage,
} from "../../../data/recorder";
import type { EntityRegistryEntry } from "../../../data/entity/entity_registry";
import { showMoreInfoDialog } from "../../../dialogs/more-info/show-ha-more-info-dialog";
import type { FrontendLocaleData } from "../../../data/translation";
import type { Themes } from "../../../data/ws-themes";
import type {
HomeAssistant,
HomeAssistantConfig,
HomeAssistantInternationalization,
HomeAssistantUI,
} from "../../../types";
import { bytesToString } from "../../../util/bytes-to-string";
// Tables below minShare of the total are summed into otherBytes.
export const groupSmallTables = (
tables: RecorderTableUsage[],
minShare = 0.01
): { tables: RecorderTableUsage[]; otherBytes: number; totalBytes: number } => {
const totalBytes = tables.reduce((sum, table) => sum + table.bytes, 0);
const large = tables.filter(
(table) => table.bytes > 0 && table.bytes >= totalBytes * minShare
);
return {
tables: large,
otherBytes: totalBytes - large.reduce((sum, table) => sum + table.bytes, 0),
totalBytes,
};
};
// Row id for the rows the database cannot attribute to an entity or statistic.
export const UNKNOWN_ROW_ID = "unknown";
export interface DatabaseUsageRow {
id: string;
states: number;
statistics: number;
statistics_short_term: number;
bytes: number | null;
}
// Statistics of an entity share its ID and are merged into its row.
export const databaseUsageRows = (
usage: RecorderDatabaseUsage
): DatabaseUsageRow[] => {
const rows = new Map<string, DatabaseUsageRow>();
const row = (id: string | null) => {
const key = id ?? UNKNOWN_ROW_ID;
let result = rows.get(key);
if (!result) {
result = {
id: key,
states: 0,
statistics: 0,
statistics_short_term: 0,
bytes: usage.tables ? 0 : null,
};
rows.set(key, result);
}
return result;
};
for (const entity of usage.entities) {
const result = row(entity.entity_id);
result.states += entity.states;
if (result.bytes !== null) {
result.bytes +=
(entity.states_bytes ?? 0) + (entity.attributes_bytes ?? 0);
}
}
for (const statistic of usage.statistics) {
const result = row(statistic.statistic_id);
result.statistics += statistic.statistics;
result.statistics_short_term += statistic.statistics_short_term;
if (result.bytes !== null) {
result.bytes +=
(statistic.statistics_bytes ?? 0) +
(statistic.statistics_short_term_bytes ?? 0);
}
}
return [...rows.values()];
};
interface EntityUsageRow extends DatabaseUsageRow, DataTableRowData {
name: string;
hasSettings: boolean;
}
@customElement("storage-database-card")
export class StorageDatabaseCard extends LitElement {
@property({ type: Boolean }) public narrow = false;
// Undefined until loaded, null when no recent report exists.
@property({ attribute: false }) public usage?: RecorderDatabaseUsage | null;
@property({ type: Boolean }) public analyzing = false;
@property() public error?: string;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@state()
@consume({ context: internationalizationContext, subscribe: true })
@transform<HomeAssistantInternationalization, FrontendLocaleData>({
transformer: ({ locale }) => locale,
})
private _locale!: FrontendLocaleData;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig>({
transformer: ({ config }) => config,
})
private _hassConfig!: HassConfig;
@state()
@consume({ context: uiContext, subscribe: true })
@transform<HomeAssistantUI, Themes>({
transformer: ({ themes }) => themes,
})
private _themes!: Themes;
// Not reactive: read when building the rows, which follow the entity registry.
@consume({ context: statesContext, subscribe: true })
private _states!: HomeAssistant["states"];
// Includes disabled entities, which have no state but can have recorded data.
@state()
@consume({ context: fullEntitiesContext, subscribe: true })
private _entityRegistry: EntityRegistryEntry[] = [];
protected render(): TemplateResult {
const usage = this.usage;
return html`
<ha-card
outlined
.header=${this._localize("ui.panel.config.storage.database.title")}
>
<div class="card-content">
${
this.error
? html`<ha-alert alert-type="error">${this.error}</ha-alert>`
: nothing
}
${
this.analyzing
? html`<div class="loading">
<ha-spinner></ha-spinner>
<span>
${this._localize(
"ui.panel.config.storage.database.analyzing"
)}
</span>
</div>`
: nothing
}
${
usage
? this._renderUsage(usage)
: usage === null && !this.analyzing
? html`<p class="description">
${this._localize(
"ui.panel.config.storage.database.description"
)}
</p>`
: nothing
}
</div>
</ha-card>
`;
}
private _renderUsage(usage: RecorderDatabaseUsage) {
return html`
<div class="summary">
<span class="total">${bytesToString(usage.total_bytes)}</span>
<span class="generated">
${this._localize("ui.panel.config.storage.database.as_of", {
time: formatDateTime(
new Date(usage.generated_at),
this._locale,
this._hassConfig
),
})}
</span>
${
!usage.tables?.length && usage.free_bytes
? html`<span class="generated">
${this._localize(
"ui.panel.config.storage.database.unused_space_of",
{ size: bytesToString(usage.free_bytes) }
)}
</span>`
: nothing
}
${
usage.wal_bytes
? html`<span class="generated">
${this._localize("ui.panel.config.storage.database.wal", {
size: bytesToString(usage.wal_bytes),
})}
</span>`
: nothing
}
</div>
${
usage.tables?.length
? html`<ha-segmented-bar
.heading=${this._localize(
"ui.panel.config.storage.database.tables"
)}
.segments=${this._tableSegments(
usage.tables,
usage.total_bytes,
usage.free_bytes,
this._localize,
this._themes
)}
></ha-segmented-bar>`
: nothing
}
<div class="table">
<ha-data-table
.narrow=${this.narrow}
.columns=${this._columns(
this._localize,
this._locale,
this.narrow,
usage.tables !== null
)}
.data=${this._rows(usage, this._entityRegistry, this._localize)}
.searchLabel=${this._localize(
"ui.panel.config.storage.database.search"
)}
.noDataText=${this._localize(
"ui.panel.config.storage.database.no_entities"
)}
></ha-data-table>
</div>
`;
}
private _tableSegments = memoizeOne(
(
tables: RecorderTableUsage[],
totalBytes: number,
freeBytes: number | null,
localize: LocalizeFunc,
_themes: Themes
): Segment[] => {
const computedStyles = getComputedStyle(this);
const grouped = groupSmallTables(tables);
const segments = grouped.tables.map((table) => ({
name: table.table,
bytes: table.bytes,
}));
// PostgreSQL catalogs are in the total but not in the tables.
const otherBytes =
grouped.otherBytes +
Math.max(0, totalBytes - grouped.totalBytes - (freeBytes ?? 0));
if (otherBytes > 0) {
segments.push({
name: localize("ui.panel.config.storage.database.other_tables"),
bytes: otherBytes,
});
}
const result: Segment[] = segments.map((segment, index) => ({
value: segment.bytes,
color: getGraphColorByIndex(index, computedStyles),
label: html`${segment.name}
<span style="color: var(--secondary-text-color)"
>${bytesToString(segment.bytes)}</span
>`,
}));
if (freeBytes) {
result.push({
value: freeBytes,
color:
"var(--ha-bar-background-color, var(--secondary-background-color))",
label: html`${localize("ui.panel.config.storage.database.unused_space")}
<span style="color: var(--secondary-text-color)"
>${bytesToString(freeBytes)}</span
>`,
});
}
return result;
}
);
// Keyed on the entity registry, not the states, so renames update the
// names without rebuilding the rows on every state change.
private _rows = memoizeOne(
(
usage: RecorderDatabaseUsage,
entityRegistry: EntityRegistryEntry[],
localize: LocalizeFunc
): EntityUsageRow[] => {
const registered = new Set(
entityRegistry.map((entry) => entry.entity_id)
);
return databaseUsageRows(usage).map((row) => {
const stateObj = this._states[row.id];
return {
...row,
// Statistics of external sources (e.g. "sensor:energy") have no entity.
hasSettings: stateObj !== undefined || registered.has(row.id),
name:
row.id === UNKNOWN_ROW_ID
? localize("ui.panel.config.storage.database.unknown")
: stateObj
? computeStateName(stateObj)
: row.id,
};
});
}
);
private _columns = memoizeOne(
(
localize: LocalizeFunc,
locale: FrontendLocaleData,
narrow: boolean,
hasSizes: boolean
): DataTableColumnContainer<EntityUsageRow> => ({
name: {
title: localize("ui.panel.config.storage.database.columns.entity"),
main: true,
sortable: true,
filterable: true,
flex: 3,
template: (row) => {
const content = html`${row.name}
${
row.id !== UNKNOWN_ROW_ID && row.name !== row.id
? html`<div class="secondary">${row.id}</div>`
: nothing
}`;
// Rendered inside the data table, which styles .row-button.
return row.hasSettings
? html`<button
type="button"
class="row-button"
data-entity-id=${row.id}
@click=${this._openSettings}
>
${content}
</button>`
: content;
},
},
id: {
title: localize("ui.panel.config.storage.database.columns.entity_id"),
filterable: true,
hidden: true,
},
states: {
title: localize("ui.panel.config.storage.database.columns.states"),
type: "numeric",
minWidth: "100px",
maxWidth: "100px",
sortable: true,
// Without sizes the rows are sorted by states instead.
direction: hasSizes ? undefined : "desc",
hidden: narrow && hasSizes,
showNarrow: !hasSizes,
template: (row) => formatNumber(row.states, locale),
},
statistics: {
title: localize("ui.panel.config.storage.database.columns.statistics"),
type: "numeric",
minWidth: "100px",
maxWidth: "100px",
sortable: true,
hidden: narrow,
template: (row) => formatNumber(row.statistics, locale),
},
statistics_short_term: {
title: localize(
"ui.panel.config.storage.database.columns.statistics_short_term"
),
type: "numeric",
minWidth: "130px",
maxWidth: "130px",
sortable: true,
hidden: narrow,
template: (row) => formatNumber(row.statistics_short_term, locale),
},
bytes: {
title: localize("ui.panel.config.storage.database.columns.size"),
type: "numeric",
minWidth: "100px",
maxWidth: "100px",
sortable: true,
direction: hasSizes ? "desc" : undefined,
hidden: !hasSizes,
showNarrow: hasSizes,
template: (row) => bytesToString(row.bytes ?? 0),
},
})
);
// Arrow function: the data table renders the template, not this card.
private _openSettings = (
ev: HASSDomCurrentTargetEvent<HTMLButtonElement>
) => {
showMoreInfoDialog(this, {
entityId: ev.currentTarget.dataset.entityId!,
view: "settings",
});
};
static styles = css`
ha-card {
margin-bottom: 12px;
}
.card-content {
display: flex;
flex-direction: column;
gap: var(--ha-space-4);
}
.loading {
display: flex;
align-items: center;
gap: var(--ha-space-3);
color: var(--secondary-text-color);
}
.summary {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: var(--ha-space-2);
}
.total {
font-size: var(--ha-font-size-2xl);
}
.generated,
.description {
color: var(--secondary-text-color);
}
.description {
margin: 0;
}
.table {
height: 480px;
}
ha-data-table {
--data-table-border-width: 0;
--data-table-row-border-width: 0;
height: 100%;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"storage-database-card": StorageDatabaseCard;
}
}
+1 -37
View File
@@ -17,7 +17,6 @@ import {
saveFrontendSystemData,
subscribeFrontendSystemData,
type HomeFrontendSystemData,
type MaintenanceFrontendSystemData,
type SecurityFrontendSystemData,
} from "../../data/frontend";
import type { LovelaceDashboardStrategyConfig } from "../../data/lovelace/config/types";
@@ -55,8 +54,6 @@ class PanelHome extends SubscribeMixin(LitElement) {
@state() private _securityConfig: SecurityFrontendSystemData = {};
@state() private _maintenanceConfig: MaintenanceFrontendSystemData = {};
@state() private _extraActionItems?: ExtraActionItem[];
@query(".banner") private _banner?: HTMLElement;
@@ -65,8 +62,6 @@ class PanelHome extends SubscribeMixin(LitElement) {
private _securityConfigRevision = 0;
private _maintenanceConfigRevision = 0;
public hassSubscribe() {
return [
subscribeFrontendSystemData(
@@ -84,21 +79,6 @@ class PanelHome extends SubscribeMixin(LitElement) {
}
}
),
subscribeFrontendSystemData(
this.hass.connection,
"maintenance",
({ value }) => {
this._maintenanceConfigRevision++;
const config = value || {};
if (deepEqual(config, this._maintenanceConfig)) {
return;
}
this._maintenanceConfig = config;
if (this.hasUpdated) {
this._setLovelace();
}
}
),
];
}
@@ -199,13 +179,11 @@ class PanelHome extends SubscribeMixin(LitElement) {
private async _loadConfig() {
const securityConfigRevision = this._securityConfigRevision;
const maintenanceConfigRevision = this._maintenanceConfigRevision;
const [translationsResult, homeResult, securityResult, maintenanceResult] =
const [translationsResult, homeResult, securityResult] =
await Promise.allSettled([
this.hass.loadFragmentTranslation("lovelace"),
fetchFrontendSystemData(this.hass.connection, "home"),
fetchFrontendSystemData(this.hass.connection, "security"),
fetchFrontendSystemData(this.hass.connection, "maintenance"),
]);
if (translationsResult.status === "rejected") {
@@ -236,19 +214,6 @@ class PanelHome extends SubscribeMixin(LitElement) {
} else if (securityConfigRevision === this._securityConfigRevision) {
this._securityConfig = securityResult.value || {};
}
if (maintenanceResult.status === "rejected") {
// eslint-disable-next-line no-console
console.error(
"Failed to load maintenance configuration:",
maintenanceResult.reason
);
if (maintenanceConfigRevision === this._maintenanceConfigRevision) {
this._maintenanceConfig = {};
}
} else if (maintenanceConfigRevision === this._maintenanceConfigRevision) {
this._maintenanceConfig = maintenanceResult.value || {};
}
}
private _debounceRegenerateStrategy = debounce(
@@ -435,7 +400,6 @@ class PanelHome extends SubscribeMixin(LitElement) {
strategy: {
type: "home",
alert_entities: this._securityConfig.alert_entities,
maintenance_hidden_entities: this._maintenanceConfig.hidden_entities,
favorite_entities: this._config?.favorite_entities,
home_panel: true,
hide_welcome_message: this._config?.hide_welcome_message,
@@ -40,6 +40,7 @@ import {
validateEnergyCollectionKey,
} from "../../../../data/energy";
import { EnergyCollectionController } from "../../../../data/energy-collection-controller";
import { getBatteryCapacity } from "../../../../data/energy-battery";
import { calculateStatisticsSumGrowth } from "../../../../data/recorder";
import type {
HomeAssistant,
@@ -125,6 +126,9 @@ class HuiEnergyDistrubutionCard extends LitElement implements LovelaceCard {
if (source.stat_soc) {
next[source.stat_soc] = states?.[source.stat_soc];
}
if (source.entity_capacity) {
next[source.entity_capacity] = states?.[source.entity_capacity];
}
}
}
return preserveUnchangedEntityStatesRecord(this._entityStates, next);
@@ -285,7 +289,7 @@ class HuiEnergyDistrubutionCard extends LitElement implements LovelaceCard {
soc: source.stat_soc
? Number(this._entityStates?.[source.stat_soc]?.state)
: NaN,
capacity: source.capacity,
capacity: getBatteryCapacity(source, this._entityStates),
}))
.filter((battery) => Number.isFinite(battery.soc));
if (socBatteries.length) {
@@ -1,193 +0,0 @@
import { mdiEye, mdiEyeOff } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import "../../../components/ha-svg-icon";
import type { HomeAssistant } from "../../../types";
import "./hui-card";
import type { HuiCard } from "./hui-card";
import type { LovelaceCard, LovelaceGridOptions } from "../types";
import type { EntityVisibilityCardConfig } from "./types";
@customElement("hui-entity-visibility-card")
export class HuiEntityVisibilityCard
extends LitElement
implements LovelaceCard
{
@property({ attribute: false }) public hass?: HomeAssistant;
@property({ type: Boolean }) public preview = false;
@state() private _config?: EntityVisibilityCardConfig;
private _card?: HuiCard;
public setConfig(config: EntityVisibilityCardConfig): void {
if (!config.entity) {
throw new Error("No entity configured");
}
if (!config.card) {
throw new Error("No card configured");
}
this._config = config;
this._card = document.createElement("hui-card");
this._card.hass = this.hass;
this._card.preview = this.preview;
this._card.config = config.card;
this._card.inert = true;
this._card.load();
}
public getCardSize(): number | Promise<number> {
return this._card?.getCardSize() ?? 1;
}
public getGridOptions(): LovelaceGridOptions {
return this._card?.getGridOptions() ?? {};
}
public connectedCallback(): void {
super.connectedCallback();
window.addEventListener(
"entity-visibility-changed",
this._entityVisibilityChanged
);
}
public disconnectedCallback(): void {
super.disconnectedCallback();
window.removeEventListener(
"entity-visibility-changed",
this._entityVisibilityChanged
);
}
protected willUpdate(changedProps: PropertyValues<this>): void {
super.willUpdate(changedProps);
if (!this._card) {
return;
}
if (changedProps.has("hass")) {
this._card.hass = this.hass;
}
if (changedProps.has("preview")) {
this._card.preview = this.preview;
}
}
protected render() {
if (!this._config || !this.hass || !this._card) {
return nothing;
}
const hidden = Boolean(this._config.hidden);
const stateObj = this.hass.states[this._config.entity];
const name = stateObj
? this.hass.formatEntityName(stateObj)
: this._config.entity;
return html`
<div class="wrapper" ?hidden-entity=${hidden}>
${this._card}
<button
class="control"
aria-label=${this.hass.localize(
`ui.components.items-display-editor.${hidden ? "show" : "hide"}`,
{ label: name }
)}
@click=${this._toggle}
>
<ha-svg-icon .path=${hidden ? mdiEyeOff : mdiEye}></ha-svg-icon>
</button>
</div>
`;
}
private _entityVisibilityChanged = (
ev: HASSDomEvent<HASSDomEvents["entity-visibility-changed"]>
) => {
if (
this._config?.hidden === undefined ||
ev.detail.entity !== this._config.entity ||
ev.detail.hidden === this._config.hidden
) {
return;
}
this._config = { ...this._config, hidden: ev.detail.hidden };
};
private _toggle(): void {
if (!this._config) {
return;
}
const hidden = !this._config.hidden;
this._config = { ...this._config, hidden };
fireEvent(this, "entity-visibility-changed", {
entity: this._config.entity,
hidden,
});
}
static styles: CSSResultGroup = css`
.wrapper {
position: relative;
height: 100%;
border-radius: var(--ha-card-border-radius, var(--ha-border-radius-lg));
}
hui-card {
display: block;
height: 100%;
}
.wrapper[hidden-entity] hui-card {
opacity: 0.8;
}
.wrapper[hidden-entity]::after {
content: "";
position: absolute;
inset: 0;
border: 2px dotted var(--secondary-text-color);
border-radius: inherit;
pointer-events: none;
}
.control {
position: absolute;
inset: 0;
z-index: 1;
display: flex;
align-items: flex-end;
justify-content: flex-end;
margin: 0;
padding: var(--ha-space-2);
border: none;
background: none;
border-radius: inherit;
cursor: pointer;
color: var(--primary-text-color);
}
.control:focus-visible {
outline: 2px solid var(--primary-color);
}
.control ha-svg-icon {
display: flex;
padding: var(--ha-space-1);
border-radius: var(--ha-border-radius-circle);
background: var(--secondary-background-color);
box-shadow: var(--ha-box-shadow-s);
--mdc-icon-size: 20px;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"hui-entity-visibility-card": HuiEntityVisibilityCard;
}
interface GlobalEventHandlersEventMap {
"entity-visibility-changed": HASSDomEvent<
HASSDomEvents["entity-visibility-changed"]
>;
}
interface HASSDomEvents {
"entity-visibility-changed": { entity: string; hidden: boolean };
}
}
@@ -326,10 +326,13 @@ export class HuiHomeSummaryCard extends LitElement implements LovelaceCard {
: localize("ui.card.home-summary.no_media_playing");
}
case "maintenance": {
const maintenanceEntities = findMaintenanceEntities(
{ states, entities, devices, areas, floors },
this._config.hidden_entities
);
const maintenanceEntities = findMaintenanceEntities({
states,
entities,
devices,
areas,
floors,
});
const lowBatteryEntities = filterLowBatteryEntities(
states,
-7
View File
@@ -71,12 +71,6 @@ export interface ConditionalCardConfig extends LovelaceCardConfig {
conditions: VisibilityCondition[];
}
export interface EntityVisibilityCardConfig extends LovelaceCardConfig {
entity: string;
hidden?: boolean;
card: LovelaceCardConfig;
}
export interface EmptyStateButtonConfig {
text: string;
icon?: string;
@@ -767,7 +761,6 @@ export interface HeadingCardConfig extends LovelaceCardConfig {
export interface HomeSummaryCard extends LovelaceCardConfig {
summary: HomeSummary;
alert_entities?: SecurityAlertEntityConfig[];
hidden_entities?: string[];
vertical?: boolean;
tap_action?: ActionConfig;
hold_action?: ActionConfig;
@@ -38,7 +38,6 @@ const LAZY_LOAD_TYPES = {
area: () => import("../cards/hui-area-card"),
calendar: () => import("../cards/hui-calendar-card"),
conditional: () => import("../cards/hui-conditional-card"),
"entity-visibility": () => import("../cards/hui-entity-visibility-card"),
"empty-state": () => import("../cards/hui-empty-state-card"),
"energy-compare": () => import("../cards/energy/hui-energy-compare-card"),
"energy-carbon-consumed-gauge": () =>
@@ -1,13 +0,0 @@
import type { LovelaceCardConfig } from "../../../../data/lovelace/config/card";
import type { EntityVisibilityCardConfig } from "../../cards/types";
export type ComputeEntityCard = (entityId: string) => LovelaceCardConfig;
export const wrapEntityVisibility =
(hiddenEntities: Set<string>, computeCard: ComputeEntityCard) =>
(entityId: string): EntityVisibilityCardConfig => ({
type: "entity-visibility",
entity: entityId,
hidden: hiddenEntities.has(entityId),
card: computeCard(entityId),
});
@@ -21,7 +21,6 @@ import type { HomeOverviewViewStrategyConfig } from "./home-overview-view-strate
export interface HomeDashboardStrategyConfig {
type: "home";
alert_entities?: SecurityAlertEntityConfig[];
maintenance_hidden_entities?: string[];
favorite_entities?: string[];
home_panel?: boolean;
hide_welcome_message?: boolean;
@@ -107,7 +106,6 @@ export class HomeDashboardStrategy extends ReactiveElement {
strategy: {
type: "home-overview",
alert_entities: config.alert_entities,
maintenance_hidden_entities: config.maintenance_hidden_entities,
favorite_entities: config.favorite_entities,
home_panel: config.home_panel,
hide_welcome_message: config.hide_welcome_message,
@@ -60,7 +60,6 @@ import { OTHER_DEVICES_FILTERS } from "./helpers/other-devices-filters";
export interface HomeOverviewViewStrategyConfig {
type: "home-overview";
alert_entities?: SecurityAlertEntityConfig[];
maintenance_hidden_entities?: string[];
favorite_entities?: string[];
home_panel?: boolean;
hide_welcome_message?: boolean;
@@ -371,9 +370,7 @@ export class HomeOverviewViewStrategy extends ReactiveElement {
const hasSecurity =
hass.panels.security && findSecurityEntities(hass).length > 0;
const hasMaintenance =
hass.panels.maintenance &&
findMaintenanceEntities(hass, config.maintenance_hidden_entities).length >
0;
hass.panels.maintenance && findMaintenanceEntities(hass).length > 0;
const alertEntities = config.alert_entities ?? [];
const alertSeverityEntities = filterSecurityAlertEntities(
@@ -471,9 +468,6 @@ export class HomeOverviewViewStrategy extends ReactiveElement {
? ({
type: "home-summary",
summary: "maintenance",
hidden_entities: config.maintenance_hidden_entities?.length
? config.maintenance_hidden_entities
: undefined,
tap_action: {
action: "navigate",
navigation_path: config.home_panel
+13 -156
View File
@@ -1,23 +1,13 @@
import { mdiPencil } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { debounce } from "../../common/util/debounce";
import { deepEqual } from "../../common/util/deep-equal";
import "../../components/ha-button";
import "../../components/ha-icon-button";
import "../../components/ha-top-app-bar-fixed";
import {
fetchFrontendSystemDataAfterSaves,
queueFrontendSystemDataSave,
type MaintenanceFrontendSystemData,
} from "../../data/frontend";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { showToast } from "../../util/toast";
import { generateLovelaceViewStrategy } from "../lovelace/strategies/get-strategy";
import type { Lovelace } from "../lovelace/types";
import "../lovelace/views/hui-view";
@@ -40,20 +30,10 @@ class PanelMaintenance extends LitElement {
@state() private _lovelace?: Lovelace;
@state() private _config?: MaintenanceFrontendSystemData;
@state() private _editVisibility = false;
@state() private _searchParams = new URLSearchParams(window.location.search);
private _childPanelReady?: ChildPanelReady;
private _loadConfigPromise?: Promise<void>;
private _loadConfigRevision = 0;
private _setLovelaceRevision = 0;
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
// Initial setup
@@ -67,22 +47,13 @@ class PanelMaintenance extends LitElement {
}
const oldHass = changedProps.get("hass") as this["hass"];
if (
oldHass &&
this.hass.config.state === "RUNNING" &&
oldHass.config.state !== "RUNNING"
) {
this._setup();
return;
}
if (oldHass && oldHass.localize !== this.hass.localize) {
this._setLovelace();
return;
}
if (oldHass && this.hass) {
// Refresh the generated view when registries or panels change.
// If the entity registry changed, ask the user if they want to refresh the config
if (
oldHass.entities !== this.hass.entities ||
oldHass.devices !== this.hass.devices ||
@@ -92,47 +63,24 @@ class PanelMaintenance extends LitElement {
) {
if (this.hass.config.state === "RUNNING") {
this._debounceRegistriesChanged();
return;
}
}
// If ha started, refresh the config
if (
this.hass.config.state === "RUNNING" &&
oldHass.config.state !== "RUNNING"
) {
this._setLovelace();
}
}
}
private async _setup() {
this._loadConfigPromise = this._loadConfig();
await Promise.all([
this.hass.loadFragmentTranslation("lovelace"),
this._loadConfigPromise,
]);
await this.hass.loadFragmentTranslation("lovelace");
this._setLovelace();
}
private async _loadConfig() {
const revision = ++this._loadConfigRevision;
this._config = undefined;
try {
const data = await fetchFrontendSystemDataAfterSaves(
this.hass.connection,
"maintenance"
);
if (revision !== this._loadConfigRevision) {
return;
}
this._config = data || {};
} catch (err) {
if (revision !== this._loadConfigRevision) {
return;
}
this._editVisibility = false;
// eslint-disable-next-line no-console
console.error("Failed to load maintenance configuration:", err);
showToast(this, {
message: this.hass.localize("ui.panel.maintenance.editor.load_failed"),
duration: 0,
dismissable: true,
});
}
}
private _debounceRegistriesChanged = debounce(
() => this._registriesChanged(),
200
@@ -149,27 +97,6 @@ class PanelMaintenance extends LitElement {
.backButton=${this._searchParams.has("historyBack")}
>
<div slot="title">${this.hass.localize("panel.maintenance")}</div>
${
!this.hass.user?.is_admin
? nothing
: this._editVisibility
? html`<ha-button
slot="actionItems"
appearance="filled"
size="s"
@click=${this._stopEditVisibility}
>
${this.hass.localize("ui.panel.lovelace.menu.exit_edit_mode")}
</ha-button>`
: this._config
? html`<ha-icon-button
slot="actionItems"
.path=${mdiPencil}
.label=${this.hass.localize("ui.panel.maintenance.editor.title")}
@click=${this._startEditVisibility}
></ha-icon-button>`
: nothing
}
${
this._lovelace
? html`
@@ -181,7 +108,6 @@ class PanelMaintenance extends LitElement {
.narrow=${this.narrow}
.lovelace=${this._lovelace}
.index=${this._viewIndex}
@entity-visibility-changed=${this._visibilityChanged}
></hui-view>
</hui-view-container>
`
@@ -191,31 +117,16 @@ class PanelMaintenance extends LitElement {
`;
}
private async _setLovelace(force = false) {
const revision = ++this._setLovelaceRevision;
if (this._loadConfigPromise) {
await this._loadConfigPromise;
}
private async _setLovelace() {
const viewConfig = await generateLovelaceViewStrategy(
{
strategy: {
...MAINTENANCE_LOVELACE_VIEW_CONFIG.strategy,
hidden_entities: this._config?.hidden_entities,
edit_visibility: this._editVisibility || undefined,
},
},
MAINTENANCE_LOVELACE_VIEW_CONFIG,
this.hass
);
if (revision !== this._setLovelaceRevision) {
return;
}
const config = { views: [viewConfig] };
const rawConfig = { views: [MAINTENANCE_LOVELACE_VIEW_CONFIG] };
if (!force && deepEqual(config, this._lovelace?.config)) {
if (deepEqual(config, this._lovelace?.config)) {
return;
}
@@ -235,60 +146,6 @@ class PanelMaintenance extends LitElement {
};
}
private _startEditVisibility = () => {
this._editVisibility = true;
this._setLovelace();
};
private _stopEditVisibility = () => {
this._editVisibility = false;
if (!this._config) {
this._loadConfigPromise = this._loadConfig();
}
this._setLovelace();
};
private _visibilityChanged = (
ev: HASSDomEvent<HASSDomEvents["entity-visibility-changed"]>
) => {
if (!this._config) {
return;
}
const { entity, hidden } = ev.detail;
const hiddenEntities = (this._config.hidden_entities ?? []).filter(
(entityId) => entityId !== entity
);
if (hidden) {
hiddenEntities.push(entity);
}
this._saveConfig({
...this._config,
hidden_entities: hiddenEntities.length ? hiddenEntities : undefined,
});
};
private _saveConfig(config: MaintenanceFrontendSystemData): Promise<void> {
this._config = config;
return queueFrontendSystemDataSave(
this.hass.connection,
"maintenance",
config
).catch(async (err) => {
// eslint-disable-next-line no-console
console.error("Failed to save maintenance configuration:", err);
showToast(this, {
message: this.hass.localize("ui.panel.maintenance.editor.save_failed"),
duration: 0,
dismissable: true,
});
if (config !== this._config) {
return;
}
await this._loadConfig();
await this._setLovelace(true);
});
}
static get styles(): CSSResultGroup {
return [
haStyle,
@@ -14,10 +14,6 @@ import type { LovelaceSectionRawConfig } from "../../../data/lovelace/config/sec
import type { LovelaceViewConfig } from "../../../data/lovelace/config/view";
import type { HomeAssistant } from "../../../types";
import type { TileCardConfig } from "../../lovelace/cards/types";
import {
wrapEntityVisibility,
type ComputeEntityCard,
} from "../../lovelace/strategies/helpers/entity-visibility";
import { BINARY_STATE_ON } from "../../../common/const";
import { computeDomain } from "../../../common/entity/compute_domain";
import { getDeviceEntityDisplayLookup } from "../../../data/device/device_registry";
@@ -25,8 +21,6 @@ import { findBatteryChargingEntity } from "../../../data/entity/entity_registry"
export interface MaintenanceViewStrategyConfig {
type: "maintenance";
hidden_entities?: string[];
edit_visibility?: boolean;
}
export const maintenanceEntityFilters: EntityFilter[] = [
@@ -41,10 +35,8 @@ export const maintenanceEntityFilters: EntityFilter[] = [
];
export const findMaintenanceEntities = (
sources: EntityFilterSources,
hiddenEntities?: string[]
): string[] =>
findFilteredEntities(sources, maintenanceEntityFilters, hiddenEntities);
sources: EntityFilterSources
): string[] => findFilteredEntities(sources, maintenanceEntityFilters);
const LOW_BATTERY_THRESHOLD = 20;
@@ -127,8 +119,7 @@ const computeMaintenanceTileCard = (
const processAreasForBattery = (
areaIds: string[],
hass: HomeAssistant,
entities: string[],
computeCard: ComputeEntityCard
entities: string[]
): LovelaceCardConfig[] => {
const cards: LovelaceCardConfig[] = [];
@@ -150,7 +141,9 @@ const processAreasForBattery = (
const areaCards: LovelaceCardConfig[] = [];
for (const entityId of areaBatteryEntities) {
areaCards.push(computeCard(entityId));
areaCards.push(
computeMaintenanceTileCard(hass.states, hass.entities, entityId)
);
}
if (areaCards.length > 0) {
@@ -174,8 +167,7 @@ const processAreasForBattery = (
const processUnassignedEntities = (
hass: HomeAssistant,
entities: string[],
computeCard: ComputeEntityCard
entities: string[]
): LovelaceCardConfig[] => {
const unassignedFilter = generateEntityFilter(
hass.states,
@@ -191,7 +183,9 @@ const processUnassignedEntities = (
const cards: LovelaceCardConfig[] = [];
for (const entityId of unassignedEntities) {
cards.push(computeCard(entityId));
cards.push(
computeMaintenanceTileCard(hass.states, hass.entities, entityId)
);
}
return cards;
@@ -200,7 +194,7 @@ const processUnassignedEntities = (
@customElement("maintenance-view-strategy")
export class MaintenanceViewStrategy extends ReactiveElement {
static async generate(
config: MaintenanceViewStrategyConfig,
_config: MaintenanceViewStrategyConfig,
hass: HomeAssistant
): Promise<LovelaceViewConfig> {
const areas = Object.values(hass.areas);
@@ -209,16 +203,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
const sections: LovelaceSectionRawConfig[] = [];
const entities = findMaintenanceEntities(
hass,
config.edit_visibility ? undefined : config.hidden_entities
);
const computeTileCard = (entityId: string) =>
computeMaintenanceTileCard(hass.states, hass.entities, entityId);
const computeCard: ComputeEntityCard = config.edit_visibility
? wrapEntityVisibility(new Set(config.hidden_entities), computeTileCard)
: computeTileCard;
const entities = findMaintenanceEntities(hass);
const floorCount =
hierarchy.floors.length + (hierarchy.areas.length ? 1 : 0);
@@ -244,12 +229,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForBattery(
areaIds,
hass,
entities,
computeCard
);
const areaCards = processAreasForBattery(areaIds, hass, entities);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -275,12 +255,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForBattery(
hierarchy.areas,
hass,
entities,
computeCard
);
const areaCards = processAreasForBattery(hierarchy.areas, hass, entities);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -289,11 +264,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
}
// Process unassigned entities
const unassignedCards = processUnassignedEntities(
hass,
entities,
computeCard
);
const unassignedCards = processUnassignedEntities(hass, entities);
if (unassignedCards.length > 0) {
const section: LovelaceSectionRawConfig = {
+8
View File
@@ -15,6 +15,8 @@ import {
DataZoomComponent,
VisualMapComponent,
ToolboxComponent,
MarkAreaComponent,
BrushComponent,
} from "echarts/components";
// Features like Universal Transition and Label Layout
@@ -48,6 +50,8 @@ import type {
GridComponentOption,
DataZoomComponentOption,
VisualMapComponentOption,
MarkAreaComponentOption,
BrushComponentOption,
} from "echarts/components";
import type { ComposeOption } from "echarts/core";
@@ -62,6 +66,8 @@ export type ECOption = ComposeOption<
| GridComponentOption
| DataZoomComponentOption
| VisualMapComponentOption
| MarkAreaComponentOption
| BrushComponentOption
| SankeySeriesOption
| GraphSeriesOption
| SunburstSeriesOption
@@ -91,6 +97,8 @@ echarts.use([
UniversalTransition,
CanvasRenderer,
ToolboxComponent,
MarkAreaComponent,
BrushComponent,
]);
export { LinearGradient };
+110 -89
View File
@@ -1,24 +1,33 @@
import type { PropertyValues } from "lit";
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import type { BootstrapProgress } from "../data/bootstrap_integrations";
import {
STATE_NOT_RUNNING,
STATE_RUNNING,
STATE_STARTING,
} from "home-assistant-js-websocket";
import type { BootstrapIntegrationsTimings } from "../data/bootstrap_integrations";
import { subscribeBootstrapIntegrations } from "../data/bootstrap_integrations";
import { domainToName } from "../data/integration";
computeStartupProgress,
startupTransition,
subscribeBootstrapProgress,
} from "../data/bootstrap_integrations";
import type { Constructor } from "../types";
import { HOST_ACTION_TOAST_ID, showToast } from "../util/toast";
import type { HassBaseEl } from "./hass-base-mixin";
import { navigate } from "../common/navigate";
import { showStartupProgressDialog } from "../dialogs/startup-progress/show-dialog-startup-progress";
const CONNECTION_LOST_TOAST_ID = "connection-lost";
const SERVER_STARTUP_TOAST_ID = "server-startup";
export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
class extends superClass {
private _subscribedBootstrapIntegrations?: Promise<UnsubscribeFunc>;
private _subscribedBootstrapProgress?: Promise<UnsubscribeFunc>;
private _startupProgress?: BootstrapProgress;
private _startupProgressVisible = false;
private _startupFinishPending = false;
private _startupProgressEl?: HTMLElementTagNameMap["ha-startup-progress"];
private _startupProgressResize?: ResizeObserver;
private _disconnectedTimeout?: number;
@@ -26,6 +35,7 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
super.firstUpdated(changedProps);
// Need to load in advance because when disconnected, can't dynamically load code.
setTimeout(() => import("../managers/notification-manager"), 5000);
setTimeout(() => import("../components/ha-startup-progress"), 5000);
}
updated(changedProperties: PropertyValues<this>) {
@@ -35,38 +45,17 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
return;
}
if (oldHass?.config?.state !== this.hass!.config.state) {
if (this.hass!.config.state === STATE_NOT_RUNNING) {
showToast(this, {
id: SERVER_STARTUP_TOAST_ID,
message:
this.hass!.localize("ui.notification_toast.starting") ||
"Home Assistant is starting. Not everything will be available until it is finished.",
duration: -1,
dismissable: false,
action: {
text:
this.hass!.localize("ui.notification_toast.dismiss") ||
"Dismiss",
action: () => {
this._unsubscribeBootstrapIntegrations();
},
},
});
this._subscribeBootstrapIntegrations();
} else if (
oldHass?.config &&
oldHass.config.state === STATE_NOT_RUNNING &&
(this.hass!.config.state === STATE_STARTING ||
this.hass!.config.state === STATE_RUNNING)
) {
this._unsubscribeBootstrapIntegrations();
showToast(this, {
id: SERVER_STARTUP_TOAST_ID,
message: this.hass!.localize("ui.notification_toast.started"),
duration: 5000,
});
const transition = startupTransition(
oldHass?.config?.state,
this.hass!.config.state
);
if (transition === "show") {
this._showStartupProgress();
} else if (transition === "finish") {
this._requestFinishStartupProgress();
}
}
this._updateStartupProgress();
if (
this.hass!.config.safe_mode &&
oldHass?.config?.safe_mode !== this.hass!.config.safe_mode
@@ -126,70 +115,102 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
}, 1000);
}
private _handleMessage(message: BootstrapIntegrationsTimings): void {
if (this.hass!.config.state !== STATE_NOT_RUNNING) {
private _showStartupProgress() {
this._unsubscribeBootstrapProgress();
this._startupProgress = undefined;
this._startupFinishPending = false;
this._startupProgressVisible = true;
this._subscribedBootstrapProgress = subscribeBootstrapProgress(
this.hass!.connection,
(message) => {
this._startupProgress = message;
if (this._startupFinishPending && message.phase === "running") {
this._finishStartupProgress();
}
}
);
this._updateStartupProgress();
}
private async _updateStartupProgress() {
if (!this._startupProgressVisible) {
return;
}
if (Object.keys(message).length === 0) {
showToast(this, {
id: SERVER_STARTUP_TOAST_ID,
message:
this.hass!.localize("ui.notification_toast.wrapping_up_startup") ||
`Wrapping up startup. Not everything will be available until it is finished.`,
duration: -1,
dismissable: false,
action: {
text:
this.hass!.localize("ui.notification_toast.dismiss") || "Dismiss",
action: () => {
this._unsubscribeBootstrapIntegrations();
},
},
});
await import("../components/ha-startup-progress");
// Hidden or finished while the component was loading.
if (!this._startupProgressVisible) {
return;
}
if (!this._startupProgressEl) {
this._startupProgressEl = document.createElement("ha-startup-progress");
this._startupProgressEl.addEventListener(
"startup-progress-dismissed",
() => this._hideStartupProgress()
);
// Lifts the toast stack above the card so neither covers the other.
this._startupProgressResize = new ResizeObserver(() =>
this.style.setProperty(
"--ha-startup-progress-offset",
`calc(${this._startupProgressEl?.offsetHeight ?? 0}px + var(--ha-space-2))`
)
);
this._startupProgressResize.observe(this._startupProgressEl);
}
// The launch screen render swap clears the root, detaching the card.
if (!this._startupProgressEl.isConnected) {
this.renderRoot.appendChild(this._startupProgressEl);
}
this._startupProgressEl.detailsAvailable =
!!this.renderRoot.querySelector("home-assistant-main");
}
// Show the integration that has been starting for the longest time
const integration = Object.entries(message).sort(
([, a], [, b]) => b - a
)[0][0];
// Keeps the subscription, so the completion toast still reflects late failures.
private _hideStartupProgress() {
this._startupProgressVisible = false;
this._startupProgressResize?.disconnect();
this._startupProgressResize = undefined;
this.style.removeProperty("--ha-startup-progress-offset");
this._startupProgressEl?.remove();
this._startupProgressEl = undefined;
}
// Core can reach RUNNING before its final snapshot with the failures arrives.
private _requestFinishStartupProgress() {
if (this._startupProgress?.phase === "running") {
this._finishStartupProgress();
} else {
this._startupFinishPending = true;
}
}
private _finishStartupProgress() {
this._startupFinishPending = false;
const { failed } = computeStartupProgress(
this._startupProgress,
this.hass!.config.state
);
this._hideStartupProgress();
this._unsubscribeBootstrapProgress();
const issues = failed.length;
showToast(this, {
id: SERVER_STARTUP_TOAST_ID,
message:
this.hass!.localize("ui.notification_toast.integration_starting", {
integration: domainToName(this.hass!.localize, integration),
}) ||
`Starting ${integration}. Not everything will be available until it is finished.`,
duration: -1,
dismissable: false,
message: issues
? this.hass!.localize("ui.notification_toast.started_with_issues", {
count: issues,
})
: this.hass!.localize("ui.notification_toast.started"),
duration: issues ? 10000 : 5000,
action: {
text:
this.hass!.localize("ui.notification_toast.dismiss") || "Dismiss",
action: () => {
this._unsubscribeBootstrapIntegrations();
},
text: this.hass!.localize("ui.notification_toast.details"),
action: () => showStartupProgressDialog(this),
},
});
}
private _unsubscribeBootstrapIntegrations() {
if (this._subscribedBootstrapIntegrations) {
this._subscribedBootstrapIntegrations.then((unsub) => unsub());
this._subscribedBootstrapIntegrations = undefined;
private _unsubscribeBootstrapProgress() {
if (this._subscribedBootstrapProgress) {
this._subscribedBootstrapProgress.then((unsub) => unsub());
this._subscribedBootstrapProgress = undefined;
}
}
private _subscribeBootstrapIntegrations() {
if (!this.hass) {
return;
}
this._subscribedBootstrapIntegrations = subscribeBootstrapIntegrations(
this.hass!,
(message) => {
this._handleMessage(message);
}
);
}
};
+57 -12
View File
@@ -2902,13 +2902,34 @@
"close": "Close",
"dismiss_all": "Dismiss all"
},
"startup_progress": {
"phase": {
"preparing": "Preparing startup",
"setup": "Setting up integrations",
"wrap_up": "Finishing integration setup",
"starting": "Running final startup tasks",
"running": "Home Assistant has started"
},
"integrations": "{done} of {total} integrations set up",
"integrations_unknown": "Not everything is available until startup is finished",
"starting": "Home Assistant is starting",
"starting_secondary": "Some features may not be available yet",
"details": "Startup details",
"elapsed": "Starting for {seconds} s",
"active": "Setting up now",
"seconds": "{seconds} s",
"failed": "Failed to set up",
"started": "Home Assistant started in {seconds} s.",
"started_with_issues": "Home Assistant started in {seconds} s. {count, plural,\n one {# integration needs}\n other {# integrations need}\n} attention.",
"slowest": "Slowest integrations",
"open_integrations": "Open integrations"
},
"notification_toast": {
"action_failed": "Failed to perform the action {service}.",
"connection_lost": "Connection lost. Reconnecting…",
"started": "Home Assistant has started!",
"starting": "Home Assistant is starting. Not everything will be available until it is finished.",
"wrapping_up_startup": "Wrapping up startup. Not everything will be available until it is finished.",
"integration_starting": "Starting {integration}. Not everything will be available until startup is finished.",
"started_with_issues": "Home Assistant has started. {count, plural,\n one {# integration needs}\n other {# integrations need}\n} attention.",
"details": "Details",
"triggered": "Triggered {name}",
"dismiss": "Dismiss",
"no_matching_link_found": "No matching My link found for {path}",
@@ -3008,13 +3029,6 @@
"save_failed": "Failed to save security and safety page configuration"
}
},
"maintenance": {
"editor": {
"title": "Edit visible entities",
"load_failed": "Failed to load maintenance page configuration",
"save_failed": "Failed to save maintenance page configuration"
}
},
"my": {
"not_supported": "This redirect is not supported by your Home Assistant instance. Check the {link} for the supported redirects and the version they where introduced.",
"component_not_loaded": "This redirect is not supported by your Home Assistant instance. You need the integration {integration} to use this redirect.",
@@ -4843,6 +4857,10 @@
"state_of_charge": "Battery state of charge sensor",
"state_of_charge_helper": "Sensor reporting battery state of charge as %.",
"capacity": "Battery capacity",
"capacity_manual": "Enter manually",
"capacity_use_sensor": "Use a sensor",
"capacity_sensor": "Battery capacity sensor",
"capacity_sensor_helper": "Sensor reporting usable battery capacity in Wh, kWh, or MWh. Use total capacity, not remaining energy or lifetime charged energy. Used to weight the combined state of charge.",
"capacity_helper": "Usable battery capacity in kWh. Used to weight the combined state of charge when you have multiple batteries of different sizes.",
"power": "Battery power",
"power_helper": "Pick a sensor which measures the electricity flowing into and out of the battery in either of {unit}. Positive values indicate discharging the battery, negative values indicate charging the battery.",
@@ -9983,6 +10001,33 @@
"lifetime_used_description": "The drive’s wear level is shown as a percentage, based on endurance indicators reported by the device via NVMe SMART or eMMC lifetime estimate fields.",
"disk_metrics": "Disk metrics",
"change_chart_type": "Change chart type",
"database": {
"title": "Database",
"description": "Use the refresh button to analyze the database and see which tables, entities and statistics use the most space.",
"analyzing": "Analyzing the database, this can take a while on a large database...",
"analyze": "Analyze database",
"as_of": "as of {time}",
"tables": "Tables",
"other_tables": "Other tables",
"unused_space": "Unused space",
"unused_space_of": "{size} unused",
"wal": "plus {size} write-ahead log",
"unknown": "Without a known entity or statistic",
"search": "Search entities",
"no_entities": "No recorded entities",
"errors": {
"recorder_not_ready": "The recorder database is not available yet.",
"migration_in_progress": "The recorder database is being migrated. Try again when the migration has finished."
},
"columns": {
"entity": "Entity",
"entity_id": "Entity ID",
"states": "States",
"statistics": "Statistics",
"statistics_short_term": "Short-term statistics",
"size": "Size"
}
},
"datadisk": {
"title": "Move data disk",
"description": "You are currently using ''{current_path}'' as data disk. Moving the data disk will reboot your device and it's estimated to take {time} minutes. Your Home Assistant installation will not be accessible during this period. Do not disconnect the power during the move!",
@@ -11297,7 +11342,7 @@
"description": "This card shows the amount of water consumed per source."
},
"power-sources-graph": {
"name": "Power sources graph",
"name": "Power profile graph",
"description": "This card shows historical power data.",
"show_legend": "Show legend"
},
@@ -13240,7 +13285,7 @@
"power_sankey_title": "Current power flow",
"water_flow_sankey_title": "Current water flow",
"gas_flow_sankey_title": "Current gas flow",
"power_sources_graph_title": "Power sources",
"power_sources_graph_title": "Power profile",
"energy_grid_balance_title": "Grid energy balance",
"energy_grid_neutrality_gauge_title": "Grid neutrality gauge",
"energy_solar_consumed_gauge_title": "Solar consumed gauge",
+8 -2
View File
@@ -5,6 +5,12 @@ export const bytesToString = (value = 0, decimals = 2): string => {
const k = 1024;
decimals = decimals < 0 ? 0 : decimals;
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const i = Math.floor(Math.log(value) / Math.log(k));
return `${parseFloat((value / k ** i).toFixed(decimals))} ${sizes[i]}`;
let i = Math.floor(Math.log(value) / Math.log(k));
let rounded = parseFloat((value / k ** i).toFixed(decimals));
// Rounding can reach the next unit, e.g. 1048575 bytes is 1024.00 KB.
if (rounded >= k && i < sizes.length - 1) {
i++;
rounded = parseFloat((value / k ** i).toFixed(decimals));
}
return `${rounded} ${sizes[i]}`;
};
+2 -1
View File
@@ -1,8 +1,9 @@
import { fileDownload } from "./file_download";
// Quote fields containing a separator, quote or line break (RFC 4180).
export function csvSafeString(s: string | undefined): string {
if (!s) return "";
return /,|"/.test(s) ? `"${s.replaceAll('"', '""')}"` : s;
return /[,"\r\n]/.test(s) ? `"${s.replaceAll('"', '""')}"` : s;
}
export function csvDownload(data: string[][], filename: string) {
@@ -0,0 +1,77 @@
import { assert, describe, it } from "vitest";
import { kelvinRangeFromEntityStates } from "../../../src/common/color/color-temp-selector-range";
const statesFor = (
ranges: Record<string, { min?: unknown; max?: unknown } | undefined>
) => {
const states: Record<string, { attributes: Record<string, unknown> }> = {};
for (const [entityId, range] of Object.entries(ranges)) {
states[entityId] = {
attributes:
range === undefined
? {}
: {
min_color_temp_kelvin: range.min,
max_color_temp_kelvin: range.max,
},
};
}
return states;
};
describe("kelvinRangeFromEntityStates", () => {
it("returns undefined when no entity reports a range", () => {
assert.strictEqual(kelvinRangeFromEntityStates(undefined), undefined);
assert.deepEqual(kelvinRangeFromEntityStates({}), undefined);
assert.deepEqual(
kelvinRangeFromEntityStates(statesFor({ "light.bulb": undefined })),
undefined
);
});
it("uses the selected light range", () => {
assert.deepEqual(
kelvinRangeFromEntityStates(
statesFor({ "light.oranzovka": { min: 1600, max: 4000 } })
),
{ min: 1600, max: 4000 }
);
});
it("uses the overlap when several lights are targeted", () => {
assert.deepEqual(
kelvinRangeFromEntityStates(
statesFor({
"light.warm": { min: 1600, max: 4000 },
"light.daylight": { min: 2000, max: 6500 },
})
),
{ min: 2000, max: 4000 }
);
});
it("spans the widest range when the lights do not overlap", () => {
assert.deepEqual(
kelvinRangeFromEntityStates(
statesFor({
"light.warm": { min: 1600, max: 2500 },
"light.cold": { min: 5000, max: 6500 },
})
),
{ min: 1600, max: 6500 }
);
});
it("ignores a light with an invalid range", () => {
assert.deepEqual(
kelvinRangeFromEntityStates(
statesFor({
"light.broken": { min: 4000, max: 1600 },
"light.bulb": { min: "1600", max: 4000 },
"light.oranzovka": { min: 1600, max: 4000 },
})
),
{ min: 1600, max: 4000 }
);
});
});
+7 -15
View File
@@ -710,23 +710,15 @@ describe("generateEntityFilter", () => {
});
describe("findFilteredEntities", () => {
it("should match any filter and drop excluded entities", () => {
const entities = findFilteredEntities(
mockHass,
[{ domain: "light" }, { domain: "switch" }],
["light.bedroom"]
);
expect(entities).toContain("light.living_room");
expect(entities).toContain("switch.kitchen");
expect(entities).not.toContain("light.bedroom");
expect(entities).not.toContain("sensor.temperature");
});
it("should return every match when nothing is excluded", () => {
const entities = findFilteredEntities(mockHass, [{ domain: "light" }]);
it("should match entities against any of the filters", () => {
const entities = findFilteredEntities(mockHass, [
{ domain: "light" },
{ domain: "switch" },
]);
expect(entities).toContain("light.living_room");
expect(entities).toContain("light.bedroom");
expect(entities).toContain("switch.kitchen");
expect(entities).not.toContain("sensor.temperature");
});
});
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { capitalizeFirstLetter } from "../../../src/common/string/capitalize-first-letter";
describe("capitalizeFirstLetter", () => {
it("uppercases the first letter", () => {
expect(capitalizeFirstLetter("living room")).toBe("Living room");
expect(capitalizeFirstLetter("école")).toBe("École");
});
it("leaves the rest of the string unchanged", () => {
expect(capitalizeFirstLetter("kITCHEN")).toBe("KITCHEN");
});
it("returns an empty string unchanged", () => {
expect(capitalizeFirstLetter("")).toBe("");
});
it("uppercases a first letter outside the BMP", () => {
// DESERET SMALL LETTER LONG I -> DESERET CAPITAL LETTER LONG I
expect(capitalizeFirstLetter("\u{10428}\u{10428}")).toBe(
"\u{10400}\u{10428}"
);
});
it("leaves a first character without case unchanged", () => {
expect(capitalizeFirstLetter("😀 smile")).toBe("😀 smile");
expect(capitalizeFirstLetter("1st floor")).toBe("1st floor");
});
});
+12
View File
@@ -120,6 +120,18 @@ describe("formatNumber", () => {
);
});
it("Formats a numeric string with more than 100 decimal places", () => {
const num = `1.${"0".repeat(120)}`;
assert.strictEqual(formatNumber(num), `1.${"0".repeat(100)}`);
});
it("Limits fraction digits to 100 for a string numeric value with more decimal places", () => {
assert.deepEqual(getDefaultFormatOptions(`1.${"0".repeat(101)}`), {
minimumFractionDigits: 100,
maximumFractionDigits: 100,
});
});
it("Sets only the maximumFractionDigits format option when none are provided for a number value", () => {
assert.deepEqual(getDefaultFormatOptions(1234.5), {
maximumFractionDigits: 2,
+44
View File
@@ -21,6 +21,12 @@ describe("isIPAddress (IPv4)", () => {
expect(isIPAddress("fe80::1")).toBe(false);
expect(isIPAddress("")).toBe(false);
});
it("rejects octets with leading zeros", () => {
expect(isIPAddress("010.1.1.1")).toBe(false);
expect(isIPAddress("1.1.1.01")).toBe(false);
expect(isIPAddress("192.168.001.1")).toBe(false);
expect(isIPAddress("00.0.0.0")).toBe(false);
});
});
describe("isIPv6Address", () => {
@@ -29,6 +35,19 @@ describe("isIPv6Address", () => {
expect(isIPv6Address("::1")).toBe(true);
expect(isIPv6Address("1050:0000:0000:0000:0005:0600:300c:326b")).toBe(true);
expect(isIPv6Address("::ffff:192.168.1.1")).toBe(true);
expect(isIPv6Address("::")).toBe(true);
expect(isIPv6Address("1:2:3:4:5:6:7::")).toBe(true);
});
it("accepts IPv6 addresses ending in dotted IPv4", () => {
expect(isIPv6Address("1:2:3:4:5:6:192.168.1.1")).toBe(true);
expect(isIPv6Address("1:2:3:4:5::192.168.1.1")).toBe(true);
expect(isIPv6Address("1::2:3:4:192.168.1.1")).toBe(true);
expect(isIPv6Address("64:ff9b::192.0.2.33")).toBe(true);
});
it("rejects IPv6 addresses with too many groups before dotted IPv4", () => {
expect(isIPv6Address("1:2:3:4:5:6:7:192.168.1.1")).toBe(false);
expect(isIPv6Address("1:2:3:4:5:6::192.168.1.1")).toBe(false);
expect(isIPv6Address("::ffff:010.1.1.1")).toBe(false);
});
it("rejects invalid IPv6 addresses", () => {
expect(isIPv6Address("192.168.1.10")).toBe(false);
@@ -112,4 +131,29 @@ describe("IP_ADDRESS_OR_NETWORK_PATTERN", () => {
false
);
});
it("rejects IPv4 octets with leading zeros", () => {
expect(matchesPattern(IP_ADDRESS_OR_NETWORK_PATTERN, "010.1.1.1")).toBe(
false
);
expect(matchesPattern(IP_ADDRESS_OR_NETWORK_PATTERN, "010.1.1.0/24")).toBe(
false
);
});
it("accepts IPv6 addresses and networks ending in dotted IPv4", () => {
expect(
matchesPattern(IP_ADDRESS_OR_NETWORK_PATTERN, "1:2:3:4:5:6:192.168.1.1")
).toBe(true);
expect(
matchesPattern(
IP_ADDRESS_OR_NETWORK_PATTERN,
"1:2:3:4:5::192.168.1.0/120"
)
).toBe(true);
});
it("compiles with the v flag used for the HTML pattern attribute", () => {
expect(
() => new RegExp(`^(?:${IP_ADDRESS_OR_NETWORK_PATTERN})$`, "v")
).not.toThrow();
expect(() => new RegExp(`^(?:${IP_ADDRESS_PATTERN})$`, "v")).not.toThrow();
});
});
+7
View File
@@ -34,4 +34,11 @@ describe("slugify", () => {
assert.strictEqual(slugify("abc def", "-"), "abc-def");
assert.strictEqual(slugify("abc-def", "-"), "abc-def");
});
it("transliterates Cyrillic characters", () => {
assert.strictEqual(slugify("Хлеб"), "khleb");
assert.strictEqual(slugify("кухня"), "kukhnia");
assert.strictEqual(slugify("Жёлтая чашка"), "zheltaia_chashka");
assert.strictEqual(slugify("щи"), "shchi");
});
});
+12
View File
@@ -122,6 +122,18 @@ describe.each(panelQueryParams)("$type query params", (panel) => {
);
});
it("ignores date params that can't be parsed", () => {
const params = decodeQueryParams(
"?entity_id=light.kitchen&start_date=yesterday&end_date=2026-06-05T11:00:00.000Z",
historyLogbookQueryParamConfig
);
expect(params).toEqual({
entity_id: ["light.kitchen"],
end_date: new Date("2026-06-05T11:00:00.000Z"),
});
});
it("creates typed URLs", () => {
expect(
createHistoryLogbookUrl(
+15
View File
@@ -149,5 +149,20 @@ describe("debounce", () => {
vi.advanceTimersByTime(500);
expect(fn).toHaveBeenCalledTimes(1);
});
it("calls immediately on the first call after cancel with immediate", () => {
const fn = vi.fn();
const debounced = debounce(fn, 500, true);
debounced("a");
debounced.cancel();
debounced("b");
expect(fn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenLastCalledWith("b");
vi.advanceTimersByTime(500);
expect(fn).toHaveBeenCalledTimes(2);
});
});
});
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { groupBy } from "../../../src/common/util/group-by";
describe("groupBy", () => {
it("groups items by the selected key in insertion order", () => {
const result = groupBy(
[
{ name: "a", type: "x" },
{ name: "b", type: "y" },
{ name: "c", type: "x" },
],
(item) => item.type
);
expect(Object.keys(result)).toEqual(["x", "y"]);
expect(result.x.map((item) => item.name)).toEqual(["a", "c"]);
expect(result.y.map((item) => item.name)).toEqual(["b"]);
});
it("returns an empty object for an empty list", () => {
expect(groupBy([], (item) => String(item))).toEqual({});
});
it.each(["constructor", "toString", "hasOwnProperty", "__proto__"])(
"groups items under the key %s",
(key) => {
const result = groupBy(["first", "second"], () => key);
expect(Object.keys(result)).toEqual([key]);
expect(result[key]).toEqual(["first", "second"]);
expect(Object.getPrototypeOf(result)).toBe(Object.prototype);
}
);
});
@@ -24,6 +24,14 @@ describe("parseAnimationDuration", () => {
assert.equal(parseAnimationDuration(" 3s "), 3000);
});
it("Parses units regardless of case", () => {
assert.equal(parseAnimationDuration("0.5S"), 500);
assert.equal(parseAnimationDuration("3S"), 3000);
assert.equal(parseAnimationDuration("300MS"), 300);
assert.equal(parseAnimationDuration("300Ms"), 300);
assert.equal(parseAnimationDuration("300mS"), 300);
});
it("Handles number without unit as milliseconds", () => {
assert.equal(parseAnimationDuration("300"), 300);
});
+110
View File
@@ -0,0 +1,110 @@
import {
STATE_NOT_RUNNING,
STATE_RUNNING,
STATE_STARTING,
} from "home-assistant-js-websocket";
import { describe, expect, it } from "vitest";
import type { BootstrapProgress } from "../../src/data/bootstrap_integrations";
import {
computeStartupProgress,
startupTransition,
} from "../../src/data/bootstrap_integrations";
const progress = (
overrides: Partial<BootstrapProgress> = {}
): BootstrapProgress => ({
phase: "setup",
elapsed: 12.4,
integrations: { total: 40, done: 10, failed: [] },
active: {},
...overrides,
});
describe("computeStartupProgress", () => {
it("is indeterminate before the total is known", () => {
const view = computeStartupProgress(undefined, STATE_NOT_RUNNING);
expect(view.phase).toBe("preparing");
expect(view.percent).toBeUndefined();
expect(view.total).toBeNull();
expect(view.finished).toBe(false);
});
it("lists concurrent setups by elapsed time and counts finished integrations", () => {
const view = computeStartupProgress(
progress({ active: { hue: 2.1, zwave_js: 8.5, met: 0.4 } }),
STATE_NOT_RUNNING
);
expect(view.percent).toBe(25);
expect(view.elapsed).toBe(12.4);
expect(view.active.map(([domain]) => domain)).toEqual([
"zwave_js",
"hue",
"met",
]);
});
it("is indeterminate during wrap up even when all integrations are done", () => {
const view = computeStartupProgress(
progress({
phase: "wrap_up",
integrations: { total: 40, done: 40, failed: [] },
}),
STATE_NOT_RUNNING
);
expect(view.percent).toBeUndefined();
expect(view.elapsed).toBe(12.4);
expect(view.done).toBe(40);
expect(view.finished).toBe(false);
});
it("reports failed integrations separately from completion", () => {
const view = computeStartupProgress(
progress({
phase: "wrap_up",
integrations: { total: 3, done: 3, failed: ["auth", "broken"] },
}),
STATE_NOT_RUNNING
);
expect(view.done).toBe(3);
expect(view.failed).toEqual(["auth", "broken"]);
});
it("follows the core state when the progress message lags behind", () => {
const view = computeStartupProgress(
progress({ phase: "wrap_up" }),
STATE_STARTING
);
expect(view.phase).toBe("starting");
expect(view.percent).toBeUndefined();
expect(view.finished).toBe(false);
});
it("is only finished in the running state", () => {
expect(
computeStartupProgress(progress({ phase: "running" }), STATE_STARTING)
.finished
).toBe(false);
const view = computeStartupProgress(
progress({ phase: "starting" }),
STATE_RUNNING
);
expect(view.phase).toBe("running");
expect(view.finished).toBe(true);
});
});
describe("startupTransition", () => {
it.each([
[undefined, STATE_NOT_RUNNING, "show"],
[undefined, STATE_STARTING, "show"],
[undefined, STATE_RUNNING, "none"],
[STATE_NOT_RUNNING, STATE_STARTING, "none"],
[STATE_NOT_RUNNING, STATE_RUNNING, "finish"],
[STATE_STARTING, STATE_RUNNING, "finish"],
// Reconnected to a restarted core.
[STATE_RUNNING, STATE_NOT_RUNNING, "show"],
[STATE_RUNNING, STATE_RUNNING, "none"],
])("%s -> %s is %s", (oldState, newState, expected) => {
expect(startupTransition(oldState, newState)).toBe(expected);
});
});
+83
View File
@@ -0,0 +1,83 @@
import { describe, expect, it } from "vitest";
import type { BatterySourceTypeEnergyPreference } from "../../src/data/energy";
import { getBatteryCapacity } from "../../src/data/energy-battery";
import { createMockEntityState } from "../fixtures/hass";
const battery: BatterySourceTypeEnergyPreference = {
type: "battery",
stat_energy_from: "sensor.discharged",
stat_energy_to: "sensor.charged",
};
describe("getBatteryCapacity", () => {
it("preserves manual capacity and optional capacity", () => {
expect(getBatteryCapacity({ ...battery, capacity: 5.76 }, {})).toBe(5.76);
expect(getBatteryCapacity(battery, {})).toBeUndefined();
});
it.each([
["Wh", "5760"],
["kWh", "5.76"],
["MWh", "0.00576"],
])("converts %s to kWh", (unit, state) => {
expect(
getBatteryCapacity(
{ ...battery, entity_capacity: "sensor.capacity" },
{
"sensor.capacity": createMockEntityState("sensor.capacity", state, {
unit_of_measurement: unit,
}),
}
)
).toBeCloseTo(5.76);
});
it.each([
["unavailable", "kWh"],
["unknown", "kWh"],
["", "kWh"],
[" ", "kWh"],
["0", "kWh"],
["-1", "kWh"],
["Infinity", "kWh"],
["NaN", "kWh"],
["5.76 kWh", "kWh"],
["5.76", "W"],
["5.76", undefined],
])("ignores invalid capacity %s %s", (state, unit) => {
expect(
getBatteryCapacity(
{ ...battery, entity_capacity: "sensor.capacity" },
{
"sensor.capacity": createMockEntityState("sensor.capacity", state, {
unit_of_measurement: unit,
}),
}
)
).toBeUndefined();
});
it("handles a missing sensor", () => {
expect(
getBatteryCapacity({ ...battery, entity_capacity: "sensor.capacity" }, {})
).toBeUndefined();
});
it("uses the current reading rather than a cached capacity", () => {
const source = { ...battery, entity_capacity: "sensor.capacity" };
expect(
getBatteryCapacity(source, {
"sensor.capacity": createMockEntityState("sensor.capacity", "5.76", {
unit_of_measurement: "kWh",
}),
})
).toBe(5.76);
expect(
getBatteryCapacity(source, {
"sensor.capacity": createMockEntityState("sensor.capacity", "4.8", {
unit_of_measurement: "kWh",
}),
})
).toBe(4.8);
});
});
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type {
AutomationConfig,
BlueprintAutomationConfig,
SidebarConfig,
Trigger,
} from "../../../../../src/data/automation";
import { AutomationTriggerController } from "../../../../../src/panels/config/automation/trigger/automation-trigger-controller";
@@ -193,3 +194,63 @@ describe("AutomationTriggerController with a blueprint automation", () => {
expect(context().blueprintStatus).toBe("failed");
});
});
describe("AutomationTriggerController.checkShowIndices", () => {
let host: TestHost;
let controller: AutomationTriggerController;
const showIndices = (): boolean => {
let value: AutomationTriggerContext | undefined;
const child = document.createElement("div");
host.appendChild(child);
child.dispatchEvent(
new ContextEvent(automationTriggerContext, child, (v) => {
value = v;
})
);
child.remove();
return value!.showIndices;
};
const sidebar = (config: unknown) => ({ config }) as unknown as SidebarConfig;
beforeEach(() => {
host = document.createElement("test-automation-trigger-host");
controller = new AutomationTriggerController(host, {
getConfig: () => ({ triggers: [], actions: [] }) as AutomationConfig,
canEdit: () => true,
commit: vi.fn(),
fetchBlueprintTriggers: vi.fn(),
});
});
afterEach(() => {
controller.hostDisconnected();
});
it.each([
["a trigger condition", { condition: "trigger", id: "a" }],
[
"a trigger condition used as action",
{ action: { condition: "trigger", id: "a" } },
],
])("shows the indices for %s", (_name, config) => {
controller.checkShowIndices(sidebar(config));
expect(showIndices()).toBe(true);
});
it.each([
["no sidebar", undefined],
["another condition", sidebar({ condition: "state" })],
["a service action", sidebar({ action: { action: "number.set_value" } })],
// What a condition row holds after an action was entered as YAML.
[
"a service action in a condition row",
sidebar({ action: "number.set_value", data: { value: 20 } }),
],
])("hides the indices for %s", (_name, sidebarConfig) => {
controller.checkShowIndices(sidebar({ condition: "trigger" }));
controller.checkShowIndices(sidebarConfig);
expect(showIndices()).toBe(false);
});
});
@@ -0,0 +1,153 @@
import { describe, expect, it } from "vitest";
import type { RecorderDatabaseUsage } from "../../../../src/data/recorder";
import {
UNKNOWN_ROW_ID,
databaseUsageRows,
groupSmallTables,
} from "../../../../src/panels/config/storage/storage-database-card";
describe("groupSmallTables", () => {
it("sums tables below the share into other bytes", () => {
expect(
groupSmallTables(
[
{ table: "states", bytes: 900 },
{ table: "statistics", bytes: 95 },
{ table: "schema_changes", bytes: 4 },
{ table: "sqlite_stat1", bytes: 1 },
{ table: "empty", bytes: 0 },
],
0.01
)
).toEqual({
tables: [
{ table: "states", bytes: 900 },
{ table: "statistics", bytes: 95 },
],
otherBytes: 5,
totalBytes: 1000,
});
});
it("keeps everything when no table is small", () => {
expect(groupSmallTables([{ table: "states", bytes: 10 }])).toEqual({
tables: [{ table: "states", bytes: 10 }],
otherBytes: 0,
totalBytes: 10,
});
});
});
const USAGE: RecorderDatabaseUsage = {
generated_at: "2026-11-12T10:00:00+00:00",
duration: 1.5,
total_bytes: 1000,
free_bytes: 100,
wal_bytes: 50,
tables: [{ table: "states", bytes: 900 }],
entities: [
{
entity_id: "sensor.energy",
states: 10,
states_bytes: 100,
attributes_bytes: 20,
},
{ entity_id: null, states: 1, states_bytes: 10, attributes_bytes: 0 },
],
statistics: [
{
statistic_id: "sensor.energy",
source: "recorder",
statistics: 5,
statistics_short_term: 7,
statistics_bytes: 50,
statistics_short_term_bytes: 70,
},
{
statistic_id: "sensor:external",
source: "sensor",
statistics: 3,
statistics_short_term: 0,
statistics_bytes: 30,
statistics_short_term_bytes: 0,
},
{
statistic_id: null,
source: null,
statistics: 1,
statistics_short_term: 0,
statistics_bytes: 10,
statistics_short_term_bytes: 0,
},
],
};
describe("databaseUsageRows", () => {
it("merges the statistics of an entity into its row", () => {
expect(databaseUsageRows(USAGE)).toEqual([
{
id: "sensor.energy",
states: 10,
statistics: 5,
statistics_short_term: 7,
bytes: 240,
},
{
id: UNKNOWN_ROW_ID,
states: 1,
statistics: 1,
statistics_short_term: 0,
bytes: 20,
},
{
id: "sensor:external",
states: 0,
statistics: 3,
statistics_short_term: 0,
bytes: 30,
},
]);
});
it("has no sizes when the database cannot report table sizes", () => {
expect(
databaseUsageRows({
...USAGE,
tables: null,
entities: [
{
entity_id: "sensor.energy",
states: 10,
states_bytes: null,
attributes_bytes: null,
},
],
statistics: [
{
statistic_id: "sensor:external",
source: "sensor",
statistics: 3,
statistics_short_term: 0,
statistics_bytes: null,
statistics_short_term_bytes: null,
},
],
})
).toEqual([
{
id: "sensor.energy",
states: 10,
statistics: 0,
statistics_short_term: 0,
bytes: null,
},
{
id: "sensor:external",
states: 0,
statistics: 3,
statistics_short_term: 0,
bytes: null,
},
]);
});
});
@@ -280,71 +280,4 @@ describe("MaintenanceViewStrategy.generate", () => {
},
]);
});
const createBatteryHass = () =>
createMockHass({
"sensor.car_target_charge": createMockEntityState(
"sensor.car_target_charge",
"80",
{ device_class: "battery" }
),
"sensor.remote_battery": createMockEntityState(
"sensor.remote_battery",
"80",
{ device_class: "battery" }
),
});
it("leaves hidden entities out of the view", async () => {
const view = await MaintenanceViewStrategy.generate(
{ type: "maintenance", hidden_entities: ["sensor.car_target_charge"] },
createBatteryHass()
);
const section = view.sections?.[0] as LovelaceSectionConfig;
expect(section.cards?.slice(1)).toEqual([
{
type: "tile",
entity: "sensor.remote_battery",
name: { type: "entity" },
},
]);
});
it("keeps hidden entities as hidden visibility wrappers while editing", async () => {
const view = await MaintenanceViewStrategy.generate(
{
type: "maintenance",
hidden_entities: ["sensor.car_target_charge"],
edit_visibility: true,
},
createBatteryHass()
);
const section = view.sections?.[0] as LovelaceSectionConfig;
expect(section.cards?.slice(1)).toEqual([
{
type: "entity-visibility",
entity: "sensor.car_target_charge",
hidden: true,
card: {
type: "tile",
entity: "sensor.car_target_charge",
name: { type: "entity" },
},
},
{
type: "entity-visibility",
entity: "sensor.remote_battery",
hidden: false,
card: {
type: "tile",
entity: "sensor.remote_battery",
name: { type: "entity" },
},
},
]);
});
});
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import { bytesToString } from "../../src/util/bytes-to-string";
describe("bytesToString", () => {
it("formats zero and missing values", () => {
expect(bytesToString(0)).toBe("0 Bytes");
expect(bytesToString()).toBe("0 Bytes");
});
it("formats values in the matching unit", () => {
expect(bytesToString(500)).toBe("500 Bytes");
expect(bytesToString(1024)).toBe("1 KB");
expect(bytesToString(1536)).toBe("1.5 KB");
expect(bytesToString(1024 ** 2)).toBe("1 MB");
expect(bytesToString(5 * 1024 ** 3)).toBe("5 GB");
});
it("respects the number of decimals", () => {
expect(bytesToString(1234567, 0)).toBe("1 MB");
expect(bytesToString(1234567, 3)).toBe("1.177 MB");
expect(bytesToString(1234567, -1)).toBe("1 MB");
});
it.each([
[1024 ** 5 - 1, 2, "1 PB"],
[1024 ** 2 - 1, 2, "1 MB"],
[1024 ** 3 - 1, 2, "1 GB"],
[1024 ** 4 - 1, 2, "1 TB"],
[1024 ** 2 - 100, 0, "1 MB"],
])(
"uses the next unit when %d bytes rounds up to it with %d decimals",
(value, decimals, expected) => {
expect(bytesToString(value, decimals)).toBe(expected);
}
);
it("formats exact unit boundaries in the larger unit", () => {
for (let i = 1; i < 9; i++) {
expect(bytesToString(1024 ** i)).toMatch(/^1 [KMGTPEZY]B$/);
}
});
});
+29
View File
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { csvSafeString } from "../../src/util/csv";
describe("csvSafeString", () => {
it("returns an empty string for empty or missing values", () => {
expect(csvSafeString(undefined)).toBe("");
expect(csvSafeString("")).toBe("");
});
it("returns plain values unchanged", () => {
expect(csvSafeString("light.kitchen")).toBe("light.kitchen");
});
it("quotes values containing a comma", () => {
expect(csvSafeString("on, off")).toBe('"on, off"');
});
it("quotes values containing a quote and escapes it", () => {
expect(csvSafeString('say "hi"')).toBe('"say ""hi"""');
});
it.each([
["line feed", "first\nsecond"],
["carriage return", "first\rsecond"],
["carriage return and line feed", "first\r\nsecond"],
])("quotes values containing a %s", (_name, value) => {
expect(csvSafeString(value)).toBe(`"${value}"`);
});
});