Compare commits

..
Author SHA1 Message Date
piitaya 27b0029c57 Merge remote-tracking branch 'origin/chart-range-selection' into statistic-dialog
# Conflicts:
#	src/components/chart/ha-chart-base.ts
#	src/components/chart/statistics-chart.ts
2026-11-16 17:38:36 +00:00
Paul Bottein ae6c80681a Set the mask flag where the mask is applied and skip hidden statistics when snapping 2026-11-16 18:29:38 +01:00
Paul Bottein 692338459d Only add empty chart mask areas once a mask was shown 2026-11-12 18:03:50 +01:00
Paul Bottein a8ee519fcf Keep drag to zoom when the chart select mode is point 2026-11-12 18:03:50 +01:00
Paul Bottein fdbab9046c Make chart selection opt-in with select-mode and cache the mask color 2026-11-12 18:03:50 +01:00
Paul Bottein 9f19a66a51 Clear stale chart masks after a data update 2026-11-12 18:03:50 +01:00
Paul Bottein 7b5d02bdba Move chart selection and highlight into ha-chart-base 2026-11-12 18:03:50 +01:00
Paul Bottein 3a3228bf79 Unify chart selection with a fade mask and a clear button in the gallery 2026-11-12 18:03:50 +01:00
Paul Bottein a299f5f9a7 Add range selection examples to the statistics chart gallery page 2026-11-12 18:03:50 +01:00
Paul Bottein 27902ef586 Keep range selection on release outside the chart and simplify the highlight 2026-11-12 18:03:50 +01:00
Paul Bottein 2d0ab5349b Add range selection and highlight to charts 2026-11-12 18:03:50 +01:00
copilot-swe-agent[bot] 68cf33d46d Merge remote-tracking branch 'origin/chart-range-selection' into statistic-dialog
# Conflicts:
#	src/components/chart/ha-chart-base.ts
2026-11-12 16:37:08 +00:00
Paul Bottein fb428ecab1 Only add empty chart mask areas once a mask was shown 2026-11-12 17:26:48 +01:00
Paul Bottein 43edb1886f Keep drag to zoom when the chart select mode is point 2026-11-06 14:32:46 +01:00
Paul Bottein 50437fd7c5 Make chart selection opt-in with select-mode and cache the mask color 2026-11-06 14:32:46 +01:00
Paul Bottein a74afc4e70 Clear stale chart masks after a data update 2026-11-06 14:32:46 +01:00
Paul Bottein 7175dc969c Move chart selection and highlight into ha-chart-base 2026-11-06 14:32:46 +01:00
Paul Bottein a2cdb48a59 Unify chart selection with a fade mask and a clear button in the gallery 2026-11-06 14:32:46 +01:00
Paul Bottein 7c38ade9ed Add range selection examples to the statistics chart gallery page 2026-11-06 14:32:46 +01:00
Paul Bottein 983ff152e5 Keep range selection on release outside the chart and simplify the highlight 2026-11-06 14:32:46 +01:00
Paul Bottein b6d761b03b Add range selection and highlight to charts 2026-11-06 14:32:46 +01:00
Paul Bottein f9ad5ed150 Merge branch 'chart-range-selection' into statistic-dialog 2026-11-06 13:56:05 +01:00
Paul Bottein 27a968d777 Keep drag to zoom when the chart select mode is point 2026-11-06 13:55:17 +01:00
Paul Bottein 3be0294867 Use select-mode and chart-select in the statistic dialog 2026-11-06 13:38:04 +01:00
Paul Bottein d96dbfaae1 Merge remote-tracking branch 'origin/chart-range-selection' into statistic-dialog
# Conflicts:
#	src/components/chart/ha-chart-base.ts
2026-11-06 13:38:04 +01:00
Paul Bottein ff3b608653 Make chart selection opt-in with select-mode and cache the mask color 2026-11-06 13:37:07 +01:00
copilot-swe-agent[bot]andpiitaya 96d15065a9 Merge remote-tracking branch 'origin/chart-range-selection' into statistic-dialog
# Conflicts:
#	gallery/src/pages/components/state-history-charts.ts
#	gallery/src/pages/components/statistics-chart.ts
#	src/components/chart/ha-chart-base.ts
#	src/components/chart/statistics-chart.ts

Co-authored-by: piitaya <[email protected]>
2026-11-05 14:06:36 +00:00
Paul Bottein ca456105e5 Clear stale chart masks after a data update 2026-11-05 14:57:44 +01:00
Paul Bottein 9f12b54a14 Move chart selection and highlight into ha-chart-base 2026-11-05 14:57:44 +01:00
Paul Bottein cf25121dda Unify chart selection with a fade mask and a clear button in the gallery 2026-11-05 14:57:44 +01:00
Paul Bottein 71f53ae3e2 Add range selection examples to the statistics chart gallery page 2026-11-05 14:57:44 +01:00
Paul Bottein 8843596e42 Keep range selection on release outside the chart and simplify the highlight 2026-11-05 14:57:44 +01:00
Paul Bottein d06ec13af6 Add range selection and highlight to charts 2026-11-05 14:57:44 +01:00
Paul Bottein 1c428c1831 Merge branch 'chart-range-selection' into statistic-dialog
# Conflicts:
#	src/panels/config/tools/statistics/dialog-statistics-adjust-sum.ts
#	src/translations/en.json
2026-11-05 10:01:26 +01:00
Paul Bottein c20a90cd81 Merge branch 'gallery-statistics-chart' into chart-range-selection 2026-11-05 10:00:24 +01:00
Paul Bottein f64a602bc8 Add history and statistics chart pages to the gallery 2026-11-05 09:59:56 +01:00
Paul Bottein 3354b5ffec Keep range selection on release outside the chart and simplify the highlight 2026-11-05 09:38:09 +01:00
Paul Bottein fce263e6ab Add range selection and highlight to charts 2026-11-05 09:38:09 +01:00
copilot-swe-agent[bot] 6317dad51b Merge remote-tracking branch 'origin/chart-range-selection' into statistic-dialog
Co-authored-by: piitaya <[email protected]>
2026-11-02 22:53:47 +00:00
Paul Bottein c350d46d44 Keep range selection on release outside the chart and simplify the highlight 2026-10-29 17:12:46 +01:00
Paul Bottein e5a43b48c2 Add range selection and highlight to charts 2026-10-29 17:12:46 +01:00
Paul Bottein 73a88453db Pass no highlight when nothing is selected 2026-10-29 17:05:42 +01:00
Paul Bottein fba2451e61 Merge the chart range selection fixes into the statistic dialog 2026-10-29 17:05:37 +01:00
Paul Bottein c33a452976 Keep range selection on release outside the chart and simplify the highlight 2026-10-29 17:05:26 +01:00
Paul Bottein ec0533f8c5 Merge the chart range selection into the statistic dialog 2026-10-29 16:45:50 +01:00
Paul Bottein b1b9c41bc1 Add range selection and highlight to charts 2026-10-29 16:45:13 +01:00
Paul Bottein 685e7d51d2 Merge the zoom slider mode base into the statistic dialog 2026-10-29 16:39:23 +01:00
Paul Bottein 315afd8ac2 Replace hide-zoom-controls with a zoom slider mode on charts 2026-10-29 16:30:40 +01:00
Paul Bottein bc9d0b5227 Fix stale adjustments, zoom and outlier selection in the statistic dialog 2026-10-29 16:26:18 +01:00
Paul Bottein 99c85c3407 Show the last 7 days by default in the statistic dialog 2026-10-29 16:23:32 +01:00
Paul Bottein e04e639100 Always show the zoom slider and keep outliers and selection after adjusting 2026-10-29 16:10:29 +01:00
Paul Bottein ca7b91af35 Show the graph loader only on slow loads 2026-10-29 15:49:51 +01:00
Paul Bottein ffd26ffc1a Add sum outliers, keep the graph while loading and fix review feedback 2026-10-29 15:48:10 +01:00
Paul Bottein bd4ff71d29 Open statistics in a dialog to view and correct their data 2026-10-29 14:57:51 +01:00
149 changed files with 4976 additions and 9824 deletions

No files matched your search

+4 -4
View File
@@ -18,7 +18,7 @@ workflows:
- 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9'
'.github/workflows/codeql-analysis.yaml':
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
- 'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066'
- 'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
'.github/workflows/copilot-setup-steps.yml':
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
@@ -151,9 +151,9 @@ dependencies:
commit: 'sha1-89ae32b08ed1a541efecbab17912962a5e38981c'
owner_id: 7513068
repo_id: 113918130
'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066':
ref: 'v4.39.3'
commit: 'sha1-33d7b85da1a04171e211befe2c739303b9a4c066'
'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370':
ref: 'v4.39.1'
commit: 'sha1-9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
owner_id: 9919
repo_id: 259445878
'home-assistant/actions@86d4564712fa02543c808e3a693dd04f9d3f8361':
+2 -2
View File
@@ -32,12 +32,12 @@ jobs:
persist-credentials: false
- name: Initialize CodeQL
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
with:
languages: javascript-typescript
build-mode: none
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
with:
category: "/language:javascript-typescript"
+1 -1
View File
@@ -1 +1 @@
24.22.3
24.22.2
+1 -3
View File
@@ -50,9 +50,7 @@ const convertToJSON = async (
const encodedData = localeData.match(
/JSON\.parse\((?<data>"(?:[^"\\]|\\.)*")\)/
)?.groups?.data;
localeData =
localeData.match(/\}\)\((?<data>\{.*\})\)\s*;?\s*$/s)?.groups?.data ??
firstBlock.match(dataRegex)?.groups?.data;
localeData = firstBlock.match(dataRegex)?.groups?.data;
if (!localeData && !encodedData) {
throw Error(`Failed to extract data for language ${lang} from ${pkg}`);
}
+2 -2
View File
@@ -28,7 +28,7 @@ class HcLaunchScreen extends LitElement {
:host {
display: block;
height: 100vh;
background-color: var(--primary-background-color, #f2f4f9);
background-color: #f2f4f9;
font-size: var(--ha-font-size-2xl);
}
.container {
@@ -44,7 +44,7 @@ class HcLaunchScreen extends LitElement {
object-fit: cover;
}
.status {
color: var(--primary-text-color, #1d2126);
color: #1d2126;
}
`;
}
+8 -24
View File
@@ -8,7 +8,7 @@ import type {
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
export const mockEnergy = (hass: MockHomeAssistant) => {
const prefs: EnergyPreferences = {
hass.mockWS("energy/get_prefs", (): EnergyPreferences => ({
energy_sources: [
{
type: "grid",
@@ -21,6 +21,7 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
entity_energy_price_export: null,
number_energy_price_export: null,
stat_rate: "sensor.power_grid",
cost_adjustment_day: 0,
},
{
type: "grid",
@@ -33,6 +34,7 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
entity_energy_price_export: null,
number_energy_price_export: null,
stat_rate: "sensor.power_grid_return",
cost_adjustment_day: 0,
},
{
type: "solar",
@@ -46,23 +48,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
stat_energy_to: "sensor.battery_input",
stat_rate: "sensor.power_battery",
},
{
type: "battery",
name: "Powerwall",
stat_energy_from_grid: "sensor.powerwall_from_grid",
stat_energy_from_solar: "sensor.powerwall_from_solar",
stat_energy_to_home: "sensor.powerwall_to_home",
stat_energy_to_grid: "sensor.powerwall_to_grid",
stat_rate: "sensor.powerwall_power",
power_config: {
stat_rate_from_grid: "sensor.powerwall_power_from_grid",
stat_rate_from_solar: "sensor.powerwall_power_from_solar",
stat_rate_to_home: "sensor.powerwall_power_to_home",
stat_rate_to_grid: "sensor.powerwall_power_to_grid",
},
stat_soc: "sensor.powerwall_battery_level",
capacity: 13.5,
},
{
type: "gas",
stat_energy_from: "sensor.energy_gas",
@@ -120,17 +105,16 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
stat_consumption: "sensor.gas_heat_pump",
},
],
};
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
}));
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
solar_forecast_domains: [],
}));
hass.mockWS("energy/validate", () => ({
energy_sources: prefs.energy_sources.map(() => []),
device_consumption: prefs.device_consumption.map(() => []),
device_consumption_water: prefs.device_consumption_water.map(() => []),
device_consumption_gas: prefs.device_consumption_gas.map(() => []),
energy_sources: Array.from({ length: 6 }, () => []),
device_consumption: Array.from({ length: 6 }, () => []),
device_consumption_water: Array.from({ length: 2 }, () => []),
device_consumption_gas: Array.from({ length: 2 }, () => []),
}));
hass.mockWS(
"energy/fossil_energy_consumption",
-75
View File
@@ -1,30 +1,3 @@
// Live power of the battery measured per direction, in W
const powerwallPower = {
from_grid: 50,
from_solar: 150,
to_home: 0,
to_grid: 0,
};
const powerEntity = (entityId: string, power: number) => ({
entity_id: entityId,
state: String(power),
attributes: {
state_class: "measurement",
unit_of_measurement: "W",
},
});
const powerwallEnergyEntity = (entityId: string, friendlyName: string) => ({
entity_id: entityId,
state: "2",
attributes: {
last_reset: "1970-01-01T00:00:00:00+00",
friendly_name: friendlyName,
unit_of_measurement: "kWh",
},
});
export const energyEntities = () =>
Object.values({
"sensor.grid_fossil_fuel_percentage": {
@@ -61,31 +34,6 @@ export const energyEntities = () =>
unit_of_measurement: "kWh",
},
},
"sensor.powerwall_from_grid": powerwallEnergyEntity(
"sensor.powerwall_from_grid",
"Powerwall charged from grid"
),
"sensor.powerwall_from_solar": powerwallEnergyEntity(
"sensor.powerwall_from_solar",
"Powerwall charged from solar"
),
"sensor.powerwall_to_home": powerwallEnergyEntity(
"sensor.powerwall_to_home",
"Powerwall discharged to home"
),
"sensor.powerwall_to_grid": powerwallEnergyEntity(
"sensor.powerwall_to_grid",
"Powerwall discharged to grid"
),
"sensor.powerwall_battery_level": {
entity_id: "sensor.powerwall_battery_level",
state: "62",
attributes: {
device_class: "battery",
friendly_name: "Powerwall battery level",
unit_of_measurement: "%",
},
},
"sensor.energy_consumption_tarif_1": {
entity_id: "sensor.energy_consumption_tarif_1",
state: "88.6",
@@ -186,29 +134,6 @@ export const energyEntities = () =>
unit_of_measurement: "W",
},
},
"sensor.powerwall_power_from_grid": powerEntity(
"sensor.powerwall_power_from_grid",
powerwallPower.from_grid
),
"sensor.powerwall_power_from_solar": powerEntity(
"sensor.powerwall_power_from_solar",
powerwallPower.from_solar
),
"sensor.powerwall_power_to_home": powerEntity(
"sensor.powerwall_power_to_home",
powerwallPower.to_home
),
"sensor.powerwall_power_to_grid": powerEntity(
"sensor.powerwall_power_to_grid",
powerwallPower.to_grid
),
"sensor.powerwall_power": powerEntity(
"sensor.powerwall_power",
powerwallPower.to_home +
powerwallPower.to_grid -
powerwallPower.from_grid -
powerwallPower.from_solar
),
"sensor.energy_gas_cost": {
entity_id: "sensor.energy_gas_cost",
state: "2",
+6 -33
View File
@@ -351,26 +351,6 @@ const statisticsFunctions: Record<
const derivedCosts: Record<string, { source: string; price: number }> = {
"sensor.energy_water_cost": { source: "sensor.energy_water", price: 0.004 },
};
// Battery directions as a share of the meter the energy also passes, so they
// never exceed it
const derivedBatteryFlows: Record<string, { source: string; share: number }> = {
"sensor.powerwall_from_grid": {
source: "sensor.energy_consumption_tarif_1",
share: 0.4,
},
"sensor.powerwall_from_solar": {
source: "sensor.solar_production",
share: 0.3,
},
"sensor.powerwall_to_home": {
source: "sensor.energy_consumption_tarif_2",
share: 0.5,
},
"sensor.powerwall_to_grid": {
source: "sensor.energy_production_tarif_2",
share: 0.3,
},
};
export const mockRecorder = (mockHass: MockHomeAssistant) => {
mockHass.mockWS(
@@ -395,22 +375,15 @@ export const mockRecorder = (mockHass: MockHomeAssistant) => {
return cache[id];
};
const scaleStats = (source: string, factor: number) => {
let sum = 0;
return getStats(source).map((statistic) => {
const change = statistic.change! * factor;
sum += change;
return { ...statistic, change, state: sum, sum };
});
};
statistic_ids.forEach((id: string) => {
if (id in derivedCosts) {
const { source, price } = derivedCosts[id];
statistics[id] = scaleStats(source, price);
} else if (id in derivedBatteryFlows) {
const { source, share } = derivedBatteryFlows[id];
statistics[id] = scaleStats(source, share);
let cost = 0;
statistics[id] = getStats(source).map((statistic) => {
const change = statistic.change! * price;
cost += change;
return { ...statistic, change, state: cost, sum: cost };
});
} else if (id in statisticsFunctions) {
statistics[id] = getStats(id);
} else {
+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);
}
`;
}
-133
View File
@@ -187,139 +187,6 @@ const ENTITIES = [
current_tilt_position: 70,
},
},
{
entity_id: "cover.shade",
state: "open",
attributes: {
friendly_name: "Shade",
device_class: "shade",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 60,
},
},
{
entity_id: "cover.shutter",
state: "open",
attributes: {
friendly_name: "Shutter",
device_class: "shutter",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 40,
},
},
{
entity_id: "cover.awning",
state: "open",
attributes: {
friendly_name: "Awning",
device_class: "awning",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 70,
},
},
{
entity_id: "cover.curtain",
state: "open",
attributes: {
friendly_name: "Curtain",
device_class: "curtain",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 50,
},
},
{
entity_id: "cover.door",
state: "open",
attributes: {
friendly_name: "Door",
device_class: "door",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 30,
},
},
{
entity_id: "cover.gate",
state: "open",
attributes: {
friendly_name: "Gate",
device_class: "gate",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 30,
},
},
{
entity_id: "cover.window",
state: "open",
attributes: {
friendly_name: "Window",
device_class: "window",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
current_position: 50,
},
},
{
entity_id: "cover.garage",
state: "closed",
attributes: {
friendly_name: "Garage door",
device_class: "garage",
supported_features: CoverEntityFeature.OPEN + CoverEntityFeature.CLOSE,
},
},
{
entity_id: "cover.unknown",
state: "unknown",
attributes: {
friendly_name: "Unknown position",
device_class: "shade",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
},
},
{
entity_id: "cover.unavailable",
state: "unavailable",
attributes: {
friendly_name: "Unavailable",
device_class: "shutter",
supported_features:
CoverEntityFeature.OPEN +
CoverEntityFeature.STOP +
CoverEntityFeature.CLOSE +
CoverEntityFeature.SET_POSITION,
},
},
];
@customElement("demo-more-info-cover")
+24 -24
View File
@@ -40,7 +40,7 @@
"license": "Apache-2.0",
"type": "module",
"dependencies": {
"@babel/runtime": "8.1.2",
"@babel/runtime": "8.1.0",
"@braintree/sanitize-url": "7.1.2",
"@codemirror/autocomplete": "6.20.4",
"@codemirror/commands": "6.11.1",
@@ -48,21 +48,21 @@
"@codemirror/lang-python": "6.2.1",
"@codemirror/lang-yaml": "6.1.3",
"@codemirror/language": "6.13.1",
"@codemirror/lint": "6.9.8",
"@codemirror/lint": "6.9.7",
"@codemirror/search": "6.7.2",
"@codemirror/state": "6.7.6",
"@codemirror/view": "6.43.15",
"@date-fns/tz": "1.5.0",
"@egjs/hammerjs": "2.0.17",
"@formatjs/intl-datetimeformat": "8.0.3",
"@formatjs/intl-displaynames": "8.0.3",
"@formatjs/intl-displaynames": "8.0.2",
"@formatjs/intl-durationformat": "0.12.4",
"@formatjs/intl-getcanonicallocales": "3.3.1",
"@formatjs/intl-listformat": "9.0.3",
"@formatjs/intl-listformat": "9.0.2",
"@formatjs/intl-locale": "5.4.3",
"@formatjs/intl-numberformat": "10.0.4",
"@formatjs/intl-pluralrules": "7.0.4",
"@formatjs/intl-relativetimeformat": "13.0.3",
"@formatjs/intl-numberformat": "10.0.3",
"@formatjs/intl-pluralrules": "7.0.3",
"@formatjs/intl-relativetimeformat": "13.0.2",
"@home-assistant/webawesome": "3.14.0-ha.2",
"@lezer/common": "1.5.5",
"@lezer/highlight": "1.2.5",
@@ -77,9 +77,9 @@
"@mdi/svg": "7.4.47",
"@replit/codemirror-indentation-markers": "6.5.3",
"@swc/helpers": "0.5.24",
"@tsparticles/engine": "4.5.4",
"@tsparticles/preset-links": "4.5.4",
"@versatiles/style": "9.1.0",
"@tsparticles/engine": "4.5.3",
"@tsparticles/preset-links": "4.5.3",
"@versatiles/style": "9.0.0",
"@vibrant/color": "4.0.4",
"@vvo/tzdb": "6.204.0",
"@webcomponents/scoped-custom-element-registry": "0.0.10",
@@ -97,7 +97,7 @@
"echarts": "6.1.0",
"echarts-extension-chart2music": "0.1.1",
"element-internals-polyfill": "3.0.2",
"fullcalendar": "7.1.5",
"fullcalendar": "7.1.4",
"fuse.js": "7.5.0",
"hls.js": "1.7.4",
"home-assistant-js-websocket": "9.8.1",
@@ -108,8 +108,8 @@
"leaflet.markercluster": "1.5.3",
"lit": "3.3.3",
"lit-html": "3.3.3",
"maplibre-gl": "6.18.0",
"marked": "18.2.0",
"maplibre-gl": "6.17.0",
"marked": "18.1.3",
"memoize-one": "6.0.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
@@ -136,12 +136,12 @@
},
"devDependencies": {
"@ampproject/remapping": "2.3.0",
"@babel/core": "8.1.2",
"@babel/core": "8.1.0",
"@babel/helper-compilation-targets": "8.0.7",
"@babel/helper-define-polyfill-provider": "1.0.0",
"@babel/plugin-transform-class-properties": "8.0.1",
"@babel/plugin-transform-private-methods": "8.0.1",
"@babel/plugin-transform-runtime": "8.1.2",
"@babel/plugin-transform-runtime": "8.0.6",
"@babel/preset-env": "8.0.7",
"@bundle-stats/plugin-webpack-filter": "4.23.1",
"@eslint/js": "10.0.1",
@@ -153,7 +153,7 @@
"@octokit/rest": "22.0.1",
"@playwright/test": "1.65.0",
"@rsdoctor/rspack-plugin": "1.6.5",
"@rspack/core": "2.3.2",
"@rspack/core": "2.3.1",
"@rspack/dev-server": "2.2.2",
"@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "7.0.1",
@@ -188,14 +188,14 @@
"fancy-log": "2.0.0",
"fs-extra": "11.4.1",
"generate-license-file": "4.2.5",
"glob": "14.0.6",
"glob": "14.0.4",
"globals": "17.14.0",
"gulp": "5.0.1",
"gulp-json-transform": "0.5.0",
"gulp-rename": "2.1.0",
"html-minifier-terser": "7.2.0",
"husky": "9.1.7",
"jsdom": "31.0.1",
"jsdom": "31.0.0",
"jszip": "3.10.2",
"license-checker-rseidelsohn": "5.0.1",
"lightningcss": "1.33.0",
@@ -206,24 +206,24 @@
"map-stream": "0.0.7",
"minify-literals": "2.2.0",
"pinst": "3.0.0",
"prettier": "3.10.1",
"prettier": "3.9.10",
"rspack-manifest-plugin": "5.2.2",
"serve": "14.2.7",
"sinon": "22.1.0",
"tar": "7.5.23",
"tar": "7.5.22",
"terser-webpack-plugin": "5.6.1",
"ts-lit-plugin": "2.0.2",
"typescript": "6.0.3",
"typescript-eslint": "8.72.2",
"vite": "8.3.8",
"typescript-eslint": "8.72.1",
"vite": "8.3.7",
"vite-tsconfig-paths": "6.1.1",
"vitest": "5.1.0",
"webpack-stats-plugin": "1.1.3",
"webpackbar": "7.0.0",
"workbox-build": "7.4.1"
},
"packageManager": "pnpm@12.20.0",
"packageManager": "pnpm@12.18.0",
"volta": {
"node": "24.22.3"
"node": "24.22.2"
}
}
+1 -1
View File
@@ -53,7 +53,7 @@
},
"devDependencies": {
"@custom-elements-manifest/analyzer": "0.11.0",
"@rslib/core": "1.0.7",
"@rslib/core": "1.0.6",
"lit": "3.3.3",
"typescript": "6.0.3"
}
+910 -906
View File
File diff suppressed because it is too large. Load diff
@@ -89,19 +89,10 @@ export class LegendFitController {
private _fit() {
const list = this._element;
if (!list) {
const rowWidth = list?.getBoundingClientRect().width;
if (!list || !rowWidth) {
return;
}
const style = getComputedStyle(list);
const rowWidth = parseFloat(style.width);
// Bounding rects include transforms, such as a dialog scaling in, which
// never resize the list, so measure in layout pixels
const scale = list.getBoundingClientRect().width / rowWidth;
if (!rowWidth || !scale) {
return;
}
const layoutWidth = (element: Element) =>
element.getBoundingClientRect().width / scale;
const children = Array.from(list.children);
const more = children.find((child) =>
child.classList.contains("legend-more")
@@ -116,7 +107,9 @@ export class LegendFitController {
}
this._more = more;
}
const widths = children.filter((child) => child !== more).map(layoutWidth);
const widths = children
.filter((child) => child !== more)
.map((child) => child.getBoundingClientRect().width);
// Values resize the items on every state update. Fitting each item at its
// widest since the last resize keeps the more button from flickering.
if (rowWidth !== this._rowWidth || widths.length !== this._widths.length) {
@@ -129,9 +122,9 @@ export class LegendFitController {
}
const fit = fitInRows(
this._widths,
more ? layoutWidth(more) : 0,
more?.getBoundingClientRect().width ?? 0,
rowWidth,
parseFloat(style.columnGap) || 0,
parseFloat(getComputedStyle(list).columnGap) || 0,
rowWidth < NARROW_WIDTH ? NARROW_MAX_ROWS : MAX_ROWS
);
if (fit !== this.fit) {
-1
View File
@@ -3,7 +3,6 @@ const SWIPE_LOCKED_COMPONENTS = new Set([
"ha-slider",
"ha-control-switch",
"ha-control-circular-slider",
"ha-state-control-cover",
"ha-hs-color-picker",
"ha-map",
// Charts pan and pinch-zoom on touch
+2 -12
View File
@@ -4,23 +4,16 @@ import {
mdiArrowDown,
mdiArrowExpandHorizontal,
mdiArrowUp,
mdiDoorClosed,
mdiDoorOpen,
mdiGate,
mdiGateOpen,
} from "@mdi/js";
import type { HassEntity } from "home-assistant-js-websocket";
export const computeOpenIcon = (stateObj: HassEntity): string => {
switch (stateObj.attributes.device_class) {
case "awning":
case "door":
return mdiDoorOpen;
case "gate":
return mdiGateOpen;
case "curtain":
return mdiArrowExpandHorizontal;
case "awning":
return mdiArrowDown;
default:
return mdiArrowUp;
}
@@ -28,14 +21,11 @@ export const computeOpenIcon = (stateObj: HassEntity): string => {
export const computeCloseIcon = (stateObj: HassEntity): string => {
switch (stateObj.attributes.device_class) {
case "awning":
case "door":
return mdiDoorClosed;
case "gate":
return mdiGate;
case "curtain":
return mdiArrowCollapseHorizontal;
case "awning":
return mdiArrowUp;
default:
return mdiArrowDown;
}
+5 -6
View File
@@ -19,7 +19,6 @@ interface MinMaxFrame {
maxPoint: Point;
maxX: number;
maxY: number;
lastX: number;
gapPoint: Point | undefined;
}
@@ -69,7 +68,6 @@ function newFrame(
maxPoint: point,
maxX: x,
maxY: y,
lastX: x,
gapPoint,
};
}
@@ -176,7 +174,6 @@ export function downSampleLineData<
if (!frame) {
frames.set(frameIndex, newFrame(point, x, y, undefined));
} else if (frame.hasValue) {
frame.lastX = x;
// Match the original strict-less / strict-greater comparisons so the
// first occurrence wins on ties.
if (y < frame.minY) {
@@ -192,7 +189,6 @@ export function downSampleLineData<
} else {
// the frame held nothing but a marker so far
frame.hasValue = true;
frame.lastX = x;
frame.minPoint = point;
frame.minX = x;
frame.minY = y;
@@ -217,8 +213,11 @@ export function downSampleLineData<
if (frame.gapPoint !== undefined) {
// A marker followed by a value in its own frame is a gap that closed
// within one frame, which is about one device pixel: too narrow to show.
// That value may be neither min nor max, so check the frame's last x.
if (Number(getPointData(frame.gapPoint)[0]) >= frame.lastX) {
// The kept points are exactly min and max, so comparing against the
// later of the two catches that without any work on the ingest path. A
// marker-only frame compares against its own x and always passes.
const lastValueX = frame.minX > frame.maxX ? frame.minX : frame.maxX;
if (Number(getPointData(frame.gapPoint)[0]) >= lastValueX) {
result.push(frame.gapPoint as T);
}
}
+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;
+27 -160
View File
@@ -76,18 +76,6 @@ export interface NetworkData {
const PHYSICS_DISABLE_THRESHOLD = 512;
const LAYOUT_ANIMATION_THRESHOLD = 100;
// Every event of a change of the legend selection, each with the whole
// selection
const LEGEND_SELECT_EVENTS = [
"legendselectchanged",
"legendselected",
"legendunselected",
"legendselectall",
"legendinverseselect",
];
const SELECTED_NODE_MAX_ZOOM = 2;
// Keeps neighbors clear of the search field, buttons and legend
@@ -136,22 +124,8 @@ export class HaNetworkGraph extends LitElement {
@state() private _showLabels = true;
// Not reactive: a new series option starts the layout again, so a drop only
// reaches the option with the next render
private _nodePositions: Record<string, { x: number; y: number }> = {};
// Dragged nodes stay where they are dropped, the force layout moves the others
private _pinnedNodes: string[] = [];
// Names of the legend categories that are switched off. Not reactive: the
// legend lays the graph out itself, only the layout animation threshold
// needs a render
private _hiddenCategories: string[] = [];
private _dragNode?: string;
private _dragMoved = false;
private _followSelectedNode = false;
private _followedChart?: EChartsType;
@@ -196,15 +170,12 @@ export class HaNetworkGraph extends LitElement {
this._showLabels,
isMobile,
hasHighlightedNodes,
this.selectedNode,
this._nodePositions,
this._pinnedNodes,
this._fewVisibleNodes()
this.selectedNode
)}
.options=${this._createOptions(this.data?.categories)}
height="100%"
.extraComponents=${[GraphChart]}
@chart-setup=${this._handleChartSetup}
@chart-setup=${this._updateFollowing}
>
<slot name="search" slot="search"></slot>
<slot name="button" slot="button"></slot>
@@ -302,10 +273,7 @@ export class HaNetworkGraph extends LitElement {
showLabels: boolean,
isMobile: boolean,
hasHighlightedNodes?: boolean,
selectedNode?: string,
nodePositions: Record<string, { x: number; y: number }> = {},
pinnedNodes: string[] = [],
fewVisibleNodes = true
selectedNode?: string
) => ({
id: "network",
type: "graph",
@@ -343,15 +311,14 @@ export class HaNetworkGraph extends LitElement {
repulsion: [400, 600],
edgeLength: [200, 350],
gravity: 0.05,
layoutAnimation: !reducedMotion && fewVisibleNodes,
layoutAnimation: !reducedMotion && data.nodes.length < 100,
},
edgeSymbol: ["none", "arrow"],
edgeSymbolSize: 10,
data: this._getSeriesData(
data.nodes,
data.links,
nodePositions,
pinnedNodes,
this._nodePositions,
selectedNode
),
links: data.links.map((link) => ({
@@ -367,25 +334,11 @@ export class HaNetworkGraph extends LitElement {
deepEqual
);
// The legend leaves the nodes of hidden categories out of the layout
private _fewVisibleNodes() {
const hidden = this._hiddenCategories;
const visibleNodes = hidden.length
? this.data.nodes.filter(
(node) =>
node.category === undefined ||
!hidden.includes(this.data.categories?.[node.category]?.name ?? "")
).length
: this.data.nodes.length;
return visibleNodes < LAYOUT_ANIMATION_THRESHOLD;
}
private _getSeriesData = memoizeOne(
(
nodes: NetworkNode[],
links: NetworkLink[],
nodePositions: Record<string, { x: number; y: number }>,
pinnedNodes: string[],
selectedNode?: string
) =>
this._getPositionedNodes(nodes, links, nodePositions).map((node) => {
@@ -402,7 +355,7 @@ export class HaNetworkGraph extends LitElement {
? { ...node.itemStyle, borderWidth: 3 }
: node.itemStyle || {},
label: selected ? { ...node.label, fontWeight: "bold" } : node.label,
fixed: node.fixed || pinnedNodes.includes(node.id),
fixed: node.fixed,
x: node.x,
y: node.y,
} as NonNullable<GraphSeriesOption["data"]>[number];
@@ -562,90 +515,6 @@ export class HaNetworkGraph extends LitElement {
}
}
private _handleChartSetup() {
const chart = this._baseChart?.chart;
chart?.on("mousedown", this._handleNodeMouseDown);
chart?.getZr().on("drag", this._handleDrag);
chart?.getZr().on("dragend", this._handleDragEnd);
for (const event of LEGEND_SELECT_EVENTS) {
chart?.on(event, this._handleLegendChange);
}
const legend = (
chart?.getOption() as
{ legend?: { selected?: Record<string, boolean> }[] } | undefined
)?.legend?.[0];
this._setHiddenCategories(legend?.selected ?? {});
// A recreated chart, e.g. after a theme change, lacks the drops since the
// last render
this.requestUpdate();
this._updateFollowing();
}
private _handleLegendChange = (params: unknown) => {
const fewVisibleNodes = this._fewVisibleNodes();
this._setHiddenCategories(
(params as { selected: Record<string, boolean> }).selected
);
if (this._fewVisibleNodes() !== fewVisibleNodes) {
// The new series option lays out again from where the nodes are now
this._saveNodePositions();
this.requestUpdate();
}
};
private _setHiddenCategories(selected: Record<string, boolean>) {
this._hiddenCategories = Object.keys(selected).filter(
(name) => !selected[name]
);
}
private _handleNodeMouseDown = (params: {
dataType?: string;
data?: unknown;
}) => {
this._dragNode =
params.dataType === "node" ? (params.data as NetworkNode).id : undefined;
this._dragMoved = false;
};
private _handleDrag = () => {
this._dragMoved = true;
};
private _handleDragEnd = () => {
const id = this._dragNode;
const moved = this._dragMoved;
this._dragNode = undefined;
this._dragMoved = false;
// A click also ends a drag, which releases a pinned node in ECharts
if (!id || (!moved && !this._pinnedNodes.includes(id))) {
return;
}
this._pinNodeInChart(id);
if (!this._pinnedNodes.includes(id)) {
this._pinnedNodes = [...this._pinnedNodes, id];
}
this._saveNodePositions();
};
// A new series option would start the layout again, so the pin goes into
// the running force layout, and into the item option that ECharts lays out
// from again, e.g. on a legend change
private _pinNodeInChart(id: string) {
const series = this._getGraphSeries();
const node = series?.getGraph().getNodeById(id);
if (!node) {
return;
}
series.forceLayout?.setFixed(node.dataIndex);
const [x, y] = node.getLayout();
Object.assign(series.getData().getRawDataItem(node.dataIndex), {
fixed: true,
x,
y,
});
}
private _updateFollowing() {
const chart = this._followSelectedNode ? this._baseChart?.chart : undefined;
if (chart !== this._followedChart) {
@@ -681,7 +550,10 @@ export class HaNetworkGraph extends LitElement {
if (!chart) {
return;
}
const series = this._getGraphSeries(chart);
const series: any = chart
// @ts-ignore private method but no other way to get the graph positions
.getModel()
.getSeriesByIndex(0);
const node = series?.getGraph().getNodeById(this.selectedNode);
const position: number[] | undefined = node?.getLayout();
if (!position) {
@@ -742,7 +614,6 @@ export class HaNetworkGraph extends LitElement {
private _togglePhysics() {
this._saveNodePositions();
this._pinnedNodes = [];
this._physicsEnabled = !this._physicsEnabled;
}
@@ -751,28 +622,24 @@ export class HaNetworkGraph extends LitElement {
}
private _saveNodePositions() {
// Nodes that are not drawn keep their earlier position
const positions = { ...this._nodePositions };
this._getGraphSeries()
?.getGraph()
.eachNode((node: any) => {
const layout = node.getLayout();
if (layout) {
positions[node.id] = {
x: layout[0],
y: layout[1],
};
}
});
this._nodePositions = positions;
}
private _getGraphSeries(chart = this._baseChart?.chart): any {
if (!chart || chart.isDisposed()) {
return undefined;
const positions = {};
if (this._baseChart?.chart) {
this._baseChart.chart
// @ts-ignore private method but no other way to get the graph positions
.getModel()
.getSeriesByIndex(0)
.getGraph()
.eachNode((node: any) => {
const layout = node.getLayout();
if (layout) {
positions[node.id] = {
x: layout[0],
y: layout[1],
};
}
});
}
// @ts-ignore private method but no other way to get the graph
return chart.getModel().getSeriesByIndex(0);
this._nodePositions = positions;
}
static styles = css`
+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");
+14 -17
View File
@@ -35,29 +35,26 @@ function computeTimelineStateColor(
const domain = computeDomain(stateObj.entity_id);
// Zone states would all share --state-person-active-color, so only an
// exact state variable may color them, like states of uncolored domains.
const isZoneState =
// Zone states for person/device_tracker don't have specific CSS color variables,
// so they all fall back to the same --state-person-active-color.
// Only use a custom CSS variable if explicitly defined (e.g. --state-person-kitchen-color),
// otherwise return undefined to get unique colors from the generic color handler.
if (
(domain === "person" || domain === "device_tracker") &&
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state);
const properties = isZoneState
? undefined
: stateColorProperties(stateObj, state);
if (!properties) {
const stateKey = slugify(state, "_");
const deviceClass = stateObj.attributes.device_class;
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state)
) {
return computeCssValue(
[
...(deviceClass
? [`--state-${domain}-${deviceClass}-${stateKey}-color`]
: []),
`--state-${domain}-${stateKey}-color`,
],
`--state-${domain}-${slugify(state, "_")}-color`,
computedStyles
);
}
const properties = stateColorProperties(stateObj, state);
if (!properties) {
return undefined;
}
const rgb = computeCssValue(properties, computedStyles);
if (!rgb) return undefined;
@@ -107,6 +107,9 @@ export class HaDateRangePicker extends LitElement {
@property({ attribute: false }) public ranges?: DateRangePickerRanges | false;
// Added after the default presets
@property({ attribute: false }) public extraRanges?: DateRangePickerRanges;
@state() private _ranges?: DateRangePickerRanges;
@property({ attribute: "time-picker", type: Boolean })
@@ -166,7 +169,8 @@ export class HaDateRangePicker extends LitElement {
if (
changedProps.has("_i18n") ||
changedProps.has("_hassConfig") ||
changedProps.has("extendedPresets")
changedProps.has("extendedPresets") ||
changedProps.has("extraRanges")
) {
const rangeKeys = this.extendedPresets
? [...RANGE_KEYS, ...EXTENDED_RANGE_KEYS]
@@ -178,7 +182,7 @@ export class HaDateRangePicker extends LitElement {
this._i18n.localize(`ui.components.date-range-picker.ranges.${key}`)
] = calcDateRange(this._i18n.locale, this._hassConfig, key);
});
this._ranges = ranges;
this._ranges = { ...ranges, ...this.extraRanges };
}
}
+1 -1
View File
@@ -52,7 +52,7 @@ class StateInfo extends LitElement {
${
this.inDialog
? html`<div class="time-ago">
<ha-tooltip for="relative-time" trigger="hover focus click">
<ha-tooltip for="relative-time">
<div class="row">
<span class="column-name">
${this._localize(
+8 -2
View File
@@ -33,8 +33,6 @@ class HaConfigNavigationList extends LitElement {
return html`
<ha-list-item-button
.href=${externalApp ? undefined : page.path}
.headline=${page.name}
.supportingText=${this.hasSecondary ? page.description : undefined}
@click=${externalApp ? this._handleExternalApp : undefined}
>
<ha-svg-icon
@@ -45,6 +43,14 @@ class HaConfigNavigationList extends LitElement {
.secondaryPath=${page.iconSecondaryPath}
.viewBox=${page.iconViewBox}
></ha-svg-icon>
<span slot="headline">${page.name}</span>
${
this.hasSecondary
? html`<span slot="supporting-text"
>${page.description}</span
>`
: ""
}
${
!this.narrow
? html`<ha-icon-next slot="end"></ha-icon-next>`
+2 -2
View File
@@ -387,7 +387,7 @@ export class HaControlCircularSlider extends LitElement {
}
private _handleKeyDown(e: KeyboardEvent) {
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
if (!A11Y_KEY_CODES.has(e.code)) return;
e.preventDefault();
if (this._lastSlider) {
this.shadowRoot?.getElementById(this._lastSlider)?.focus();
@@ -439,7 +439,7 @@ export class HaControlCircularSlider extends LitElement {
}
private _handleKeyUp(e: KeyboardEvent) {
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
if (!A11Y_KEY_CODES.has(e.code)) return;
this._activeSlider = (e.currentTarget as any).id as ActiveSlider;
e.preventDefault();
fireEvent(this, `${this._activeSlider}-changing`, {
+1 -2
View File
@@ -87,12 +87,11 @@ export class HaFilterCategories extends LitElement {
public disconnectedCallback() {
super.disconnectedCallback();
this._unsubscribeCategories();
this._categories = [];
}
protected willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
if (changedProps.has("scope") && this.scope !== this._categoriesScope) {
if (changedProps.get("scope") !== undefined) {
this._categories = [];
}
}
+1 -5
View File
@@ -26,11 +26,7 @@ export class HaHelpTooltip extends LitElement {
protected render(): TemplateResult {
return html`
<ha-svg-icon id="svg-icon" .path=${mdiHelpCircleOutline}></ha-svg-icon>
<ha-tooltip
trigger="hover focus click"
for="svg-icon"
.placement=${this.position}
>
<ha-tooltip for="svg-icon" .placement=${this.position}>
${this.label}
</ha-tooltip>
`;
+15 -53
View File
@@ -12,7 +12,6 @@ import type { LocalizeFunc } from "../common/translations/localize";
import { nextRender } from "../common/util/render-status";
import { fetchStreamUrl } from "../data/camera";
import { apiContext, configContext, connectionContext } from "../data/context";
import { isExternal } from "../data/external";
import "./ha-alert";
type HlsLite = Omit<
@@ -72,7 +71,7 @@ class HaHLSPlayer extends LitElement {
@state() private _errorIsFatal = false;
private _url?: string;
@state() private _url!: string;
private _hlsPolyfillInstance?: HlsLite;
@@ -82,22 +81,12 @@ class HaHLSPlayer extends LitElement {
private _hiddenCleanupTimeout?: number;
// Increased on every clean up, so a start that is still waiting on the
// network knows it is outdated
private _cleanUpCount = 0;
private _handleVisibilityChange = () => {
if (document.pictureInPictureElement) {
// video is playing in picture-in-picture mode, don't do anything
return;
}
if (document.hidden) {
if (isExternal) {
// The companion apps pause JavaScript timers while in the background,
// so a delayed clean up would not run until the app is opened again
this._cleanUp();
return;
}
this._hiddenCleanupTimeout = window.setTimeout(() => {
this._hiddenCleanupTimeout = undefined;
this._cleanUp();
@@ -107,7 +96,8 @@ class HaHLSPlayer extends LitElement {
clearTimeout(this._hiddenCleanupTimeout);
this._hiddenCleanupTimeout = undefined;
} else {
this._restartHls();
this._resetError();
this._startHls();
}
};
@@ -115,7 +105,8 @@ class HaHLSPlayer extends LitElement {
super.connectedCallback();
HaHLSPlayer.streamCount += 1;
if (this.hasUpdated) {
this._restartHls();
this._resetError();
this._startHls();
}
document.addEventListener("visibilitychange", this._handleVisibilityChange);
}
@@ -180,22 +171,9 @@ class HaHLSPlayer extends LitElement {
}
}
/** Starts the stream again, replacing a start that is still pending. */
private _restartHls() {
if (this.entityid) {
// The stream URL stops working once the stream has been idle for a while
this._getStreamUrlFromEntityId();
return;
}
this._cleanUp();
this._resetError();
this._startHls();
}
private async _getStreamUrlFromEntityId(): Promise<void> {
this._cleanUp();
this._resetError();
this._url = undefined;
if (!isComponentLoaded(this._config.config, "stream")) {
this._setFatalError("Streaming component is not loaded.");
@@ -206,18 +184,12 @@ class HaHLSPlayer extends LitElement {
if (!entityId) {
return;
}
const cleanUpCount = this._cleanUpCount;
try {
const { url } = await fetchStreamUrl(
{ callWS: this._api.callWS, hassUrl: this._connection.hassUrl },
entityId
);
if (cleanUpCount !== this._cleanUpCount) {
// Removed, hidden or switched camera while fetching
return;
}
this._url = this._connection.hassUrl(url);
this._cleanUp();
this._resetError();
@@ -227,8 +199,8 @@ class HaHLSPlayer extends LitElement {
// eslint-disable-next-line
console.error(err);
if (cleanUpCount !== this._cleanUpCount || entityId !== this.entityid) {
// Removed, hidden or switched camera while fetching
if (!this.isConnected || entityId !== this.entityid) {
// Removed or switched camera while fetching, the result is outdated
return;
}
fireEvent(this, "streams", { hasAudio: false, hasVideo: false });
@@ -236,18 +208,13 @@ class HaHLSPlayer extends LitElement {
}
private async _startHls(): Promise<void> {
const url = this._url;
if (!url) {
return;
}
const cleanUpCount = this._cleanUpCount;
const masterPlaylistPromise = fetch(url);
const masterPlaylistPromise = fetch(this._url);
// eslint-disable-next-line @typescript-eslint/naming-convention
const Hls: typeof HlsType = (await import("hls.js/dist/hls.light.mjs"))
.default;
if (cleanUpCount !== this._cleanUpCount || !this.isConnected) {
if (!this.isConnected) {
return;
}
@@ -269,7 +236,7 @@ class HaHLSPlayer extends LitElement {
this.allowExoPlayer && this._config.auth.external?.config.hasExoPlayer;
const masterPlaylist = await (await masterPlaylistPromise).text();
if (cleanUpCount !== this._cleanUpCount || !this.isConnected) {
if (!this.isConnected) {
return;
}
@@ -285,9 +252,9 @@ class HaHLSPlayer extends LitElement {
let playlist_url: string;
if (match !== null && matchTwice === null) {
// Only send the regular playlist url if we match exactly once
playlist_url = new URL(match[3], url).href;
playlist_url = new URL(match[3], this._url).href;
} else {
playlist_url = url;
playlist_url = this._url;
}
const codecs = match ? `${match[1]},${match[2]}` : undefined;
@@ -425,17 +392,12 @@ class HaHLSPlayer extends LitElement {
private async _renderHLSNative(videoEl: HTMLVideoElement, url: string) {
videoEl.src = url;
videoEl.addEventListener(
"loadedmetadata",
() => {
videoEl.play();
},
{ once: true }
);
videoEl.addEventListener("loadedmetadata", () => {
videoEl.play();
});
}
private _cleanUp() {
this._cleanUpCount++;
if (this._hlsPolyfillInstance) {
this._hlsPolyfillInstance.destroy();
this._hlsPolyfillInstance = undefined;
+1 -5
View File
@@ -32,10 +32,6 @@ export class HaMarqueeText extends LitElement {
private _pauseTimeout?: number;
private get _animationFactor() {
return document.dir === "rtl" ? -1 : 1;
}
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
@@ -121,7 +117,7 @@ export class HaMarqueeText extends LitElement {
reachedEnd = true;
}
}
this._textSpan.style.transform = `translateX(${this._position * this._animationFactor}px)`;
this._textSpan.style.transform = `translateX(${this._position}px)`;
if (reachedEnd) {
this._pauseTimeout = window.setTimeout(() => {
this._pauseTimeout = undefined;
+3 -25
View File
@@ -171,16 +171,6 @@ export class HaRipple extends LitElement {
return;
}
// A touch long press opens the context menu while the press continues,
// e.g. for a hold action. touchend or pointercancel ends it instead.
if (
ev.type === "contextmenu" &&
this._startEvent &&
isTouch(this._startEvent)
) {
return;
}
if (ev.type === "contextmenu" || ev.type === "touchend") {
this._endPress();
@@ -203,25 +193,13 @@ export class HaRipple extends LitElement {
break;
case "pointerenter":
this._hovered = true;
if (this._state === "waiting-for-click") {
if (ev.buttons === 1) {
// Back on the control with the press still held
this._pressed = true;
} else {
// The press was released off the control, so no click follows
this._endPress();
}
}
break;
case "pointerleave":
this._hovered = false;
// A mouse or pen press that moves off the control still clicks if it
// is released back on it, so only hide the press until it returns
if (this._state === "waiting-for-click") {
this._pressed = false;
// Release a held mouse or pen press that moves off the control
if (this._state !== "inactive") {
this._endPress();
}
break;
+4 -7
View File
@@ -465,13 +465,10 @@ export class HaServiceControl extends LitElement {
serviceData?.flatFields.some((field) => showOptionalToggle(field))
);
// Actions that can never have targets get null, like template targets
const targetEntities =
serviceData &&
("target" in serviceData ||
serviceData.flatFields.some((field) => field.key === "entity_id"))
? this._getTargetedEntities(serviceData.target, this._value)
: null;
const targetEntities = this._getTargetedEntities(
serviceData?.target,
this._value
);
const domain = this._value?.action
? computeDomain(this._value.action)
-7
View File
@@ -18,7 +18,6 @@ import {
type WebRtcOfferEvent,
} from "../data/camera";
import { apiContext, connectionContext } from "../data/context";
import { isExternal } from "../data/external";
import "./ha-alert";
import "./ha-spinner";
import { showToast } from "../util/toast";
@@ -237,12 +236,6 @@ export class HaWebRtcPlayer extends LitElement {
return;
}
if (document.hidden) {
if (isExternal) {
// The companion apps pause JavaScript timers while in the background,
// so a delayed clean up would not run until the app is opened again
this._cleanUp();
return;
}
this._hiddenCleanupTimeout = window.setTimeout(() => {
this._hiddenCleanupTimeout = undefined;
this._cleanUp();
@@ -22,65 +22,11 @@ const SMALL_THUMBNAIL_THRESHOLD = 16;
const isSvgUrl = (url: string): boolean =>
/\.svg(\?|#|$)/i.test(url) || url.startsWith("data:image/svg+xml");
// Local thumbnails can be slow to generate, for example when the integration
// extracts them from a recording on a camera. Without a limit they take all of
// the browser's connections to Home Assistant (6 for HTTP/1.1), and requests
// such as starting media playback wait until all queued thumbnails are loaded.
const MAX_PARALLEL_LOCAL_THUMBNAILS = 4;
let activeLocalThumbnails = 0;
const localThumbnailQueue: (() => void)[] = [];
const acquireLocalThumbnailSlot = (signal: AbortSignal): Promise<void> => {
if (signal.aborted) {
return Promise.reject(signal.reason);
}
if (activeLocalThumbnails < MAX_PARALLEL_LOCAL_THUMBNAILS) {
activeLocalThumbnails++;
return Promise.resolve();
}
return new Promise<void>((resolve, reject) => {
const start = () => {
signal.removeEventListener("abort", onAbort);
activeLocalThumbnails++;
resolve();
};
const onAbort = () => {
const index = localThumbnailQueue.indexOf(start);
if (index !== -1) {
localThumbnailQueue.splice(index, 1);
}
reject(signal.reason);
};
localThumbnailQueue.push(start);
signal.addEventListener("abort", onAbort, { once: true });
});
};
const releaseLocalThumbnailSlot = (): void => {
activeLocalThumbnails--;
localThumbnailQueue.shift()?.();
};
const fetchLocalThumbnail = async (
fetchWithAuth: HomeAssistantApi["fetchWithAuth"],
thumbnailUrl: string,
signal: AbortSignal
): Promise<Blob> => {
await acquireLocalThumbnailSlot(signal);
try {
const response = await fetchWithAuth(thumbnailUrl, { signal });
return await response.blob();
} finally {
releaseLocalThumbnailSlot();
}
};
const resolveThumbnailURL = (
thumbnailUrl: string,
darkMode: boolean | undefined,
hassUrl: string | undefined,
fetchWithAuth: HomeAssistantApi["fetchWithAuth"],
signal: AbortSignal
fetchWithAuth: HomeAssistantApi["fetchWithAuth"]
): Promise<string> => {
if (isBrandUrl(thumbnailUrl)) {
return Promise.resolve(
@@ -96,16 +42,18 @@ const resolveThumbnailURL = (
}
if (thumbnailUrl.startsWith("/")) {
// Local thumbnails require authentication; fetch and inline as base64.
return fetchLocalThumbnail(fetchWithAuth, thumbnailUrl, signal).then(
(blob) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () =>
resolve(typeof reader.result === "string" ? reader.result : "");
reader.onerror = (e) => reject(e);
reader.readAsDataURL(blob);
})
);
return fetchWithAuth(thumbnailUrl)
.then((response) => response.blob())
.then(
(blob) =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () =>
resolve(typeof reader.result === "string" ? reader.result : "");
reader.onerror = (e) => reject(e);
reader.readAsDataURL(blob);
})
);
}
return Promise.resolve(thumbnailUrl);
};
@@ -137,28 +85,6 @@ export class HaMediaBrowserThumbnail extends LitElement {
@state() private _brand = false;
private _abortController?: AbortController;
public connectedCallback(): void {
super.connectedCallback();
// Resume a thumbnail which was aborted when this element was disconnected
if (this.hasUpdated && this.url && !this._resolvedUrl) {
this._resolve();
}
}
public disconnectedCallback(): void {
super.disconnectedCallback();
// Do not keep loading thumbnails which are no longer shown
if (this._abortController) {
this._abortController.abort();
this._abortController = undefined;
// A shown image can belong to a previous url, clear it so
// connectedCallback restarts loading the current url.
this._resolvedUrl = undefined;
}
}
protected willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
if (
@@ -171,8 +97,6 @@ export class HaMediaBrowserThumbnail extends LitElement {
}
private async _resolve(): Promise<void> {
this._abortController?.abort();
this._abortController = undefined;
this._small = false;
this._brand = !!this.url && isBrandUrl(this.url);
if (!this.url) {
@@ -180,28 +104,18 @@ export class HaMediaBrowserThumbnail extends LitElement {
return;
}
const requested = this.url;
const abortController = new AbortController();
this._abortController = abortController;
try {
const resolved = await resolveThumbnailURL(
requested,
this._darkMode,
this._hassUrl,
this._api.fetchWithAuth,
abortController.signal
this._api.fetchWithAuth
);
if (requested !== this.url) return;
this._resolvedUrl = resolved;
this._probeSize(resolved);
} catch (_err) {
// Aborted when the url changed or this element was disconnected,
// which already restarted or reset the resolution.
if (abortController.signal.aborted) return;
if (requested === this.url) this._resolvedUrl = undefined;
} finally {
if (this._abortController === abortController) {
this._abortController = undefined;
}
}
}
@@ -112,7 +112,7 @@ export class HaTracePathDetails extends LitElement {
initialValue: {
options: [],
showIndices: false,
select: () => true,
select: () => undefined,
fixDuplicateIds: async () => undefined,
updateTriggerId: () => false,
},
+1 -1
View File
@@ -123,7 +123,7 @@ export const setProtectedAlarmControlPanelMode = async (
(mode === "disarmed" && stateObj.attributes.code_format)
) {
const entry = await getExtendedEntityRegistryEntry(
hass.callWS,
hass,
stateObj.entity_id
).catch(() => undefined);
const defaultCode = entry?.options?.alarm_control_panel?.default_code;
+25 -123
View File
@@ -2,37 +2,16 @@ import type {
HassEntityAttributeBase,
HassEntityBase,
} from "home-assistant-js-websocket";
import { stateActive } from "../common/entity/state_active";
import { supportsFeature } from "../common/entity/supports-feature";
import { UNAVAILABLE, UNKNOWN } from "./entity/entity";
import type { HomeAssistantFormatters } from "../types";
import { UNAVAILABLE } from "./entity/entity";
import { CoverEntityFeature } from "./feature/cover_entity_feature";
export { CoverEntityFeature };
export const DEFAULT_COVER_FAVORITE_POSITIONS = [0, 25, 75, 100];
export type CoverControlMode = "position" | "tilt";
export type CoverAction = "open" | "close" | "stop";
export type CoverCommand =
| { mode: CoverControlMode; action: CoverAction }
| { mode: CoverControlMode; action: "set"; value: number };
export interface CoverRequest {
mode: CoverControlMode;
value: number;
}
export interface CoverSwipe {
action: "open" | "close";
passedHalfway: boolean;
}
export interface CoverDrag {
value: number;
swipe?: CoverSwipe;
}
export const coverSupportsPosition = (stateObj: CoverEntity) =>
supportsFeature(stateObj, CoverEntityFeature.SET_POSITION);
@@ -42,79 +21,11 @@ export const coverSupportsTiltPosition = (stateObj: CoverEntity) =>
export const coverSupportsAnyPosition = (stateObj: CoverEntity) =>
coverSupportsPosition(stateObj) || coverSupportsTiltPosition(stateObj);
export const coverSupportsSetValue = (
stateObj: CoverEntity,
mode: CoverControlMode
) =>
mode === "tilt"
? coverSupportsTiltPosition(stateObj)
: coverSupportsPosition(stateObj);
const POSITION_FEATURES = [
CoverEntityFeature.OPEN,
CoverEntityFeature.CLOSE,
CoverEntityFeature.STOP,
CoverEntityFeature.SET_POSITION,
];
const TILT_FEATURES = [
CoverEntityFeature.OPEN_TILT,
CoverEntityFeature.CLOSE_TILT,
CoverEntityFeature.STOP_TILT,
CoverEntityFeature.SET_TILT_POSITION,
];
export const coverHasPositionControls = (stateObj: CoverEntity) =>
POSITION_FEATURES.some((feature) => supportsFeature(stateObj, feature));
export const coverHasTiltControls = (stateObj: CoverEntity) =>
TILT_FEATURES.some((feature) => supportsFeature(stateObj, feature));
export const defaultCoverMode = (stateObj: CoverEntity): CoverControlMode =>
coverHasTiltControls(stateObj) && !coverHasPositionControls(stateObj)
? "tilt"
: "position";
export const coverModeAttribute = (mode: CoverControlMode) =>
mode === "tilt" ? "current_tilt_position" : "current_position";
const COVER_SERVICES: Record<
CoverControlMode,
Record<CoverCommand["action"], string>
> = {
position: {
open: "open_cover",
close: "close_cover",
stop: "stop_cover",
set: "set_cover_position",
},
tilt: {
open: "open_cover_tilt",
close: "close_cover_tilt",
stop: "stop_cover_tilt",
set: "set_cover_tilt_position",
},
};
export const coverCommandService = ({ mode, action }: CoverCommand) =>
COVER_SERVICES[mode][action];
export const coverCommandData = (
stateObj: CoverEntity,
command: CoverCommand
): Record<string, unknown> => {
const data = { entity_id: stateObj.entity_id };
if (command.action !== "set") {
return data;
}
if (command.mode === "tilt") {
return { ...data, tilt_position: command.value };
}
return { ...data, position: command.value };
};
export function isFullyOpen(stateObj: CoverEntity) {
return stateObj.attributes.current_position === 100;
if (stateObj.attributes.current_position !== undefined) {
return stateObj.attributes.current_position === 100;
}
return stateObj.state === "open";
}
export function isFullyClosed(stateObj: CoverEntity) {
@@ -140,10 +51,6 @@ export function isClosing(stateObj: CoverEntity) {
return stateObj.state === "closing";
}
export function isMoving(stateObj: CoverEntity) {
return isOpening(stateObj) || isClosing(stateObj);
}
export function isTiltOnly(stateObj: CoverEntity) {
const supportsCover =
supportsFeature(stateObj, CoverEntityFeature.OPEN) ||
@@ -206,29 +113,24 @@ export interface CoverEntity extends HassEntityBase {
attributes: CoverEntityAttributes;
}
export const coverCurrentValue = (
export function computeCoverPositionStateDisplay(
stateObj: CoverEntity,
mode: CoverControlMode
): number | undefined => {
if (mode === "tilt") {
return stateObj.attributes.current_tilt_position ?? undefined;
}
const position = stateObj.attributes.current_position;
if (
position != null ||
supportsFeature(stateObj, CoverEntityFeature.SET_POSITION)
) {
return position ?? undefined;
}
if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
return undefined;
}
return stateObj.state === "closed" || stateObj.state === "opening" ? 0 : 100;
};
formatEntityAttributeValue: HomeAssistantFormatters["formatEntityAttributeValue"],
position?: number
) {
const statePosition = stateActive(stateObj)
? (stateObj.attributes.current_position ??
stateObj.attributes.current_tilt_position)
: undefined;
declare global {
interface HASSDomEvents {
"cover-command": CoverCommand;
"cover-drag-changed": { drag?: CoverDrag };
}
const currentPosition = position ?? statePosition;
return currentPosition && currentPosition !== 100
? formatEntityAttributeValue(
stateObj,
// Always use position as it's the same formatting as tilt position
"current_position",
Math.round(currentPosition)
)
: "";
}
+50 -323
View File
@@ -81,6 +81,7 @@ export const emptyGridSourceEnergyPreference =
number_energy_price: null,
entity_energy_price_export: null,
number_energy_price_export: null,
cost_adjustment_day: 0,
});
export const emptySolarEnergyPreference =
@@ -96,6 +97,13 @@ export const emptyHomeEnergyPreference =
stat_energy_to: "",
});
export const emptyBatteryEnergyPreference =
(): BatterySourceTypeEnergyPreference => ({
type: "battery",
stat_energy_from: "",
stat_energy_to: "",
});
export const emptyGasEnergyPreference = (): GasSourceTypeEnergyPreference => ({
type: "gas",
stat_energy_from: "",
@@ -161,6 +169,7 @@ export interface GridSourceTypeEnergyPreference {
stat_rate?: string; // always available if power_config is set
power_config?: PowerConfig;
cost_adjustment_day: number;
name?: string;
}
@@ -181,125 +190,16 @@ export interface HomeSourceTypeEnergyPreference {
name?: string;
}
export interface BatteryTotalsSourceTypeEnergyPreference {
export interface BatterySourceTypeEnergyPreference {
type: "battery";
stat_energy_from: string; // out of the battery
stat_energy_to: string; // into the battery
stat_energy_from: string;
stat_energy_to: string;
stat_rate?: string; // always available if power_config is set
power_config?: PowerConfig;
stat_soc?: string;
capacity?: number; // usable capacity in kWh, used to weight the combined SOC
name?: string;
}
// Non-negative power sensors, any subset
export interface BatteryDirectionsPowerConfig {
stat_rate_from_grid?: string; // grid → battery
stat_rate_from_solar?: string; // solar → battery
stat_rate_to_home?: string; // battery → home
stat_rate_to_grid?: string; // battery → grid
}
// A missing direction is 0. At least one charge and one discharge direction is
// required, so getBatteryEnergyStatIds never returns an empty list.
export interface BatteryDirectionsSourceTypeEnergyPreference {
type: "battery";
stat_energy_from?: undefined;
stat_energy_to?: undefined;
stat_energy_from_grid?: string; // grid → battery
stat_energy_from_solar?: string; // solar → battery
stat_energy_to_home?: string; // battery → home
stat_energy_to_grid?: string; // battery → grid
// Net power generated from power_config, + discharge and − charge
stat_rate?: string;
power_config?: BatteryDirectionsPowerConfig;
stat_soc?: string;
capacity?: number;
name?: string;
}
export type BatterySourceTypeEnergyPreference =
| BatteryTotalsSourceTypeEnergyPreference
| BatteryDirectionsSourceTypeEnergyPreference;
export interface BatteryFlowStatIds {
grid_to_battery?: string;
solar_to_battery?: string;
battery_to_home?: string;
battery_to_grid?: string;
}
export const BATTERY_FLOW_KEYS = [
"grid_to_battery",
"solar_to_battery",
"battery_to_home",
"battery_to_grid",
] as const satisfies readonly (keyof BatteryFlowStatIds)[];
export const isBatteryDirections = (
source: BatterySourceTypeEnergyPreference
): source is BatteryDirectionsSourceTypeEnergyPreference => {
const directions = source as BatteryDirectionsSourceTypeEnergyPreference;
return !!(
directions.stat_energy_from_grid ||
directions.stat_energy_from_solar ||
directions.stat_energy_to_home ||
directions.stat_energy_to_grid
);
};
/** The direction statistics, or undefined for a battery configured with totals. */
export const getBatteryFlowStatIds = (
source: BatterySourceTypeEnergyPreference
): BatteryFlowStatIds | undefined =>
isBatteryDirections(source)
? {
grid_to_battery: source.stat_energy_from_grid || undefined,
solar_to_battery: source.stat_energy_from_solar || undefined,
battery_to_home: source.stat_energy_to_home || undefined,
battery_to_grid: source.stat_energy_to_grid || undefined,
}
: undefined;
/** The direction power sensors, or undefined for a battery configured with totals. */
export const getBatteryFlowPowerIds = (
source: BatterySourceTypeEnergyPreference
): BatteryFlowStatIds | undefined =>
isBatteryDirections(source)
? {
grid_to_battery: source.power_config?.stat_rate_from_grid || undefined,
solar_to_battery:
source.power_config?.stat_rate_from_solar || undefined,
battery_to_home: source.power_config?.stat_rate_to_home || undefined,
battery_to_grid: source.power_config?.stat_rate_to_grid || undefined,
}
: undefined;
/** Statistics whose sum is the energy going into and coming out of the battery. */
export const getBatteryEnergyStatIds = (
source: BatterySourceTypeEnergyPreference
): { charge: string[]; discharge: string[] } => {
if (!isBatteryDirections(source)) {
return {
charge: [source.stat_energy_to],
discharge: [source.stat_energy_from],
};
}
const ids = (...stats: (string | undefined)[]) =>
stats.filter((id): id is string => !!id);
return {
charge: ids(source.stat_energy_from_grid, source.stat_energy_from_solar),
discharge: ids(source.stat_energy_to_home, source.stat_energy_to_grid),
};
};
/** Identifies a battery in page keys and lookups. */
export const getBatteryPrimaryStat = (
source: BatterySourceTypeEnergyPreference
): string => {
const { charge, discharge } = getBatteryEnergyStatIds(source);
return discharge[0] ?? charge[0] ?? "";
};
export interface GasSourceTypeEnergyPreference {
type: "gas";
@@ -492,28 +392,6 @@ export const computeEnergyLabel = (
);
};
/**
* Name that cards show as "<name> charged" and "<name> discharged". Unnamed
* batteries configured with totals are labelled by each statistic instead.
*/
export const getBatteryName = (
states: HomeAssistant["states"],
formatEntityName: HomeAssistant["formatEntityName"],
source: BatterySourceTypeEnergyPreference,
statsMetadata?: Record<string, StatisticsMetaData>
): string | undefined => {
if (source.name || !isBatteryDirections(source)) {
return source.name;
}
const primary = getBatteryPrimaryStat(source);
return computeEnergyLabel(
states,
formatEntityName,
primary,
statsMetadata?.[primary]
);
};
export const computeEnergyStatisticArea = (
registries: HomeAssistantRegistries,
statisticId: string
@@ -674,8 +552,8 @@ export const getReferencedStatisticIds = (
}
if (source.type === "battery") {
const { charge, discharge } = getBatteryEnergyStatIds(source);
statIDs.push(...discharge, ...charge);
statIDs.push(source.stat_energy_from);
statIDs.push(source.stat_energy_to);
continue;
}
@@ -1759,8 +1637,7 @@ const getEnergyGasUnit = (
return [source.stat_energy_to];
}
if (source.type === "battery") {
const { charge, discharge } = getBatteryEnergyStatIds(source);
return [...discharge, ...charge];
return [source.stat_energy_from, source.stat_energy_to];
}
if (source.type === "grid") {
return [source.stat_energy_from, source.stat_energy_to].filter(
@@ -1833,14 +1710,6 @@ export interface EnergySumData {
from_battery?: Record<number, number>;
solar?: Record<number, number>;
home?: Record<number, number>;
// Set together, only when a battery has direction statistics
grid_to_battery?: Record<number, number>;
solar_to_battery?: Record<number, number>;
battery_to_home?: Record<number, number>;
battery_to_grid?: Record<number, number>;
// Charge and discharge of the batteries configured with totals
to_battery_totals?: Record<number, number>;
from_battery_totals?: Record<number, number>;
total: {
to_grid?: number;
from_grid?: number;
@@ -1848,12 +1717,6 @@ export interface EnergySumData {
from_battery?: number;
solar?: number;
home?: number;
grid_to_battery?: number;
solar_to_battery?: number;
battery_to_home?: number;
battery_to_grid?: number;
to_battery_totals?: number;
from_battery_totals?: number;
};
timestamps: number[];
}
@@ -1895,10 +1758,14 @@ const getSummedDataPartial = (
data: EnergyData,
compare?: boolean
): EnergySumData => {
const statIds: Partial<
Record<Exclude<keyof EnergySumData, "total" | "timestamps">, string[]>
> = {};
const batteries: BatterySourceTypeEnergyPreference[] = [];
const statIds: {
to_grid?: string[];
from_grid?: string[];
solar?: string[];
to_battery?: string[];
from_battery?: string[];
home?: string[];
} = {};
for (const source of data.prefs.energy_sources) {
if (source.type === "solar") {
@@ -1916,14 +1783,12 @@ const getSummedDataPartial = (
}
if (source.type === "battery") {
batteries.push(source);
const { charge, discharge } = getBatteryEnergyStatIds(source);
if (statIds.to_battery) {
statIds.to_battery.push(...charge);
statIds.from_battery!.push(...discharge);
statIds.to_battery.push(source.stat_energy_to);
statIds.from_battery!.push(source.stat_energy_from);
} else {
statIds.to_battery = [...charge];
statIds.from_battery = [...discharge];
statIds.to_battery = [source.stat_energy_to];
statIds.from_battery = [source.stat_energy_from];
}
continue;
}
@@ -1949,23 +1814,6 @@ const getSummedDataPartial = (
}
}
if (batteries.some(isBatteryDirections)) {
for (const key of BATTERY_FLOW_KEYS) {
statIds[key] = batteries.flatMap(
(battery) => getBatteryFlowStatIds(battery)?.[key] ?? []
);
}
const totalsBatteries = batteries.filter(
(battery) => !isBatteryDirections(battery)
);
statIds.to_battery_totals = totalsBatteries.flatMap(
(battery) => getBatteryEnergyStatIds(battery).charge
);
statIds.from_battery_totals = totalsBatteries.flatMap(
(battery) => getBatteryEnergyStatIds(battery).discharge
);
}
const summedData: EnergySumData = { total: {}, timestamps: [] };
const timestamps = new Set<number>();
Object.entries(statIds).forEach(([key, subStatIds]) => {
@@ -2036,12 +1884,11 @@ const computeConsumptionDataPartial = (
},
};
const measured = BATTERY_FLOW_KEYS.some((key) => data[key]);
const fromGrid = data.from_grid;
const toGrid = data.to_grid;
const solarData = data.solar;
const toBattery = measured ? data.to_battery_totals : data.to_battery;
const fromBattery = measured ? data.from_battery_totals : data.from_battery;
const toBattery = data.to_battery;
const fromBattery = data.from_battery;
const total = outData.total;
data.timestamps.forEach((t) => {
@@ -2056,25 +1903,13 @@ const computeConsumptionDataPartial = (
used_total,
solar_to_battery,
solar_to_grid,
} = computeConsumptionSingle(
{
from_grid: fromGrid && (fromGrid[t] ?? 0),
to_grid: toGrid && (toGrid[t] ?? 0),
solar: solarData && (solarData[t] ?? 0),
to_battery: toBattery && (toBattery[t] ?? 0),
from_battery: fromBattery && (fromBattery[t] ?? 0),
},
measured
? {
measured: {
grid_to_battery: data.grid_to_battery?.[t] ?? 0,
solar_to_battery: data.solar_to_battery?.[t] ?? 0,
battery_to_home: data.battery_to_home?.[t] ?? 0,
battery_to_grid: data.battery_to_grid?.[t] ?? 0,
},
}
: undefined
);
} = computeConsumptionSingle({
from_grid: fromGrid && (fromGrid[t] ?? 0),
to_grid: toGrid && (toGrid[t] ?? 0),
solar: solarData && (solarData[t] ?? 0),
to_battery: toBattery && (toBattery[t] ?? 0),
from_battery: fromBattery && (fromBattery[t] ?? 0),
});
const usedTotal = hasHome ? Math.max(homeUsed, 0) : used_total;
outData.used_total[t] = usedTotal;
@@ -2098,15 +1933,13 @@ const computeConsumptionDataPartial = (
return outData;
};
interface ConsumptionInput {
export const computeConsumptionSingle = (data: {
from_grid: number | undefined;
to_grid: number | undefined;
solar: number | undefined;
to_battery: number | undefined;
from_battery: number | undefined;
}
interface ConsumptionResult {
}): {
grid_to_battery: number;
battery_to_grid: number;
solar_to_battery: number;
@@ -2115,12 +1948,7 @@ interface ConsumptionResult {
used_grid: number;
used_battery: number;
used_total: number;
}
const inferConsumption = (
data: ConsumptionInput,
usedTotal?: number
): ConsumptionResult => {
} => {
let to_grid = Math.max(data.to_grid || 0, 0);
let to_battery = Math.max(data.to_battery || 0, 0);
let solar = Math.max(data.solar || 0, 0);
@@ -2128,12 +1956,11 @@ const inferConsumption = (
let from_battery = Math.max(data.from_battery || 0, 0);
const used_total =
usedTotal ??
(from_grid || 0) +
(solar || 0) +
(from_battery || 0) -
(to_grid || 0) -
(to_battery || 0);
(solar || 0) +
(from_battery || 0) -
(to_grid || 0) -
(to_battery || 0);
let grid_to_battery = 0;
@@ -2201,70 +2028,6 @@ const inferConsumption = (
};
};
export type MeasuredBatteryFlows = Record<
(typeof BATTERY_FLOW_KEYS)[number],
number | undefined
>;
/**
* Splits the energy or power of one period into flows. Batteries with
* direction statistics pass them in `measured`, and `to_battery` and
* `from_battery` then only hold the batteries configured with totals.
* Measured flows are kept as they are; only the rest is estimated. Leave a
* meter undefined when it isn't configured, rather than 0.
*/
export const computeConsumptionSingle = (
data: ConsumptionInput,
options?: { measured?: MeasuredBatteryFlows; used_total?: number }
): ConsumptionResult => {
const measured = options?.measured;
if (!measured) {
return inferConsumption(data, options?.used_total);
}
const clamp = (value: number | undefined) => Math.max(value || 0, 0);
const gridToBattery = clamp(measured.grid_to_battery);
const solarToBattery = clamp(measured.solar_to_battery);
const batteryToHome = clamp(measured.battery_to_home);
const batteryToGrid = clamp(measured.battery_to_grid);
const fromGrid = clamp(data.from_grid);
const toGrid = clamp(data.to_grid);
const solar = clamp(data.solar);
// A flow without a configured meter never passed one, so it stays out of
// the home load
const metered = (meter: number | undefined, flow: number) =>
meter === undefined ? 0 : flow;
const toBattery =
clamp(data.to_battery) +
metered(data.from_grid, gridToBattery) +
metered(data.solar, solarToBattery);
const fromBattery =
clamp(data.from_battery) +
batteryToHome +
metered(data.to_grid, batteryToGrid);
const usedTotal =
options.used_total ?? fromGrid + solar + fromBattery - toGrid - toBattery;
// Only what the measured flows leave over is estimated
const inferred = inferConsumption(
{
from_grid: Math.max(fromGrid - gridToBattery, 0),
to_grid: Math.max(toGrid - batteryToGrid, 0),
solar: Math.max(solar - solarToBattery, 0),
to_battery: data.to_battery,
from_battery: data.from_battery,
},
Math.max(usedTotal - batteryToHome, 0)
);
return {
...inferred,
grid_to_battery: inferred.grid_to_battery + gridToBattery,
solar_to_battery: inferred.solar_to_battery + solarToBattery,
battery_to_grid: inferred.battery_to_grid + batteryToGrid,
used_battery: inferred.used_battery + batteryToHome,
used_total: usedTotal,
};
};
export const formatConsumptionShort = (
locale: HomeAssistant["locale"],
consumption: number | null,
@@ -2754,54 +2517,18 @@ export const downloadEnergyData = (
grid_productions_cost
);
const batteries = energy_sources.filter(
(s): s is BatterySourceTypeEnergyPreference => s.type === "battery"
);
const battery_ins: string[] = [];
const battery_outs: string[] = [];
const battery_flows: Record<keyof BatteryFlowStatIds, string[]> = {
grid_to_battery: [],
solar_to_battery: [],
battery_to_home: [],
battery_to_grid: [],
};
batteries.forEach((source) => {
const flows = getBatteryFlowStatIds(source);
if (!flows) {
const { charge, discharge } = getBatteryEnergyStatIds(source);
battery_ins.push(...charge);
battery_outs.push(...discharge);
return;
}
BATTERY_FLOW_KEYS.forEach((key) => {
if (flows[key]) {
battery_flows[key].push(flows[key]);
}
energy_sources
.filter((s) => s.type === "battery")
.forEach((source) => {
source = source as BatterySourceTypeEnergyPreference;
battery_ins.push(source.stat_energy_to);
battery_outs.push(source.stat_energy_from);
});
});
printCategory("battery_in", battery_ins, electricUnit);
printCategory("battery_out", battery_outs, electricUnit);
printCategory(
"battery_in_from_grid",
battery_flows.grid_to_battery,
electricUnit
);
printCategory(
"battery_in_from_solar",
battery_flows.solar_to_battery,
electricUnit
);
printCategory(
"battery_out_to_home",
battery_flows.battery_to_home,
electricUnit
);
printCategory(
"battery_out_to_grid",
battery_flows.battery_to_grid,
electricUnit
);
const solar_productions: string[] = [];
energy_sources
@@ -2918,7 +2645,7 @@ export const downloadEnergyData = (
const hasSolar = !!solar_productions.length;
const hasHome = !!home_consumptions.length;
const hasBattery = batteries.length > 0;
const hasBattery = !!battery_ins.length;
const hasGridReturn = !!grid_productions.length;
const hasGridSource = !!grid_consumptions.length;
+2 -2
View File
@@ -266,10 +266,10 @@ export const computeEntityRegistryName = (
};
export const getExtendedEntityRegistryEntry = (
callWS: HomeAssistant["callWS"],
hass: Pick<HomeAssistant, "callWS">,
entityId: string
): Promise<ExtEntityRegistryEntry> =>
callWS({
hass.callWS({
type: "config/entity_registry/get",
entity_id: entityId,
});
-55
View File
@@ -1,11 +1,8 @@
import type {
HassEntities,
HassEntity,
HassEntityAttributeBase,
HassEntityBase,
} from "home-assistant-js-websocket";
import { computeDomain } from "../common/entity/compute_domain";
import type { ExtEntityRegistryEntry } from "./entity/entity_registry";
interface GroupEntityAttributes extends HassEntityAttributeBase {
entity_id: string[];
@@ -27,55 +24,3 @@ export const computeGroupDomain = (
];
return uniqueDomains.length === 1 ? uniqueDomains[0] : undefined;
};
/** Member entity IDs of a group, or undefined if it is not a group. */
export const computeGroupMemberIds = (
stateObj: HassEntity,
entry?: Pick<ExtEntityRegistryEntry, "capabilities"> | null
): string[] | undefined => {
const ids =
entry?.capabilities?.group_entities ??
stateObj.attributes.group_entities ??
stateObj.attributes.entity_id;
return Array.isArray(ids) ? ids : undefined;
};
/**
* Drops groups that have a member in `entityIds`, at any depth (a hidden
* group in between still counts). A group with no listed member stays, so
* hiding its bulbs doesn't read "All off".
*/
export const filterGroupsWithListedMembers = (
entityIds: string[],
states: HassEntities
): string[] => {
const listed = new Set(entityIds);
const hasListedDescendant = (groupId: string): boolean => {
const seen = new Set([groupId]);
const queue = [groupId];
while (queue.length) {
const stateObj = states[queue.shift()!];
for (const memberId of (stateObj && computeGroupMemberIds(stateObj)) ??
[]) {
if (seen.has(memberId)) {
continue;
}
if (listed.has(memberId)) {
return true;
}
seen.add(memberId);
queue.push(memberId);
}
}
return false;
};
return entityIds.filter((entityId) => {
if (!hasListedDescendant(entityId)) {
return true;
}
// A dropped group no longer counts as listed, so of two groups that
// contain each other one still stays.
listed.delete(entityId);
return false;
});
};
-15
View File
@@ -60,18 +60,3 @@ export const validateHassioSession = async (
): Promise<void> => {
await hass.callWS({ type: "supervisor/ingress/validate_session", session });
};
// Extends the session, or replaces it with a new one for the app if it has
// expired. Returns the session to keep using.
export const refreshHassioSession = async (
hass: Pick<HomeAssistant, "callWS">,
slug: string,
session: string
): Promise<string> => {
try {
await validateHassioSession(hass, session);
return session;
} catch (_err: any) {
return createHassioSession(hass, slug);
}
};
+5 -5
View File
@@ -6,7 +6,7 @@ import type { LocalizeFunc } from "../common/translations/localize";
import { showEnterCodeDialog } from "../dialogs/enter-code/show-enter-code-dialog";
import type { HomeAssistant } from "../types";
import { UNAVAILABLE } from "./entity/entity";
import { getExtendedEntityRegistryEntry } from "./entity/entity_registry";
import type { ExtEntityRegistryEntry } from "./entity/entity_registry";
export enum LockEntityFeature {
OPEN = 1,
@@ -88,10 +88,10 @@ export const callProtectedLockService = async (
service: ProtectedLockService
) => {
let code: string | undefined;
const lockRegistryEntry = await getExtendedEntityRegistryEntry(
callWS,
stateObj.entity_id
).catch(() => undefined);
const lockRegistryEntry = await callWS<ExtEntityRegistryEntry>({
type: "config/entity_registry/get",
entity_id: stateObj.entity_id,
}).catch(() => undefined);
const defaultCode = lockRegistryEntry?.options?.lock?.default_code;
if (stateObj!.attributes.code_format && !defaultCode) {
+19 -28
View File
@@ -20,7 +20,7 @@ import {
registriesContext,
uiContext,
} from "./context";
import type { HomeAssistant, HomeAssistantRegistries } from "../types";
import type { HomeAssistant } from "../types";
/**
* Reactive controller that keeps `NavigationPathInfo` in sync with a
@@ -45,8 +45,19 @@ export class NavigationPathInfoController extends ContextController {
})
private _panels?: HomeAssistant["panels"];
@consumeContext({ context: registriesContext, subscribe: true })
private _registries?: HomeAssistantRegistries | null;
@consumeContext({
context: registriesContext,
subscribe: true,
transform: ({ areas }) => areas,
})
private _areas?: HomeAssistant["areas"];
@consumeContext({
context: registriesContext,
subscribe: true,
transform: ({ devices }) => devices,
})
private _devices?: HomeAssistant["devices"];
@consumeContext({
context: configContext,
@@ -68,8 +79,6 @@ export class NavigationPathInfoController extends ContextController {
private _path?: string;
private _resolvedInputs?: unknown[];
get info(): NavigationPathInfo {
return this._info;
}
@@ -88,31 +97,13 @@ export class NavigationPathInfoController extends ContextController {
this._unsubscribe();
}
// The resolved info depends on every consumed value, so re-resolve.
protected contextUpdated(): void {
const inputs = this._inputs();
if (
this._resolvedInputs &&
inputs.every((value, i) => value === this._resolvedInputs![i])
) {
return;
}
this._resolve();
}
private _inputs(): unknown[] {
return [
this._localize,
this._panels,
this._registries?.areas,
this._registries?.devices,
this._config,
this._connection,
];
}
private _resolve(): void {
this._unsubscribe();
this._resolvedInputs = this._inputs();
if (!this._path) {
if (this._info !== DEFAULT_NAVIGATION_PATH_INFO) {
@@ -125,8 +116,8 @@ export class NavigationPathInfoController extends ContextController {
if (
!this._localize ||
!this._panels ||
!this._registries?.areas ||
!this._registries.devices ||
!this._areas ||
!this._devices ||
!this._config ||
!this._connection
) {
@@ -137,8 +128,8 @@ export class NavigationPathInfoController extends ContextController {
{
localize: this._localize,
panels: this._panels,
areas: this._registries.areas,
devices: this._registries.devices,
areas: this._areas,
devices: this._devices,
config: this._config,
connection: this._connection,
},
+1 -1
View File
@@ -349,7 +349,7 @@ export const statisticsMetaHasType = (
};
export const adjustStatisticsSum = (
hass: HomeAssistant,
hass: Pick<HomeAssistant, "callWS">,
statistic_id: string,
start_time: number,
adjustment: number,
+7 -13
View File
@@ -364,25 +364,19 @@ const getWeatherExtrema = (
if (new Date(fc.datetime).getDate() !== today) {
break;
}
if (fc.temperature == null) {
continue;
}
if (tempHigh === undefined || fc.temperature > tempHigh) {
if (!tempHigh || fc.temperature > tempHigh) {
tempHigh =
temperatureFractionDigits === undefined
? fc.temperature
: round(fc.temperature, temperatureFractionDigits);
}
if (fc.templow != null && (tempLow === undefined || fc.templow < tempLow)) {
if (fc.templow !== undefined && (!tempLow || fc.templow < tempLow)) {
tempLow =
temperatureFractionDigits === undefined
? fc.templow
: round(fc.templow, temperatureFractionDigits);
}
if (
fc.templow == null &&
(tempLow === undefined || fc.temperature < tempLow)
) {
if (!fc.templow && (!tempLow || fc.temperature < tempLow)) {
tempLow =
temperatureFractionDigits === undefined
? fc.temperature
@@ -390,19 +384,19 @@ const getWeatherExtrema = (
}
}
if (tempLow === undefined && tempHigh === undefined) {
if (!tempLow && !tempHigh) {
return undefined;
}
return html`
${
tempHigh !== undefined
tempHigh
? formatEntityAttributeValue(stateObj, "temperature", tempHigh)
: ""
}
${tempLow !== undefined && tempHigh !== undefined ? " / " : ""}
${tempLow && tempHigh ? " / " : ""}
${
tempLow !== undefined
tempLow
? formatEntityAttributeValue(stateObj, "temperature", tempLow)
: ""
}
@@ -19,7 +19,7 @@ export const fetchEntityConfigFlow = async (
if (!entities || !(entityId in entities)) {
return undefined;
}
const regEntry = await getExtendedEntityRegistryEntry(api.callWS, entityId);
const regEntry = await getExtendedEntityRegistryEntry(api, entityId);
if (!regEntry.config_entry_id) {
return undefined;
}
@@ -1,168 +0,0 @@
import { mdiArrowBottomLeft, mdiArrowTopRight, mdiStop } from "@mdi/js";
import { LitElement, css, html, 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 {
computeCloseIcon,
computeOpenIcon,
} from "../../../../common/entity/cover_icon";
import { supportsFeature } from "../../../../common/entity/supports-feature";
import type {
LocalizeFunc,
LocalizeKeys,
} from "../../../../common/translations/localize";
import "../../../../components/ha-control-button";
import "../../../../components/ha-svg-icon";
import type {
CoverAction,
CoverControlMode,
CoverEntity,
} from "../../../../data/cover";
import {
CoverEntityFeature,
canClose,
canCloseTilt,
canOpen,
canOpenTilt,
canStop,
canStopTilt,
} from "../../../../data/cover";
interface CoverButton {
action: CoverAction;
feature: CoverEntityFeature;
icon: (stateObj: CoverEntity) => string;
label: LocalizeKeys;
enabled: (stateObj: CoverEntity) => boolean;
}
const BUTTONS: Record<CoverControlMode, CoverButton[]> = {
position: [
{
action: "open",
feature: CoverEntityFeature.OPEN,
icon: computeOpenIcon,
label: "ui.card.cover.open_cover",
enabled: canOpen,
},
{
action: "stop",
feature: CoverEntityFeature.STOP,
icon: () => mdiStop,
label: "ui.card.cover.stop_cover",
enabled: canStop,
},
{
action: "close",
feature: CoverEntityFeature.CLOSE,
icon: computeCloseIcon,
label: "ui.card.cover.close_cover",
enabled: canClose,
},
],
tilt: [
{
action: "open",
feature: CoverEntityFeature.OPEN_TILT,
icon: () => mdiArrowTopRight,
label: "ui.card.cover.open_tilt_cover",
enabled: canOpenTilt,
},
{
action: "stop",
feature: CoverEntityFeature.STOP_TILT,
icon: () => mdiStop,
label: "ui.card.cover.stop_cover",
enabled: canStopTilt,
},
{
action: "close",
feature: CoverEntityFeature.CLOSE_TILT,
icon: () => mdiArrowBottomLeft,
label: "ui.card.cover.close_tilt_cover",
enabled: canCloseTilt,
},
],
};
@customElement("ha-more-info-cover-buttons")
export class HaMoreInfoCoverButtons extends LitElement {
@property({ attribute: false }) public stateObj!: CoverEntity;
@property({ attribute: false }) public mode: CoverControlMode = "position";
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
private _handleClick(ev: Event) {
const action = (ev.currentTarget as HTMLElement).dataset
.action as CoverAction;
fireEvent(this, "cover-command", { mode: this.mode, action });
}
protected render() {
if (!this.stateObj) {
return nothing;
}
const stateObj = this.stateObj;
const buttons = BUTTONS[this.mode].filter((button) =>
supportsFeature(stateObj, button.feature)
);
if (!buttons.length) {
return nothing;
}
return html`
${buttons.map(
(button) => html`
<ha-control-button
.label=${this._localize(button.label)}
.disabled=${!button.enabled(stateObj)}
data-action=${button.action}
@click=${this._handleClick}
>
<div class="content">
<ha-svg-icon .path=${button.icon(stateObj)}></ha-svg-icon>
<span>
${this._localize(
`ui.dialogs.more_info_control.cover.${button.action}`
)}
</span>
</div>
</ha-control-button>
`
)}
`;
}
static styles = css`
:host {
display: flex;
justify-content: center;
gap: var(--ha-space-3);
width: 100%;
}
ha-control-button {
flex: 1;
max-width: 104px;
height: 64px;
--control-button-border-radius: var(--ha-border-radius-xl);
--mdc-icon-size: 22px;
}
.content {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--ha-space-1);
font-size: var(--ha-font-size-s);
font-weight: var(--ha-font-weight-medium);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-more-info-cover-buttons": HaMoreInfoCoverButtons;
}
}
@@ -8,14 +8,14 @@ import { consumeLocalize } from "../../../../common/decorators/consume-context-e
import { transform } from "../../../../common/decorators/transform";
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
import { fireEvent } from "../../../../common/dom/fire_event";
import { clamp } from "../../../../common/number/clamp";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import "../../../../components/ha-control-button";
import { apiContext, configContext } from "../../../../data/context";
import type { CoverControlMode, CoverEntity } from "../../../../data/cover";
import type { CoverEntity } from "../../../../data/cover";
import {
DEFAULT_COVER_FAVORITE_POSITIONS,
coverCurrentValue,
coverSupportsPosition,
coverSupportsTiltPosition,
} from "../../../../data/cover";
import { normalizeFavoritePositions } from "../../../../data/favorite_positions";
import { UNAVAILABLE } from "../../../../data/entity/entity";
@@ -37,6 +37,8 @@ import {
import "../ha-more-info-favorites";
import type { HaMoreInfoFavorites } from "../ha-more-info-favorites";
type FavoriteKind = "position" | "tilt";
type FavoriteLocalizeKey =
| "set"
| "edit"
@@ -48,10 +50,8 @@ type FavoriteLocalizeKey =
| "edit_title"
| "add_title";
const OPTION_KEYS = {
position: "favorite_positions",
tilt: "favorite_tilt_positions",
} as const satisfies Record<CoverControlMode, keyof CoverEntityOptions>;
const favoriteKindFromEvent = (ev: Event): FavoriteKind =>
(ev.currentTarget as HTMLElement).dataset.kind as FavoriteKind;
@customElement("ha-more-info-cover-favorite-positions")
export class HaMoreInfoCoverFavoritePositions extends LitElement {
@@ -76,70 +76,145 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
@property({ attribute: false }) public editMode?: boolean;
@property({ attribute: false }) public mode: CoverControlMode = "position";
@state() private _favoritePositions: number[] = [];
@state() private _favorites: number[] = [];
@state() private _favoriteTiltPositions: number[] = [];
protected willUpdate(changedProps: PropertyValues<this>): void {
if (changedProps.has("entry") || changedProps.has("mode")) {
this._favorites = normalizeFavoritePositions(
this.entry?.options?.cover?.[OPTION_KEYS[this.mode]] ??
DEFAULT_COVER_FAVORITE_POSITIONS
);
protected updated(changedProps: PropertyValues<this>): void {
if (
(changedProps.has("entry") || changedProps.has("stateObj")) &&
this.entry &&
this.stateObj
) {
const options = this.entry.options?.cover;
this._favoritePositions = coverSupportsPosition(this.stateObj)
? normalizeFavoritePositions(
options?.favorite_positions ?? DEFAULT_COVER_FAVORITE_POSITIONS
)
: [];
this._favoriteTiltPositions = coverSupportsTiltPosition(this.stateObj)
? normalizeFavoritePositions(
options?.favorite_tilt_positions ?? DEFAULT_COVER_FAVORITE_POSITIONS
)
: [];
}
}
private _localizeFavorite(
kind: FavoriteKind,
key: FavoriteLocalizeKey,
values?: Record<string, string | number>
): string {
return this._localize(
`ui.dialogs.more_info_control.cover.${this.mode === "position" ? "favorite_position" : "favorite_tilt_position"}.${key}`,
`ui.dialogs.more_info_control.cover.${kind === "position" ? "favorite_position" : "favorite_tilt_position"}.${key}`,
values
);
}
private async _setFavorites(favorites: number[]): Promise<void> {
private _getFavorites(kind: FavoriteKind): number[] {
return kind === "position"
? this._favoritePositions
: this._favoriteTiltPositions;
}
private _getCurrentValue(kind: FavoriteKind): number | undefined {
const current =
kind === "position"
? this.stateObj.attributes.current_position
: this.stateObj.attributes.current_tilt_position;
return current == null ? undefined : current;
}
private async _save(options: CoverEntityOptions): Promise<void> {
if (!this.entry) {
return;
}
const normalized = normalizeFavoritePositions(favorites);
this._favorites = normalized;
const currentOptions: CoverEntityOptions = {
...(this.entry.options?.cover ?? {}),
};
if (coverSupportsPosition(this.stateObj)) {
currentOptions.favorite_positions = this._favoritePositions;
}
if (coverSupportsTiltPosition(this.stateObj)) {
currentOptions.favorite_tilt_positions = this._favoriteTiltPositions;
}
const result = await updateEntityRegistryEntry(
this._api.callWS,
this.entry.entity_id,
{
options_domain: "cover",
options: {
...this.entry.options?.cover,
[OPTION_KEYS[this.mode]]: normalized,
...currentOptions,
...options,
},
}
);
fireEvent(this, "entity-entry-updated", result.entity_entry);
}
private _applyFavorite(index: number): void {
const favorite = this._favorites[index];
private async _setFavorites(
kind: FavoriteKind,
favorites: number[]
): Promise<void> {
const normalized = normalizeFavoritePositions(favorites);
if (kind === "position") {
this._favoritePositions = normalized;
await this._save({ favorite_positions: normalized });
return;
}
this._favoriteTiltPositions = normalized;
await this._save({ favorite_tilt_positions: normalized });
}
private _move(kind: FavoriteKind, index: number, newIndex: number): void {
const favorites = this._getFavorites(kind).concat();
const moved = favorites.splice(index, 1)[0];
favorites.splice(newIndex, 0, moved);
this._setFavorites(kind, favorites);
}
private _applyFavorite(kind: FavoriteKind, index: number): void {
const favorite = this._getFavorites(kind)[index];
if (favorite === undefined) {
return;
}
fireEvent(this, "cover-command", {
mode: this.mode,
action: "set",
value: favorite,
if (kind === "position") {
this._api.callService("cover", "set_cover_position", {
entity_id: this.stateObj.entity_id,
position: favorite,
});
return;
}
this._api.callService("cover", "set_cover_tilt_position", {
entity_id: this.stateObj.entity_id,
tilt_position: favorite,
});
}
private async _promptFavoriteValue(
kind: FavoriteKind,
value?: number
): Promise<number | undefined> {
const response = await showPromptDialog(this, {
title: this._localizeFavorite(
kind,
value === undefined ? "add_title" : "edit_title"
),
inputLabel: this._localize(
this.mode === "position"
kind === "position"
? "ui.card.cover.position"
: "ui.card.cover.tilt_position"
),
@@ -160,56 +235,76 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
return undefined;
}
return clamp(number, 0, 100);
return Math.max(0, Math.min(100, number));
}
private async _addFavorite(): Promise<void> {
const value = await this._promptFavoriteValue();
private async _addFavorite(kind: FavoriteKind): Promise<void> {
const value = await this._promptFavoriteValue(kind);
if (value === undefined) {
return;
}
await this._setFavorites([...this._favorites, value]);
await this._setFavorites(kind, [...this._getFavorites(kind), value]);
}
private async _editFavorite(index: number): Promise<void> {
const current = this._favorites[index];
private async _editFavorite(
kind: FavoriteKind,
index: number
): Promise<void> {
const favorites = this._getFavorites(kind);
const current = favorites[index];
if (current === undefined) {
return;
}
const value = await this._promptFavoriteValue(current);
const value = await this._promptFavoriteValue(kind, current);
if (value === undefined) {
return;
}
const updated = [...this._favorites];
const updated = [...favorites];
updated[index] = value;
await this._setFavorites(updated);
await this._setFavorites(kind, updated);
}
private async _deleteFavorite(index: number): Promise<void> {
private async _deleteFavorite(
kind: FavoriteKind,
index: number
): Promise<void> {
const confirmed = await showConfirmationDialog(this, {
destructive: true,
title: this._localizeFavorite("delete_confirm_title"),
text: this._localizeFavorite("delete_confirm_text"),
confirmText: this._localizeFavorite("delete_confirm_action"),
title: this._localizeFavorite(kind, "delete_confirm_title"),
text: this._localizeFavorite(kind, "delete_confirm_text"),
confirmText: this._localizeFavorite(kind, "delete_confirm_action"),
});
if (!confirmed) {
return;
}
await this._setFavorites(
this._favorites.filter((_, itemIndex) => itemIndex !== index)
kind,
this._getFavorites(kind).filter((_, itemIndex) => itemIndex !== index)
);
}
private _favoriteButtonRenderer(): HaMoreInfoFavorites["renderItem"] {
return (favorite, _index, editMode) => {
const active = coverCurrentValue(this.stateObj, this.mode) === favorite;
const label = this._localizeFavorite(editMode ? "edit" : "set", {
private _renderFavoriteButton =
(kind: FavoriteKind): HaMoreInfoFavorites["renderItem"] =>
(favorite, _index, editMode) => {
const currentValue = this._getCurrentValue(kind);
const active = currentValue === favorite;
const label = this._localizeFavorite(kind, editMode ? "edit" : "set", {
value: `${favorite as number}%`,
});
return html`
<ha-control-button
class=${classMap({ active })}
class=${classMap({
active,
})}
style=${styleMap({
"--control-button-border-radius": "var(--ha-border-radius-pill)",
width: "72px",
@@ -222,15 +317,20 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
</ha-control-button>
`;
};
}
private _deleteLabel: HaMoreInfoFavorites["deleteLabel"] = (index) =>
this._localizeFavorite("delete", { number: index + 1 });
private _deleteLabel =
(kind: FavoriteKind): HaMoreInfoFavorites["deleteLabel"] =>
(index) =>
this._localizeFavorite(kind, "delete", {
number: index + 1,
});
private _handleFavoriteAction(
private _handleFavoriteAction = (
ev: HASSDomEvent<HASSDomEvents["favorite-item-action"]>
): void {
): void => {
ev.stopPropagation();
const kind = favoriteKindFromEvent(ev);
const { action, index } = ev.detail;
if (action === "hold" && this._user?.is_admin) {
@@ -239,87 +339,158 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
}
if (this.editMode) {
this._editFavorite(index);
this._editFavorite(kind, index);
return;
}
this._applyFavorite(index);
}
this._applyFavorite(kind, index);
};
private _handleFavoriteMoved(
private _handleFavoriteMoved = (
ev: HASSDomEvent<HASSDomEvents["favorite-item-moved"]>
): void {
): void => {
ev.stopPropagation();
const favorites = [...this._favorites];
const [moved] = favorites.splice(ev.detail.oldIndex, 1);
favorites.splice(ev.detail.newIndex, 0, moved);
this._setFavorites(favorites);
}
const kind = favoriteKindFromEvent(ev);
this._move(kind, ev.detail.oldIndex, ev.detail.newIndex);
};
private _handleFavoriteDelete(
private _handleFavoriteDelete = (
ev: HASSDomEvent<HASSDomEvents["favorite-item-delete"]>
): void {
): void => {
ev.stopPropagation();
this._deleteFavorite(ev.detail.index);
}
const kind = favoriteKindFromEvent(ev);
this._deleteFavorite(kind, ev.detail.index);
};
private _handleFavoriteAdd(
private _handleFavoriteAdd = (
ev: HASSDomEvent<HASSDomEvents["favorite-item-add"]>
): void {
): void => {
ev.stopPropagation();
this._addFavorite();
}
const kind = favoriteKindFromEvent(ev);
this._addFavorite(kind);
};
private _handleFavoriteDone(
private _handleFavoriteDone = (
ev: HASSDomEvent<HASSDomEvents["favorite-item-done"]>
): void {
): void => {
ev.stopPropagation();
fireEvent(this, "toggle-edit-mode", false);
};
private _renderKindSection(
kind: FavoriteKind,
label: string,
favorites: number[],
showDone: boolean,
showLabel: boolean
): TemplateResult | typeof nothing {
if (!this.editMode && favorites.length === 0) {
return nothing;
}
return html`
<section class="group">
${showLabel ? html`<h4>${label}</h4>` : nothing}
<ha-more-info-favorites
data-kind=${kind}
.items=${favorites}
.renderItem=${this._renderFavoriteButton(kind)}
.deleteLabel=${this._deleteLabel(kind)}
.editMode=${this.editMode ?? false}
.disabled=${this.stateObj.state === UNAVAILABLE}
.isAdmin=${Boolean(this._user?.is_admin)}
.showDone=${showDone}
.addLabel=${this._localizeFavorite(kind, "add")}
.doneLabel=${this._localize(
"ui.dialogs.more_info_control.exit_edit_mode"
)}
@favorite-item-action=${this._handleFavoriteAction}
@favorite-item-moved=${this._handleFavoriteMoved}
@favorite-item-delete=${this._handleFavoriteDelete}
@favorite-item-add=${this._handleFavoriteAdd}
@favorite-item-done=${this._handleFavoriteDone}
></ha-more-info-favorites>
</section>
`;
}
protected render(): TemplateResult | typeof nothing {
if (!this.stateObj || !this.entry) {
return nothing;
}
if (!this.editMode && this._favorites.length === 0) {
return nothing;
}
const supportsPosition = coverSupportsPosition(this.stateObj);
const supportsTiltPosition = coverSupportsTiltPosition(this.stateObj);
const showPositionSection = supportsPosition
? this.editMode || this._favoritePositions.length > 0
: false;
const showTiltSection = supportsTiltPosition
? this.editMode || this._favoriteTiltPositions.length > 0
: false;
const showLabels =
[showPositionSection, showTiltSection].filter(Boolean).length > 1;
const showDoneOnPosition = supportsPosition && !supportsTiltPosition;
return html`
<ha-more-info-favorites
.items=${this._favorites}
.renderItem=${this._favoriteButtonRenderer()}
.deleteLabel=${this._deleteLabel}
.editMode=${this.editMode ?? false}
.disabled=${this.stateObj.state === UNAVAILABLE}
.isAdmin=${Boolean(this._user?.is_admin)}
.showDone=${true}
.addLabel=${this._localizeFavorite("add")}
.doneLabel=${this._localize(
"ui.dialogs.more_info_control.exit_edit_mode"
)}
@favorite-item-action=${this._handleFavoriteAction}
@favorite-item-moved=${this._handleFavoriteMoved}
@favorite-item-delete=${this._handleFavoriteDelete}
@favorite-item-add=${this._handleFavoriteAdd}
@favorite-item-done=${this._handleFavoriteDone}
></ha-more-info-favorites>
<div class="groups">
${
supportsPosition
? this._renderKindSection(
"position",
this._localize("ui.card.cover.position"),
this._favoritePositions,
showDoneOnPosition,
showLabels
)
: nothing
}
${
supportsTiltPosition
? this._renderKindSection(
"tilt",
this._localize("ui.card.cover.tilt_position"),
this._favoriteTiltPositions,
true,
showLabels
)
: nothing
}
</div>
`;
}
static styles = css`
:host {
display: flex;
justify-content: center;
display: block;
width: 100%;
}
ha-more-info-favorites {
.groups {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--ha-space-3);
}
.group {
width: 100%;
max-width: 384px;
margin: 0;
}
.group ha-more-info-favorites {
--favorite-items-max-width: 384px;
--favorite-item-active-background-color: var(--state-cover-active-color);
}
h4 {
margin: 0 0 var(--ha-space-2);
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
font-weight: var(--ha-font-weight-medium);
text-align: center;
}
`;
}
@@ -1,7 +1,6 @@
import type { TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { consume } from "../../../common/decorators/consume";
import "../../../components/ha-absolute-time";
import "../../../components/ha-relative-time";
@@ -20,10 +19,6 @@ export class HaMoreInfoStateHeader extends LitElement {
@property({ attribute: false }) public changedOverride?: number;
@property({ attribute: false }) public changedTextOverride?: string;
@property({ attribute: false }) public stateAccent = false;
@state() private _absoluteTime = false;
@state()
@@ -56,41 +51,30 @@ export class HaMoreInfoStateHeader extends LitElement {
const stateDisplay = this.stateOverride ?? this._localizeState();
return html`
<p class=${classMap({ state: true, accent: this.stateAccent })}>
${stateDisplay}
</p>
<p class="state">${stateDisplay}</p>
<div class="time-row">
${
this.changedTextOverride
? html`<p class="last-changed secondary" aria-hidden="true">
${this.changedTextOverride}
</p>`
: html`<p class="last-changed" @click=${this._toggleAbsolute}>
${
this._absoluteTime
? html`
<ha-absolute-time
.datetime=${
this.changedOverride ?? this.stateObj.last_changed
}
></ha-absolute-time>
`
: html`
<ha-relative-time
.datetime=${
this.changedOverride ?? this.stateObj.last_changed
}
capitalize
></ha-relative-time>
`
}
</p>`
}
<p class="last-changed" @click=${this._toggleAbsolute}>
${
this._absoluteTime
? html`
<ha-absolute-time
.datetime=${
this.changedOverride ?? this.stateObj.last_changed
}
></ha-absolute-time>
`
: html`
<ha-relative-time
.datetime=${
this.changedOverride ?? this.stateObj.last_changed
}
capitalize
></ha-relative-time>
`
}
</p>
<slot name="after-time"></slot>
</div>
<span class="visually-hidden" aria-live="polite"
>${this.changedTextOverride ?? ""}</span
>
`;
}
@@ -129,22 +113,6 @@ export class HaMoreInfoStateHeader extends LitElement {
user-select: none;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.visually-hidden {
position: absolute;
overflow: hidden;
clip: rect(0 0 0 0);
height: 1px;
width: 1px;
margin: -1px;
padding: 0;
border: 0;
}
.state.accent {
color: var(--primary-color);
}
.last-changed.secondary {
cursor: default;
}
`;
}
@@ -22,7 +22,7 @@ export class HaMoreInfoViewVacuumCleanAreasHeaderAction extends LitElement {
if (!this.params.entityId || !this.hass.user?.is_admin) return;
try {
const entry = await getExtendedEntityRegistryEntry(
this.hass.callWS,
this.hass,
this.params.entityId
);
const areaMapping = entry?.options?.vacuum?.area_mapping;
@@ -56,10 +56,7 @@ export class HaMoreInfoViewVacuumCleanAreas extends LitElement {
try {
const entry: ExtEntityRegistryEntry =
await getExtendedEntityRegistryEntry(
this.hass.callWS,
this.params.entityId
);
await getExtendedEntityRegistryEntry(this.hass, this.params.entityId);
const areaMapping = entry?.options?.vacuum?.area_mapping || {};
const mappedAreaIds = new Set(Object.keys(areaMapping));
@@ -50,7 +50,7 @@ export class HaMoreInfoViewVacuumSegmentMapping extends LitElement {
if (!this.params.entityId) return;
this._entry = await getExtendedEntityRegistryEntry(
this.hass.callWS,
this.hass,
this.params.entityId
);
+139 -172
View File
@@ -1,46 +1,36 @@
import { mdiAngleAcute, mdiArrowUpDown } from "@mdi/js";
import { mdiMenu, mdiSwapVertical } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { supportsFeature } from "../../../common/entity/supports-feature";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-icon-button-group";
import "../../../components/ha-icon-button-toggle";
import { apiContext, formattersContext } from "../../../data/context";
import type {
CoverCommand,
CoverControlMode,
CoverDrag,
CoverEntity,
} from "../../../data/cover";
import { formattersContext } from "../../../data/context";
import {
coverCommandData,
coverCommandService,
coverCurrentValue,
coverHasPositionControls,
coverHasTiltControls,
coverModeAttribute,
shouldShowFavoriteOptions,
type ExtEntityRegistryEntry,
} from "../../../data/entity/entity_registry";
import type { CoverEntity } from "../../../data/cover";
import {
CoverEntityFeature,
coverSupportsAnyPosition,
coverSupportsPosition,
coverSupportsSetValue,
defaultCoverMode,
coverSupportsTiltPosition,
computeCoverPositionStateDisplay,
} from "../../../data/cover";
import type { ExtEntityRegistryEntry } from "../../../data/entity/entity_registry";
import { CoverRequestController } from "../../../state-control/cover/cover-request-controller";
import "../../../state-control/cover/ha-state-control-cover";
import type { HomeAssistantApi, HomeAssistantFormatters } from "../../../types";
import "../components/covers/ha-more-info-cover-buttons";
import "../../../state-control/cover/ha-state-control-cover-buttons";
import "../../../state-control/cover/ha-state-control-cover-position";
import "../../../state-control/cover/ha-state-control-cover-tilt-position";
import "../../../state-control/cover/ha-state-control-cover-toggle";
import type { HomeAssistantFormatters } from "../../../types";
import "../components/covers/ha-more-info-cover-favorite-positions";
import "../components/ha-more-info-state-header";
import { moreInfoControlStyle } from "../components/more-info-control-style";
type CoverHintKey =
| "requested"
| "requested_open"
| "requested_closed"
| "currently"
| "currently_unknown";
type Mode = "position" | "button";
@customElement("more-info-cover")
class MoreInfoCover extends LitElement {
@@ -52,176 +42,159 @@ class MoreInfoCover extends LitElement {
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
@property({ attribute: false }) public stateObj?: CoverEntity;
@property({ attribute: false }) public entry?: ExtEntityRegistryEntry | null;
@property({ attribute: false }) public editMode?: boolean;
@state() private _mode: CoverControlMode = "position";
@state() private _mode?: Mode;
@state() private _drag?: CoverDrag;
private _requests = new CoverRequestController(this);
private _setMode(ev) {
this._mode = ev.currentTarget.mode;
}
protected willUpdate(changedProps: PropertyValues<this>): void {
super.willUpdate(changedProps);
if (!changedProps.has("stateObj") || !this.stateObj) {
return;
if (changedProps.has("stateObj") && this.stateObj) {
const entityId = this.stateObj.entity_id;
const oldEntityId = changedProps.get("stateObj")?.entity_id;
if (!this._mode || entityId !== oldEntityId) {
this._mode = coverSupportsAnyPosition(this.stateObj)
? "position"
: "button";
}
}
if (changedProps.get("stateObj")?.entity_id !== this.stateObj.entity_id) {
this._mode = defaultCoverMode(this.stateObj);
this._requests.clear();
this._drag = undefined;
return;
}
this._requests.stateChanged(this.stateObj);
}
private _setMode(ev: Event) {
this._mode = (ev.currentTarget as HTMLElement).dataset
.mode as CoverControlMode;
}
private get _stateOverride() {
const stateDisplay = this._formatters.formatEntityState(this.stateObj!);
private _handleCommand(ev: HASSDomEvent<CoverCommand>) {
ev.stopPropagation();
const stateObj = this.stateObj!;
const command = ev.detail;
this._api
.callService(
"cover",
coverCommandService(command),
coverCommandData(stateObj, command)
)
.catch(() => this._requests.clear());
this._requests.commandSent(command, stateObj);
}
private _handleDrag(ev: HASSDomEvent<HASSDomEvents["cover-drag-changed"]>) {
ev.stopPropagation();
this._drag = ev.detail.drag;
}
private _formatValue(mode: CoverControlMode, value: number) {
return this._formatters.formatEntityAttributeValue(
const positionStateDisplay = computeCoverPositionStateDisplay(
this.stateObj!,
coverModeAttribute(mode),
Math.round(value)
this._formatters.formatEntityAttributeValue
);
}
private _hint(key: CoverHintKey, values?: Record<string, string>) {
return this._localize(`ui.dialogs.more_info_control.cover.${key}`, values);
}
private _dragText(): string | undefined {
const drag = this._drag;
if (!drag) {
return undefined;
if (positionStateDisplay) {
return `${stateDisplay} · ${positionStateDisplay}`;
}
if (!drag.swipe) {
return this._formatValue(this._mode, drag.value);
}
if (!drag.swipe.passedHalfway) {
return undefined;
}
return this._localize(
drag.swipe.action === "close"
? "ui.dialogs.more_info_control.cover.closes_on_release"
: "ui.dialogs.more_info_control.cover.opens_on_release"
);
}
private _stateText(): string {
const stateObj = this.stateObj!;
const stateDisplay = this._formatters.formatEntityState(stateObj);
const value = Math.round(
stateObj.attributes[coverModeAttribute(this._mode)] ?? 0
);
if (value === 0) {
return stateDisplay;
}
return `${stateDisplay} · ${this._formatValue(this._mode, value)}`;
}
private _dragHint(): string | undefined {
if (!this._drag || this._drag.swipe) {
return undefined;
}
const current = coverCurrentValue(this.stateObj!, this._mode);
return current === undefined
? this._hint("currently_unknown")
: this._hint("currently", {
value: this._formatValue(this._mode, current),
});
}
private _requestHint(): string | undefined {
const request = this._requests.request;
if (!request || this._drag) {
return undefined;
}
if (request.mode === "position" && !coverSupportsPosition(this.stateObj!)) {
return this._hint(request.value ? "requested_open" : "requested_closed");
}
return this._hint("requested", {
value: this._formatValue(request.mode, request.value),
});
}
private _showFavorites(stateObj: CoverEntity): boolean {
if (!this.entry) {
return false;
}
return coverSupportsSetValue(stateObj, this._mode);
return stateDisplay;
}
protected render() {
if (!this.stateObj) {
return nothing;
}
const stateObj = this.stateObj;
const bothModes =
coverHasPositionControls(stateObj) && coverHasTiltControls(stateObj);
const dragText = this._dragText();
const supportsPosition = coverSupportsPosition(this.stateObj);
const supportsTiltPosition = coverSupportsTiltPosition(this.stateObj);
const showFavoriteControls = Boolean(
this.entry &&
(this.editMode ||
(coverSupportsPosition(this.stateObj) &&
shouldShowFavoriteOptions(
this.entry.options?.cover?.favorite_positions
)) ||
(coverSupportsTiltPosition(this.stateObj) &&
shouldShowFavoriteOptions(
this.entry.options?.cover?.favorite_tilt_positions
)))
);
const supportsOpenClose =
supportsFeature(this.stateObj, CoverEntityFeature.OPEN) ||
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE) ||
supportsFeature(this.stateObj, CoverEntityFeature.STOP);
const supportsTilt =
supportsFeature(this.stateObj, CoverEntityFeature.OPEN_TILT) ||
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE_TILT) ||
supportsFeature(this.stateObj, CoverEntityFeature.STOP_TILT);
const supportsOpenCloseOnly =
supportsFeature(this.stateObj, CoverEntityFeature.OPEN) &&
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE) &&
!supportsFeature(this.stateObj, CoverEntityFeature.STOP) &&
!supportsTilt &&
!supportsPosition &&
!supportsTiltPosition;
return html`
<ha-more-info-state-header
.stateObj=${stateObj}
.stateOverride=${dragText ?? this._stateText()}
.changedTextOverride=${this._dragHint() ?? this._requestHint()}
.stateAccent=${dragText !== undefined}
.stateObj=${this.stateObj}
.stateOverride=${this._stateOverride}
></ha-more-info-state-header>
<div
class="controls"
@cover-command=${this._handleCommand}
@cover-drag-changed=${this._handleDrag}
>
<div class="controls">
<div class="main-control">
<ha-state-control-cover
.stateObj=${stateObj}
.mode=${this._mode}
.request=${this._requests.request}
></ha-state-control-cover>
${
bothModes
this._mode === "position"
? html`
${
supportsPosition
? html`
<ha-state-control-cover-position
.stateObj=${this.stateObj}
></ha-state-control-cover-position>
`
: nothing
}
${
supportsTiltPosition
? html`
<ha-state-control-cover-tilt-position
.stateObj=${this.stateObj}
></ha-state-control-cover-tilt-position>
`
: nothing
}
`
: nothing
}
${
this._mode === "button"
? html`
${
supportsOpenCloseOnly
? html`
<ha-state-control-cover-toggle
.stateObj=${this.stateObj}
></ha-state-control-cover-toggle>
`
: supportsOpenClose || supportsTilt
? html`
<ha-state-control-cover-buttons
.stateObj=${this.stateObj}
></ha-state-control-cover-buttons>
`
: nothing
}
`
: nothing
}
</div>
${
(supportsPosition || supportsTiltPosition) &&
(supportsOpenClose || supportsTilt)
? html`
<ha-icon-button-group>
<ha-icon-button-toggle
.label=${this._localize("ui.card.cover.position")}
.label=${this._localize(
`ui.dialogs.more_info_control.cover.switch_mode.position`
)}
.selected=${this._mode === "position"}
.path=${mdiArrowUpDown}
data-mode="position"
.path=${mdiMenu}
.mode=${"position"}
@click=${this._setMode}
></ha-icon-button-toggle>
<ha-icon-button-toggle
.label=${this._localize("ui.card.cover.tilt_position")}
.selected=${this._mode === "tilt"}
.path=${mdiAngleAcute}
data-mode="tilt"
.label=${this._localize(
`ui.dialogs.more_info_control.cover.switch_mode.button`
)}
.selected=${this._mode === "button"}
.path=${mdiSwapVertical}
.mode=${"button"}
@click=${this._setMode}
></ha-icon-button-toggle>
</ha-icon-button-group>
@@ -229,18 +202,13 @@ class MoreInfoCover extends LitElement {
: nothing
}
</div>
<ha-more-info-cover-buttons
.stateObj=${stateObj}
.mode=${this._mode}
></ha-more-info-cover-buttons>
${
this._showFavorites(stateObj)
showFavoriteControls
? html`
<ha-more-info-cover-favorite-positions
.stateObj=${stateObj}
.stateObj=${this.stateObj}
.entry=${this.entry}
.editMode=${this.editMode}
.mode=${this._mode}
></ha-more-info-cover-favorite-positions>
`
: nothing
@@ -255,12 +223,11 @@ class MoreInfoCover extends LitElement {
css`
.main-control {
display: flex;
flex-direction: column;
flex-direction: row;
align-items: center;
gap: var(--ha-space-4);
}
ha-more-info-cover-buttons {
max-width: 360px;
.main-control > * {
margin: 0 var(--ha-space-2);
}
`,
];
@@ -227,7 +227,7 @@ class MoreInfoWeather extends LitElement {
.datetime=${this.stateObj.last_changed}
capitalize
></ha-relative-time>
<ha-tooltip trigger="hover focus click" for="relative-time">
<ha-tooltip for="relative-time">
<div class="row">
<span class="column-name">
${this._i18n.localize(
+1 -1
View File
@@ -217,7 +217,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
}
try {
this._entry = await getExtendedEntityRegistryEntry(
this.hass.callWS,
this.hass,
this._entityId
);
} catch (_e) {
+7 -4
View File
@@ -12,7 +12,6 @@ import { computeStateDomain } from "../../common/entity/compute_state_domain";
import { getEntityContext } from "../../common/entity/context/get_entity_context";
import "../../components/ha-badge";
import type { ExtEntityRegistryEntry } from "../../data/entity/entity_registry";
import { computeGroupMemberIds } from "../../data/group";
import { supportsCoverPositionCardFeature } from "../../panels/lovelace/card-features/hui-cover-position-card-feature";
import { supportsLightBrightnessCardFeature } from "../../panels/lovelace/card-features/hui-light-brightness-card-feature";
import { supportsLightColorCardFeature } from "../../panels/lovelace/card-features/hui-light-color-card-feature";
@@ -116,9 +115,13 @@ class MoreInfoContent extends LitElement {
return undefined;
}
return computeGroupMemberIds(stateObj, entry)?.filter(
(entityId) => !entities[entityId]?.hidden
);
const memberIds =
(entry?.capabilities?.group_entities as string[] | undefined) ??
(Array.isArray(stateObj.attributes.entity_id)
? (stateObj.attributes.entity_id as string[])
: undefined);
return memberIds?.filter((entityId) => !entities[entityId]?.hidden);
}
);
@@ -33,11 +33,7 @@ export class HuiPersistentNotificationItem extends LitElement {
.datetime=${this.notification.created_at}
capitalize
></ha-relative-time>
<ha-tooltip
trigger="hover focus click"
for="relative-time"
placement="bottom"
>
<ha-tooltip for="relative-time" placement="bottom">
${this._computeTooltip(this.hass, this.notification)}
</ha-tooltip>
</span>
+8 -51
View File
@@ -16,7 +16,7 @@ import type { IngressAppInfo } from "../../data/hassio/ingress";
import {
createHassioSession,
fetchIngressAppInfo,
refreshHassioSession,
validateHassioSession,
} from "../../data/hassio/ingress";
import {
showAlertDialog,
@@ -60,10 +60,6 @@ class HaPanelApp extends LitElement {
private _sessionKeepAlive?: number;
private _session?: { slug: string; session: string };
private _sessionRefresh?: Promise<void>;
private _fetchDataTimeout?: number;
private _autoRetryUntil?: number;
@@ -96,22 +92,17 @@ class HaPanelApp extends LitElement {
super.connectedCallback();
window.addEventListener("message", this._handleIframeMessage);
window.addEventListener("resize", this._handleResize);
document.addEventListener("visibilitychange", this._handleVisibility);
document.addEventListener("resume", this._handleVisibility);
}
public disconnectedCallback() {
super.disconnectedCallback();
window.removeEventListener("message", this._handleIframeMessage);
window.removeEventListener("resize", this._handleResize);
document.removeEventListener("visibilitychange", this._handleVisibility);
document.removeEventListener("resume", this._handleVisibility);
if (this._sessionKeepAlive) {
clearInterval(this._sessionKeepAlive);
this._sessionKeepAlive = undefined;
}
this._session = undefined;
if (this._fetchDataTimeout) {
clearTimeout(this._fetchDataTimeout);
this._fetchDataTimeout = undefined;
@@ -351,51 +342,17 @@ class HaPanelApp extends LitElement {
if (this._sessionKeepAlive) {
clearInterval(this._sessionKeepAlive);
}
this._session = { slug: addonSlug, session };
this._sessionKeepAlive = window.setInterval(this._refreshSession, 60000);
this._sessionKeepAlive = window.setInterval(async () => {
try {
await validateHassioSession(this.hass, session);
} catch (_err: any) {
session = await createHassioSession(this.hass, addonSlug);
}
}, 60000);
this._addon = addon;
}
// The keep-alive timer does not run while the device sleeps, so the session
// may have expired by the time the page is visible again. Refresh it right
// away instead of leaving the app unreachable until the next tick.
// "resume" only fires in Chromium after a frozen page, other browsers rely
// on "visibilitychange".
private _handleVisibility = () => {
if (!document.hidden) {
this._refreshSession();
}
};
private _refreshSession = (): Promise<void> => {
const current = this._session;
if (!current) {
return Promise.resolve();
}
if (this._sessionRefresh) {
return this._sessionRefresh;
}
this._sessionRefresh = refreshHassioSession(
this.hass,
current.slug,
current.session
)
.then((session) => {
// the panel may have switched to another app meanwhile
if (this._session === current) {
this._session = { slug: current.slug, session };
}
})
.catch((_err: any) => {
// Connection to Home Assistant is gone, the next refresh will retry
})
.finally(() => {
this._sessionRefresh = undefined;
});
return this._sessionRefresh;
};
private async _checkLoaded(ev: Event): Promise<void> {
const iframe = ev.target as HTMLIFrameElement;
@@ -6,10 +6,8 @@ import { consume } from "../../../../../common/decorators/consume";
import { ensureArray } from "../../../../../common/array/ensure-array";
import { fireEvent } from "../../../../../common/dom/fire_event";
import { capitalizeFirstLetter } from "../../../../../common/string/capitalize-first-letter";
import "../../../../../components/animation/ha-fade-in";
import "../../../../../components/ha-alert";
import "../../../../../components/ha-button";
import "../../../../../components/ha-spinner";
import "../../../../../components/ha-svg-icon";
import "../../../../../components/ha-trigger-icon";
import "../../../../../components/item/ha-list-item-option";
@@ -19,7 +17,6 @@ import type { TriggerCondition } from "../../../../../data/automation";
import {
automationTriggerContext,
hasCustomTriggerId,
triggerOptionsResolved,
type AutomationTriggerContext,
type TriggerIdOption,
} from "../../trigger/automation-trigger-id";
@@ -56,33 +53,16 @@ export class HaTriggerCondition extends LitElement {
const selectedIds = (ensureArray(this.condition.id) ?? []).filter(Boolean);
const triggerIdOptions = this._triggers?.options ?? [];
const missingIds = this._missingIds(this.condition.id, triggerIdOptions);
const status = this._triggers?.blueprintStatus;
const resolved = triggerOptionsResolved(this._triggers);
if (!triggerIdOptions.length && !selectedIds.length) {
switch (status) {
case "loading":
return html`<ha-fade-in .delay=${500}>
<ha-spinner size="small"></ha-spinner>
</ha-fade-in>`;
case "failed":
return this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.blueprint_triggers_unavailable"
);
case "loaded":
return this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.blueprint_no_trigger_ids"
);
case undefined:
return this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.no_triggers"
);
}
return this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.no_triggers"
);
}
return html`
${
resolved && missingIds.length
missingIds.length
? html`<ha-alert alert-type="warning">
${this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.missing_triggers"
@@ -126,13 +106,7 @@ export class HaTriggerCondition extends LitElement {
appearance="checkbox"
>
<span slot="start" class="trigger-row-leading">
${
this._triggers?.showIndices
? html`<span class="trigger-index-badge"
>${option.index + 1}</span
>`
: nothing
}
<span class="trigger-index-badge">${option.index + 1}</span>
<ha-trigger-icon
.trigger=${
"trigger" in option.trigger ? option.trigger.trigger : ""
@@ -145,9 +119,7 @@ export class HaTriggerCondition extends LitElement {
)}
</span>
${
option.duplicate ||
hasCustomTriggerId(option) ||
!this._triggers?.showIndices
option.duplicate || hasCustomTriggerId(option)
? html`<span
slot="supporting-text"
class="trigger-id ${option.duplicate ? "duplicate" : ""}"
@@ -180,22 +152,14 @@ export class HaTriggerCondition extends LitElement {
.disabled=${this.disabled}
appearance="checkbox"
>
${
resolved
? html`<span slot="start" class="missing-trigger-badge">
<ha-svg-icon .path=${mdiLinkVariantOff}></ha-svg-icon>
<span class="missing-trigger-id">${id}</span>
</span>`
: nothing
}
<span slot="start" class="missing-trigger-badge">
<ha-svg-icon .path=${mdiLinkVariantOff}></ha-svg-icon>
<span class="missing-trigger-id">${id}</span>
</span>
<span slot="headline">
${
resolved
? this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.missing_trigger"
)
: id
}
${this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.missing_trigger"
)}
</span>
</ha-list-item-option>
`
@@ -233,7 +197,8 @@ export class HaTriggerCondition extends LitElement {
? ids
: [...ids, id]
: ids.filter((_id) => _id !== id);
if (this._triggers?.select(this.condition, selectedIds)) {
if (this._triggers) {
this._triggers.select(this.condition, selectedIds);
return;
}
fireEvent(this, "value-changed", {
@@ -146,15 +146,6 @@ export class HaAutomationEditor extends AutomationScriptEditorMixin<AutomationCo
this._manualEditor?.resetPastedConfig();
this._updateConfig(config);
},
fetchBlueprintTriggers: async ({ path, input }) => {
const result = await substituteBlueprint(
this.hass,
"automation",
path,
input || {}
);
return normalizeAutomationConfig(result.substituted_config).triggers;
},
});
private _newAutomationId?: string;
@@ -3,14 +3,11 @@ import type { LitElement, ReactiveController } from "lit";
import memoizeOne from "memoize-one";
import type {
AutomationConfig,
BlueprintAutomationConfig,
SidebarConfig,
Trigger,
TriggerCondition,
} from "../../../../data/automation";
import { ContextSubscriptionController } from "../../../../common/decorators/consume";
import { debounce } from "../../../../common/util/debounce";
import { deepEqual } from "../../../../common/util/deep-equal";
import type { LocalizeFunc } from "../../../../common/translations/localize";
import { internationalizationContext } from "../../../../data/context";
import { showConfirmationDialog } from "../../../../dialogs/generic/show-dialog-box";
@@ -19,15 +16,12 @@ import {
automationTriggerContext,
cleanupRemovedGeneratedTriggerReferences,
cleanupUnusedGeneratedTriggerIds,
getBlueprintTriggerIdOptions,
getTriggerIdOptions,
getExplicitTriggerIds,
isGeneratedTriggerId,
makeDuplicateTriggerIdsUnique,
replaceLeafTrigger,
updateTriggerCondition,
type TriggerIdOption,
type BlueprintTriggersStatus,
} from "./automation-trigger-id";
import { preserveAutomationRowKeys } from "../ha-automation-sortable-list-mixin";
@@ -37,10 +31,6 @@ interface AutomationTriggerControllerOptions {
canEdit: () => boolean;
/** Apply one complete change through the editor's undo and dirty-state handling. */
commit: (config: AutomationConfig) => void;
/** Resolve a blueprint automation's triggers, with its inputs substituted. */
fetchBlueprintTriggers: (
useBlueprint: BlueprintAutomationConfig["use_blueprint"]
) => Promise<Trigger | Trigger[] | undefined>;
}
/**
@@ -53,9 +43,6 @@ interface AutomationTriggerControllerOptions {
*
* The transformation helpers only change configuration. This controller preserves
* the corresponding row keys so an open sidebar continues to track the edited row.
*
* A blueprint automation has no triggers of its own: options come from the
* blueprint's substituted triggers, and conditions in its inputs change themselves.
*/
export class AutomationTriggerController implements ReactiveController {
// Only read in event handlers, so it does not need to rerender the host.
@@ -67,18 +54,6 @@ export class AutomationTriggerController implements ReactiveController {
// changes, so rendering and selection use the same IDs across host updates.
private _getTriggerIdOptions = memoizeOne(getTriggerIdOptions);
private _getBlueprintTriggerIdOptions = memoizeOne(
getBlueprintTriggerIdOptions
);
/** The blueprint use whose triggers were last requested. */
private _blueprintRequested?: BlueprintAutomationConfig["use_blueprint"];
private _blueprintTriggers?: Trigger | Trigger[];
/** "failed" while required inputs are empty. */
private _blueprintStatus: BlueprintTriggersStatus = "loading";
constructor(
private _host: LitElement,
private _options: AutomationTriggerControllerOptions
@@ -103,39 +78,15 @@ export class AutomationTriggerController implements ReactiveController {
_host.addController(this);
}
public hostDisconnected() {
this._fetchBlueprintTriggers.cancel();
this._blueprintRequested = undefined;
}
/** Publish options before descendants render, including after undo or redo. */
public hostUpdate() {
const config = this._options.getConfig();
if (!config) {
return;
}
let options: TriggerIdOption[];
let blueprintStatus: BlueprintTriggersStatus | undefined;
let showIndices = this._provider.value.showIndices;
if ("use_blueprint" in config && config.use_blueprint) {
this._requestBlueprintTriggers(config.use_blueprint);
options = this._getBlueprintTriggerIdOptions(this._blueprintTriggers);
blueprintStatus = this._blueprintStatus;
showIndices = false;
} else {
options = this._getTriggerIdOptions(config.triggers);
}
if (
options !== this._provider.value.options ||
blueprintStatus !== this._provider.value.blueprintStatus ||
showIndices !== this._provider.value.showIndices
) {
this._provider.setValue({
...this._provider.value,
options,
blueprintStatus,
showIndices,
});
const options = this._getTriggerIdOptions(config.triggers);
if (options !== this._provider.value.options) {
this._provider.setValue({ ...this._provider.value, options });
}
}
@@ -187,54 +138,10 @@ export class AutomationTriggerController implements ReactiveController {
return cleaned;
}
/** Request the blueprint's triggers again whenever its path or inputs change. */
private _requestBlueprintTriggers(
useBlueprint: BlueprintAutomationConfig["use_blueprint"]
) {
if (deepEqual(useBlueprint, this._blueprintRequested)) {
return;
}
if (useBlueprint.path !== this._blueprintRequested?.path) {
this._blueprintTriggers = undefined;
}
this._blueprintStatus = "loading";
this._blueprintRequested = useBlueprint;
this._fetchBlueprintTriggers(useBlueprint);
}
private _fetchBlueprintTriggers = debounce(
async (useBlueprint: BlueprintAutomationConfig["use_blueprint"]) => {
let triggers: Trigger | Trigger[] | undefined;
try {
triggers = await this._options.fetchBlueprintTriggers(useBlueprint);
} catch (_err) {
if (useBlueprint === this._blueprintRequested) {
this._blueprintStatus = "failed";
this._host.requestUpdate();
}
return;
}
if (useBlueprint !== this._blueprintRequested) {
return;
}
this._blueprintTriggers = triggers;
this._blueprintStatus = "loaded";
this._host.requestUpdate();
},
500,
true
);
private _selectTriggerIds = (
condition: TriggerCondition,
ids: string[]
): boolean => {
private _selectTriggerIds = (condition: TriggerCondition, ids: string[]) => {
const config = this._options.getConfig();
if (config && "use_blueprint" in config) {
return false;
}
if (!config || !this._options.canEdit()) {
return true;
return;
}
const triggers = assignGeneratedTriggerIds(
config.triggers,
@@ -250,7 +157,6 @@ export class AutomationTriggerController implements ReactiveController {
// Generated IDs that no condition or action references are no longer in use.
// Strip them so the YAML does not accumulate stale identifiers.
this._commit(cleanupUnusedGeneratedTriggerIds(updated));
return true;
};
private _fixDuplicateTriggerIds = async () => {
@@ -38,28 +38,13 @@ export interface TriggerIdOption {
duplicate: boolean;
}
/**
* Whether a blueprint's substituted triggers are known. While "loading" or
* "failed", options keep the last triggers fetched, if any.
*/
export type BlueprintTriggersStatus = "loaded" | "loading" | "failed";
/** Controller-provided options and operations for editors, sidebars, and row summaries. */
export interface AutomationTriggerContext {
options: TriggerIdOption[];
/**
* Left out for an automation with its own triggers. Set for a blueprint
* automation, whose missing IDs can only be flagged once "loaded".
*/
blueprintStatus?: BlueprintTriggersStatus;
/** True while the user is editing a `triggered_by` condition; trigger rows show their index badges only in this state. */
showIndices: boolean;
/**
* Pass the original condition object so identical conditions remain distinguishable.
* Return false when the condition is not one of the automation's conditions, as in
* a blueprint automation, whose conditions live in its inputs.
*/
select: (condition: TriggerCondition, ids: string[]) => boolean;
/** Pass the original condition object so identical conditions remain distinguishable. */
select: (condition: TriggerCondition, ids: string[]) => void;
/** Requests confirmation before migrating duplicate IDs throughout the automation. */
fixDuplicateIds: () => Promise<void>;
/**
@@ -69,13 +54,6 @@ export interface AutomationTriggerContext {
updateTriggerId: (original: Trigger, updated: Trigger) => boolean;
}
/** Whether options list every trigger, so an ID not among them is really missing. */
export const triggerOptionsResolved = (
context: AutomationTriggerContext | undefined
): boolean =>
context?.blueprintStatus === undefined ||
context.blueprintStatus === "loaded";
export const automationTriggerContext =
createContext<AutomationTriggerContext>("automationTriggers");
@@ -162,27 +140,6 @@ export const getTriggerIdOptions = (
});
};
/**
* Build options from a blueprint's substituted triggers. The blueprint owns its
* triggers, so only those with a stored ID can be referenced, and triggers sharing
* an ID are one option: a condition on that ID matches any of them.
*/
export const getBlueprintTriggerIdOptions = (
triggers: Trigger | Trigger[] | undefined
): TriggerIdOption[] => {
const options: TriggerIdOption[] = [];
const seenIds = new Set<string>();
flattenTriggers(triggers).forEach((trigger, index) => {
const id = getTriggerId(trigger);
if (!id || seenIds.has(id)) {
return;
}
seenIds.add(id);
options.push({ id, trigger, index, draft: false, duplicate: false });
});
return options;
};
/**
* Transform leaf triggers recursively, retaining list wrappers and scalar/array shape.
* Copy only changed branches; callbacks must return replacements rather than mutate leaves.
@@ -14,7 +14,6 @@ import type { EntityRegistryEntry } from "../../../../data/entity/entity_registr
import type { HomeAssistant } from "../../../../types";
import {
automationTriggerContext,
triggerOptionsResolved,
type AutomationTriggerContext,
} from "./automation-trigger-id";
@@ -42,7 +41,6 @@ export class HaAutomationTriggerReferences extends LitElement {
const missingIds = selectedIds.filter(
(id) => !options.some((option) => option.id === id)
);
const resolved = triggerOptionsResolved(this._triggers);
if (options.length && !selectedIds.length) {
return html`<span class="trigger-reference no-selection">
@@ -89,21 +87,17 @@ export class HaAutomationTriggerReferences extends LitElement {
</span>
`
),
missingIds.map((id) =>
resolved
? html`
<span class="trigger-reference missing">
<ha-svg-icon .path=${mdiLinkVariantOff}></ha-svg-icon>
<span>
${this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.missing_trigger"
)}
</span>
</span>
`
: html`<span class="trigger-reference">
<span class="trigger-reference-label">${id}</span>
</span>`
missingIds.map(
() => html`
<span class="trigger-reference missing">
<ha-svg-icon .path=${mdiLinkVariantOff}></ha-svg-icon>
<span>
${this.hass.localize(
"ui.panel.config.automation.editor.conditions.type.trigger.missing_trigger"
)}
</span>
</span>
`
),
];
}
@@ -333,7 +333,6 @@ class HaConfigBackupDetails extends LitElement {
margin: 0 auto;
gap: var(--ha-space-6);
display: grid;
grid-template-columns: minmax(0, 1fr);
margin-bottom: 24px;
}
.card-content {
@@ -16,13 +16,7 @@ import type {
EnergyPreferencesValidation,
EnergyValidationIssue,
} from "../../../../data/energy";
import {
getBatteryEnergyStatIds,
getBatteryFlowStatIds,
getBatteryName,
getBatteryPrimaryStat,
saveEnergyPreferences,
} from "../../../../data/energy";
import { saveEnergyPreferences } from "../../../../data/energy";
import type { StatisticsMetaData } from "../../../../data/recorder";
import { getStatisticLabel } from "../../../../data/recorder";
import {
@@ -120,10 +114,8 @@ export class EnergyBatterySettings extends LitElement {
? html`
<div class="items">
${batterySources.map((source) => {
const chargeStat =
getBatteryEnergyStatIds(source).charge[0];
const toEntityState = this.hass.states[chargeStat];
const summary = this._directionsSummary(source);
const toEntityState =
this.hass.states[source.stat_energy_to];
return html`
<ha-card outlined>
<ha-automation-row
@@ -147,20 +139,18 @@ export class EnergyBatterySettings extends LitElement {
>${this._sourceName(source)}</span
>
${
summary
? html`<span class="label secondary"
>${summary}</span
source.name
? nothing
: html`<span class="label secondary"
>${getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
source.stat_energy_to,
this.statsMetadata?.[
source.stat_energy_to
]
)}</span
>`
: source.name
? nothing
: html`<span class="label secondary"
>${getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
chargeStat,
this.statsMetadata?.[chargeStat]
)}</span
>`
}
</div>
<ha-icon-button
@@ -198,52 +188,17 @@ export class EnergyBatterySettings extends LitElement {
}
private _sourceName(source: BatterySourceTypeEnergyPreference) {
const primary = getBatteryPrimaryStat(source);
return (
getBatteryName(
this.hass.states,
this.hass.formatEntityName,
source,
this.statsMetadata
) ||
source.name ||
getStatisticLabel(
this.hass.states,
this.hass.formatEntityName,
primary,
this.statsMetadata?.[primary]
source.stat_energy_from,
this.statsMetadata?.[source.stat_energy_from]
)
);
}
private _directionsSummary(
source: BatterySourceTypeEnergyPreference
): string | undefined {
const flows = getBatteryFlowStatIds(source);
if (!flows) {
return undefined;
}
const key = "ui.panel.config.energy.battery.summary";
const charge =
flows.grid_to_battery && flows.solar_to_battery
? this.hass.localize(`${key}.charges_from_grid_and_solar`)
: flows.grid_to_battery
? this.hass.localize(`${key}.charges_from_grid`)
: flows.solar_to_battery
? this.hass.localize(`${key}.charges_from_solar`)
: undefined;
const discharge =
flows.battery_to_home && flows.battery_to_grid
? this.hass.localize(`${key}.discharges_to_home_and_grid`)
: flows.battery_to_home
? this.hass.localize(`${key}.discharges_to_home`)
: flows.battery_to_grid
? this.hass.localize(`${key}.discharges_to_grid`)
: undefined;
return charge && discharge
? this.hass.localize(`${key}.directions`, { charge, discharge })
: charge || discharge;
}
private _addSource() {
this._openEditor();
}
@@ -260,7 +215,7 @@ export class EnergyBatterySettings extends LitElement {
private _editorHref(source?: BatterySourceTypeEnergyPreference) {
return this.listPath
? `${this.listPath}/battery/${source ? encodeURIComponent(getBatteryPrimaryStat(source)) : "new"}`
? `${this.listPath}/battery/${source ? encodeURIComponent(source.stat_energy_from) : "new"}`
: undefined;
}
@@ -268,20 +223,12 @@ export class EnergyBatterySettings extends LitElement {
preferences: EnergyPreferences,
source?: BatterySourceTypeEnergyPreference
): EnergyEditorConfig {
const sources = preferences.energy_sources;
return {
kind: "battery",
params: {
statsMetadata: this.statsMetadata,
source: source ? { ...source } : undefined,
battery_sources: sources.filter(isBatterySource),
has_grid_import: sources.some(
(src) => src.type === "grid" && !!src.stat_energy_from
),
has_grid_export: sources.some(
(src) => src.type === "grid" && !!src.stat_energy_to
),
has_solar: sources.some((src) => src.type === "solar"),
battery_sources: preferences.energy_sources.filter(isBatterySource),
saveCallback: (newSource) => this._saveSource(newSource, source),
},
};
@@ -294,9 +241,9 @@ export class EnergyBatterySettings extends LitElement {
return index;
}
// Saving replaces the preferences, after which only the statistic matches
const key = getBatteryPrimaryStat(source);
return sources.findIndex(
(src) => isBatterySource(src) && getBatteryPrimaryStat(src) === key
(src) =>
isBatterySource(src) && src.stat_energy_from === source.stat_energy_from
);
}
@@ -308,7 +255,7 @@ export class EnergyBatterySettings extends LitElement {
}
const source = this.preferences.energy_sources.find(
(src): src is BatterySourceTypeEnergyPreference =>
isBatterySource(src) && getBatteryPrimaryStat(src) === key
isBatterySource(src) && src.stat_energy_from === key
);
return (
source &&
@@ -64,33 +64,9 @@ export function integralUnits(
return totalUnits.includes(unit) ? { unit_time: "h" } : undefined;
}
export interface PowerIntegral<
Energy extends string = "stat_energy_from" | "stat_energy_to",
> extends Omit<IntegralRequest, "name"> {
export interface PowerIntegral extends Omit<IntegralRequest, "name"> {
/** Energy statistic the helper provides. */
energy: Energy;
}
/**
* Returns the energy statistics of a source that are not set yet and can be
* calculated from the power sensor paired with them.
*/
export function pendingIntegrals<Energy extends string>(
states: HomeAssistant["states"],
source: Partial<Record<Energy, string | null>>,
pairs: readonly (readonly [Energy, string | undefined])[],
totalUnits: string[]
): PowerIntegral<Energy>[] {
return pairs.flatMap(([energy, rate]) => {
if (!rate || source[energy]) {
return [];
}
const units = integralUnits(
states[rate]?.attributes.unit_of_measurement,
totalUnits
);
return units ? [{ energy, rate, units }] : [];
});
energy: "stat_energy_from" | "stat_energy_to";
}
/**
@@ -108,15 +84,21 @@ export function pendingPowerIntegrals(
if (powerType !== "two_sensors") {
return [];
}
return pendingIntegrals(
states,
source,
[
["stat_energy_from", powerConfig.stat_rate_from],
["stat_energy_to", powerConfig.stat_rate_to],
],
totalUnits
);
const rates = {
stat_energy_from: powerConfig.stat_rate_from,
stat_energy_to: powerConfig.stat_rate_to,
};
return (["stat_energy_from", "stat_energy_to"] as const).flatMap((energy) => {
const rate = rates[energy];
if (!rate || source[energy]) {
return [];
}
const units = integralUnits(
states[rate]?.attributes.unit_of_measurement,
totalUnits
);
return units ? [{ energy, rate, units }] : [];
});
}
/**
+21 -102
View File
@@ -1,58 +1,8 @@
import type {
BatteryDirectionsPowerConfig,
BatteryDirectionsSourceTypeEnergyPreference,
BatterySourceTypeEnergyPreference,
PowerConfig,
} from "../../../../data/energy";
import {
getBatteryEnergyStatIds,
isBatteryDirections,
} from "../../../../data/energy";
import type { PowerConfig } from "../../../../data/energy";
import { deepEqual } from "../../../../common/util/deep-equal";
export type PowerType = "none" | "standard" | "inverted" | "two_sensors";
export type BatteryMode = "total" | "directions";
export const BATTERY_DIRECTIONS = [
{
key: "from_grid",
energy: "stat_energy_from_grid",
power: "stat_rate_from_grid",
charge: true,
},
{
key: "from_solar",
energy: "stat_energy_from_solar",
power: "stat_rate_from_solar",
charge: true,
},
{
key: "to_home",
energy: "stat_energy_to_home",
power: "stat_rate_to_home",
charge: false,
},
{
key: "to_grid",
energy: "stat_energy_to_grid",
power: "stat_rate_to_grid",
charge: false,
},
] as const satisfies readonly {
key: string;
energy: keyof BatteryDirectionsSourceTypeEnergyPreference;
power: keyof BatteryDirectionsPowerConfig;
charge: boolean;
}[];
export type BatteryDirection = (typeof BATTERY_DIRECTIONS)[number];
export const getBatteryMode = (
source?: BatterySourceTypeEnergyPreference
): BatteryMode | undefined =>
source ? (isBatteryDirections(source) ? "directions" : "total") : undefined;
/**
* Extracts the power type from a PowerConfig object.
*/
@@ -127,9 +77,18 @@ export function buildPowerExcludeList(
sources.forEach((entry) => {
if (entry.stat_rate) powerIds.push(entry.stat_rate);
if (entry.power_config) {
powerIds.push(
...Object.values(entry.power_config).filter((id): id is string => !!id)
);
if (entry.power_config.stat_rate) {
powerIds.push(entry.power_config.stat_rate);
}
if (entry.power_config.stat_rate_inverted) {
powerIds.push(entry.power_config.stat_rate_inverted);
}
if (entry.power_config.stat_rate_from) {
powerIds.push(entry.power_config.stat_rate_from);
}
if (entry.power_config.stat_rate_to) {
powerIds.push(entry.power_config.stat_rate_to);
}
}
});
@@ -144,62 +103,22 @@ export function buildPowerExcludeList(
return powerIds.filter((id) => !currentPowerIds.includes(id));
}
/**
* Returns the statistics the other batteries use in either mode. The edited
* battery can't reuse them.
*/
export function buildBatteryExcludeList(
sources: BatterySourceTypeEnergyPreference[],
current?: BatterySourceTypeEnergyPreference
): string[] {
const currentIndex = current
? sources.findIndex((source) => deepEqual(source, current))
: -1;
return sources.flatMap((source, index) => {
if (index === currentIndex) {
return [];
}
const { charge, discharge } = getBatteryEnergyStatIds(source);
return [
...charge,
...discharge,
source.stat_rate,
...Object.values(source.power_config ?? {}),
].filter((id): id is string => !!id);
});
}
const isDirectionPowerConfig = (
config: PowerConfig | BatteryDirectionsPowerConfig
): config is BatteryDirectionsPowerConfig =>
BATTERY_DIRECTIONS.some(
({ power }) => !!(config as BatteryDirectionsPowerConfig)[power]
);
/**
* Returns the entity id of the power sensor the backend generated for a saved
* source, if any. Inverted, two sensor and battery direction configs get such
* a helper, its entity id is stored in `stat_rate`. Returns nothing while the
* config differs from the saved one, as the helper doesn't match the edited
* config yet.
* source, if any. Inverted and two sensor configs get such a helper, its entity
* id is stored in `stat_rate`. Returns nothing while the config differs from the
* saved one, as the helper doesn't match the edited config yet.
*/
export function getPowerHelperEntityId(
source:
| {
stat_rate?: string;
power_config?: PowerConfig | BatteryDirectionsPowerConfig;
}
| undefined,
currentPowerConfig: PowerConfig | BatteryDirectionsPowerConfig
source: { stat_rate?: string; power_config?: PowerConfig } | undefined,
currentPowerConfig: PowerConfig
): string | undefined {
if (!source?.stat_rate || !source.power_config) {
return undefined;
}
if (!isDirectionPowerConfig(source.power_config)) {
const savedPowerType = getPowerTypeFromConfig(source.power_config);
if (savedPowerType !== "inverted" && savedPowerType !== "two_sensors") {
return undefined;
}
const savedPowerType = getPowerTypeFromConfig(source.power_config);
if (savedPowerType !== "inverted" && savedPowerType !== "two_sensors") {
return undefined;
}
if (!deepEqual(source.power_config, currentPowerConfig)) {
return undefined;
@@ -40,10 +40,6 @@ export interface EnergyHomeSourceEditorParams {
export interface EnergyBatterySourceEditorParams {
source?: BatterySourceTypeEnergyPreference;
battery_sources: BatterySourceTypeEnergyPreference[];
/** The sources a battery measured per direction charges from or discharges to */
has_grid_import: boolean;
has_grid_export: boolean;
has_solar: boolean;
statsMetadata?: Record<string, StatisticsMetaData>;
saveCallback: (source: BatterySourceTypeEnergyPreference) => Promise<void>;
}
File diff suppressed because it is too large. Load diff
@@ -768,6 +768,7 @@ export class HaEnergyGridSourceEditor extends EnergyEditorMixin(
number_energy_price: draft.number_energy_price,
entity_energy_price_export: draft.entity_energy_price_export,
number_energy_price_export: draft.number_energy_price_export,
cost_adjustment_day: draft.cost_adjustment_day,
};
if (draft.name) {
source.name = draft.name;
@@ -77,10 +77,7 @@ export class DialogVacuumSegmentMapping
if (!this._params) return;
const entityId = this._params.entityId;
this._entry = await getExtendedEntityRegistryEntry(
this.hass.callWS,
entityId
);
this._entry = await getExtendedEntityRegistryEntry(this.hass, entityId);
if (this._entry?.options?.vacuum) {
this._areaMapping = this._entry.options.vacuum.area_mapping || {};
@@ -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;
@@ -601,7 +601,7 @@ export class DialogHelperDetail extends DirtyStateProviderMixin<
try {
// The entity ID usually matches the helper ID, unless it was taken
const entry = await getExtendedEntityRegistryEntry(
this._api.callWS,
this._api,
`${domain}.${uniqueId}`
).catch(() => undefined);
if (entry && isCreated(entry)) {
@@ -225,10 +225,12 @@ class MqttSubscribeCard extends LitElement {
static styles = css`
form {
padding: var(--ha-space-4) 0 var(--ha-space-8);
padding: var(--ha-space-4);
padding-bottom: var(--ha-space-8);
}
.content_subscribe_panel {
max-width: var(--ha-content-width-narrow);
margin-top: var(--ha-space-6);
max-width: 600px;
margin: 0 auto;
direction: ltr;
}
+1 -1
View File
@@ -99,7 +99,7 @@ class HaPanelDevDebug extends SubscribeMixin(LitElement) {
}
let entity: ExtEntityRegistryEntry | undefined;
try {
entity = await getExtendedEntityRegistryEntry(this.hass.callWS, id);
entity = await getExtendedEntityRegistryEntry(this.hass, id);
} catch {
// not in the registry
}
File diff suppressed because it is too large. Load diff
@@ -1,670 +0,0 @@
import { formatISO9075 } from "date-fns";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { formatDateTime } from "../../../../common/datetime/format_date_time";
import { fireEvent } from "../../../../common/dom/fire_event";
import { formatNumberWithUnit } from "../../../../common/number/format_number";
import "../../../../components/ha-spinner";
import "../../../../components/ha-dialog-footer";
import "../../../../components/ha-dialog";
import "../../../../components/ha-button";
import "../../../../components/ha-icon-next";
import "../../../../components/ha-selector/ha-selector-datetime";
import "../../../../components/ha-selector/ha-selector-number";
import "../../../../components/item/ha-list-item-button";
import "../../../../components/list/ha-list-base";
import type { StatisticValue } from "../../../../data/recorder";
import {
adjustStatisticsSum,
fetchStatistics,
getDisplayUnit,
} from "../../../../data/recorder";
import type {
DateTimeSelector,
NumberSelector,
} from "../../../../data/selector";
import { showAlertDialog } from "../../../../dialogs/generic/show-dialog-box";
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
import { haStyle, haStyleDialog } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import { showToast } from "../../../../util/toast";
import type { DialogStatisticsAdjustSumParams } from "./show-dialog-statistics-adjust-sum";
interface CombinedStat {
hour: StatisticValue | null;
fiveMin: StatisticValue[];
}
interface FetchedStats {
hour: StatisticValue[];
fiveMin: StatisticValue[];
}
interface AdjustState {
amount: number | undefined;
}
@customElement("dialog-statistics-adjust-sum")
export class DialogStatisticsFixUnsupportedUnitMetadata extends DirtyStateProviderMixin<AdjustState>()(
LitElement
) {
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _params?: DialogStatisticsAdjustSumParams;
@state() private _open = false;
@state() private _busy = false;
@state() private _moment?: string;
@state() private _stats5min?: StatisticValue[];
@state() private _statsHour?: StatisticValue[];
@state() private _chosenStat?: StatisticValue;
@state() private _amount?: number;
private _showingOutliers = false;
// Adjustments made while the dialog is open, keyed by period. The recorder
// processes adjustments asynchronously, so a fetch right after adjusting can
// still return the old values.
private _adjustedChanges = new Map<string, number>();
// Incremented for every fetch, so results of outdated fetches are ignored
private _fetchId = 0;
private _dateTimeSelector: DateTimeSelector = {
datetime: {},
};
private _precision = 2;
private _amountSelector = memoizeOne(
(
unit_of_measurement: string | undefined,
precision: number
): NumberSelector => ({
number: {
step: 10 ** -precision,
unit_of_measurement,
mode: "box",
},
})
);
public showDialog(params: DialogStatisticsAdjustSumParams): void {
this._params = params;
this._open = true;
// moment is in format YYYY-MM-DD HH:mm:ss because of selector
// Here we create a date with minutes set to %5
const now = new Date();
now.setMinutes(now.getMinutes() - (now.getMinutes() % 5), 0);
this._moment = formatISO9075(now);
this._showingOutliers = false;
this._adjustedChanges.clear();
this._refreshStats();
const entry = this.hass.entities[params.statistic.statistic_id];
this._precision = Math.max(entry?.display_precision ?? 0, 2);
}
public closeDialog(): void {
this._open = false;
}
private _dialogClosed(): void {
this._open = false;
this._params = undefined;
this._moment = undefined;
this._stats5min = undefined;
this._statsHour = undefined;
this._amount = undefined;
this._chosenStat = undefined;
this._initDirtyTracking({ type: "deep" }, { amount: undefined });
this._busy = false;
this._showingOutliers = false;
this._adjustedChanges.clear();
this._fetchId++;
fireEvent(this, "dialog-closed", { dialog: this.localName });
}
protected render() {
if (!this._params) {
return nothing;
}
let content: TemplateResult;
let footer: TemplateResult;
if (!this._chosenStat) {
content = this._renderPickStatistic();
footer = html`
<ha-button
slot="secondaryAction"
appearance="plain"
@click=${this._showOutliers}
>
${this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.outliers"
)}
</ha-button>
<ha-button slot="primaryAction" data-dialog="close">
${this.hass.localize("ui.common.close")}
</ha-button>
`;
} else {
content = this._renderAdjustStat();
footer = html`
<ha-button
slot="secondaryAction"
.disabled=${this._busy}
@click=${this._clearChosenStatistic}
appearance="plain"
>
${this.hass.localize("ui.common.back")}</ha-button
>
<ha-button
slot="primaryAction"
.disabled=${this._busy || !this.isDirtyState}
@click=${this._fixIssue}
>
${this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.adjust"
)}</ha-button
>
`;
}
return html`
<ha-dialog
.open=${this._open}
header-title=${this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.title"
)}
.preventScrimClose=${this.isDirtyState}
@closed=${this._dialogClosed}
>
${content}
<ha-dialog-footer slot="footer">${footer}</ha-dialog-footer>
</ha-dialog>
`;
}
protected shouldUpdate(changedProps: PropertyValues<this>): boolean {
if (changedProps.size !== 1 || !changedProps.has("hass")) {
return true;
}
// We only respond to hass changes if the translations or locale changed
const oldHass = changedProps.get("hass") as HomeAssistant | undefined;
return (
!oldHass ||
oldHass.localize !== this.hass.localize ||
oldHass.locale !== this.hass.locale
);
}
private _renderPickStatistic() {
let stats: TemplateResult;
if (!this._stats5min || !this._statsHour) {
stats = html`<ha-spinner></ha-spinner>`;
} else if (this._statsHour.length < 1 && this._stats5min.length < 1) {
stats = html`<p>
${this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.no_statistics_found"
)}
</p>`;
} else {
const data =
this._stats5min.length >= 1 ? this._stats5min : this._statsHour;
const unit = getDisplayUnit(
this.hass.states,
this._params!.statistic.statistic_id,
this._params!.statistic
);
const rows: TemplateResult[] = [];
for (const stat of data) {
const digits = this._fractionDigits(stat.change);
const change = formatNumberWithUnit(
stat.change!,
unit,
this.hass.locale,
{
minimumFractionDigits: digits,
maximumFractionDigits: digits,
}
);
rows.push(html`
<ha-list-item-button
.headline=${change}
.supportingText=${formatDateTime(
new Date(stat.start),
this.hass.locale,
this.hass.config
)}
.stat=${stat}
@click=${this._setChosenStatistic}
>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
`);
}
stats = html`<ha-list-base
aria-label=${this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.statistic_values"
)}
>${rows}</ha-list-base
>`;
}
return html`
<div class="text-content">
${this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.info_text_1"
)}
</div>
<div class="text-content">
<b
>${this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.statistic"
)}</b
>
${this._params!.statistic.statistic_id}
</div>
<ha-selector-datetime
.label=${this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.pick_a_time"
)}
.selector=${this._dateTimeSelector}
.value=${this._moment}
@value-changed=${this._dateTimeSelectorChanged}
></ha-selector-datetime>
<div class="stat-list">${stats}</div>
`;
}
private _clearChosenStatistic() {
this._chosenStat = undefined;
this._initDirtyTracking({ type: "deep" }, { amount: undefined });
}
// Small changes get more digits, so they do not round to zero.
private _fractionDigits(value: number | null | undefined): number {
if (!value || Math.abs(value) >= 10 ** -this._precision) {
return this._precision;
}
return Math.min(Math.ceil(-Math.log10(Math.abs(value))) + 1, 20);
}
private _setChosenStatistic(ev) {
const stat = ev.currentTarget.stat;
const multiple = 10 ** this._fractionDigits(stat.change);
const growth = Math.round(stat.change! * multiple) / multiple;
this._chosenStat = stat;
this._amount = growth;
this._initDirtyTracking({ type: "deep" }, { amount: growth });
}
private _dateTimeSelectorChanged(ev) {
this._moment = ev.detail.value;
this._showingOutliers = false;
this._refreshStats();
}
private _showOutliers() {
this._showingOutliers = true;
this._refreshStats();
}
private async _refreshStats(): Promise<void> {
const fetchId = ++this._fetchId;
this._stats5min = undefined;
this._statsHour = undefined;
try {
const stats = this._showingOutliers
? await this._fetchOutliers()
: await this._fetchStats();
if (fetchId !== this._fetchId) {
return;
}
this._statsHour = stats.hour;
this._stats5min = stats.fiveMin;
} catch (err: any) {
if (fetchId !== this._fetchId) {
return;
}
this._stats5min = [];
this._statsHour = [];
showAlertDialog(this, {
text: this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.error_loading_statistics",
{ message: err.message || err }
),
});
}
}
private _applyAdjustedChanges(stats: StatisticValue[]): StatisticValue[] {
if (!this._adjustedChanges.size) {
return stats;
}
return stats.map((stat) => {
const change = this._adjustedChanges.get(`${stat.start}-${stat.end}`);
return change === undefined ? stat : { ...stat, change };
});
}
private _renderAdjustStat() {
const unit = getDisplayUnit(
this.hass.states,
this._params!.statistic.statistic_id,
this._params!.statistic
);
return html`
<div class="text-content">
<b
>${this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.statistic"
)}</b
>
${this._params!.statistic.statistic_id}
</div>
<div class="table-row">
<span
>${this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.start"
)}</span
>
<span
>${formatDateTime(
new Date(this._chosenStat!.start),
this.hass.locale,
this.hass.config
)}</span
>
</div>
<div class="table-row">
<span
>${this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.end"
)}</span
>
<span
>${formatDateTime(
new Date(this._chosenStat!.end),
this.hass.locale,
this.hass.config
)}</span
>
</div>
<ha-selector-number
.label=${this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.new_value"
)}
.selector=${this._amountSelector(
unit || undefined,
this._fractionDigits(this._chosenStat!.change)
)}
.value=${this._amount}
.disabled=${this._busy}
@value-changed=${this._amountChanged}
></ha-selector-number>
`;
}
private _amountChanged(ev) {
this._amount = ev.detail.value;
this._updateDirtyState({ amount: this._amount });
}
private async _fetchStats(): Promise<FetchedStats> {
const statId = this._params!.statistic.statistic_id;
// moment is in format YYYY-MM-DD HH:mm:ss because of selector
// Here we convert it to an ISO string.
const moment = new Date(this._moment!.replace(" ", "T"));
// Search 2 hours before and 3 hours after chosen time
const hourStatStart = new Date(moment.getTime());
hourStatStart.setTime(hourStatStart.getTime() - 2 * 3600 * 1000);
const hourStatEnd = new Date(moment.getTime());
hourStatEnd.setTime(hourStatEnd.getTime() + 3 * 3600 * 1000);
const statsHourData = await fetchStatistics(
this.hass.callWS,
hourStatStart,
hourStatEnd,
[statId],
"hour"
);
const statsHour =
statId in statsHourData
? this._applyAdjustedChanges(statsHourData[statId].slice(0, 5))
: [];
// Can't have 5 min data if no hourly data
if (statsHour.length === 0) {
return { hour: [], fiveMin: [] };
}
// Search 10 minutes before and 15 minutes after chosen time
const minStatStart = new Date(moment.getTime());
minStatStart.setTime(minStatStart.getTime() - 10 * 60 * 1000);
const minStatEnd = new Date(moment.getTime());
minStatEnd.setTime(minStatEnd.getTime() + 15 * 60 * 1000);
const stats5MinData = await fetchStatistics(
this.hass.callWS,
minStatStart,
minStatEnd,
[statId],
"5minute"
);
return {
hour: statsHour,
fiveMin:
statId in stats5MinData
? this._applyAdjustedChanges(stats5MinData[statId].slice(0, 5))
: [],
};
}
private async _fetchOutliers(): Promise<FetchedStats> {
const statId = this._params!.statistic.statistic_id;
// Get all the data
const start = new Date(0);
const end = new Date();
const statsHourData = await fetchStatistics(
this.hass.callWS,
start,
end,
[statId],
"hour"
);
const statsHour =
statId in statsHourData
? this._applyAdjustedChanges(statsHourData[statId])
: [];
if (statsHour.length === 0) {
return { hour: [], fiveMin: [] };
}
const stats5MinData = await fetchStatistics(
this.hass.callWS,
start,
end,
[statId],
"5minute"
);
const stats5Min =
statId in stats5MinData
? this._applyAdjustedChanges(stats5MinData[statId])
: [];
// First datapoint of 5 minute data in the history is always junk since it counts the entire sum
// as the change, which we don't want here.
stats5Min.shift();
const combinedStatsData: CombinedStat[] = [];
statsHour.forEach((s) => {
combinedStatsData.push({ hour: s, fiveMin: [] });
});
const lasthour: CombinedStat = { hour: null, fiveMin: [] };
let i = 0;
stats5Min.forEach((s) => {
let matched = false;
for (i; i < combinedStatsData.length; i++) {
const hour = combinedStatsData[i].hour;
if (hour && s.start >= hour.start && s.end <= hour.end) {
combinedStatsData[i].fiveMin.push(s);
matched = true;
break;
}
}
if (!matched) {
lasthour.fiveMin.push(s);
}
});
combinedStatsData.push(lasthour);
let statsOutliers: StatisticValue[] = [];
let min = 0;
const numOutliers = 10;
// Track the top 10 values.
const addOutlier = (s) => {
const val = Math.abs(s.change ?? 0);
if (statsOutliers.length < numOutliers || val > min) {
statsOutliers.push(s);
statsOutliers = statsOutliers.sort(
(a, b) => Math.abs(b.change ?? 0) - Math.abs(a.change ?? 0)
);
statsOutliers = statsOutliers.slice(0, numOutliers);
min = statsOutliers[statsOutliers.length - 1].change ?? 0;
}
};
// If an hour has incomplete five minute data, add the hour value
// Otherwise, add the 5 minute values and ignore the hour value
combinedStatsData.forEach((c) => {
if (c.fiveMin.length !== 12 && c.hour) {
addOutlier(c.hour);
} else {
c.fiveMin.forEach((s) => {
addOutlier(s);
});
}
});
// Outliers are a possible mix of hour/5minute data, but the distinction
// is not relevant here, as long as only one array is populated.
return { hour: statsOutliers, fiveMin: [] };
}
private async _fixIssue(): Promise<void> {
const params = this._params!;
const chosenStat = this._chosenStat!;
const amount = this._amount!;
const unit = getDisplayUnit(
this.hass.states,
params.statistic.statistic_id,
params.statistic
);
this._busy = true;
try {
await adjustStatisticsSum(
this.hass,
params.statistic.statistic_id,
chosenStat.start,
// The shown value is rounded, so compare with the stored value.
amount - chosenStat.change!,
unit || null
);
} catch (err: any) {
// Report the error even if the dialog was closed or reopened while
// adjusting, but leave the state of a newer invocation alone
if (this._params === params) {
this._busy = false;
}
showAlertDialog(this, {
text: this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.error_sum_adjusted",
{ message: err.message || err }
),
});
return;
}
showToast(this, {
message: this.hass.localize(
"ui.panel.config.tools.tabs.statistics.fix_issue.adjust_sum.sum_adjusted"
),
});
// The dialog was closed or reopened while adjusting
if (this._params !== params) {
return;
}
this._adjustedChanges.set(`${chosenStat.start}-${chosenStat.end}`, amount);
this._busy = false;
this._clearChosenStatistic();
this._refreshStats();
}
static get styles(): CSSResultGroup {
return [
haStyle,
haStyleDialog,
css`
.text-content,
ha-selector-datetime,
ha-selector-number {
margin-bottom: var(--ha-space-5);
}
ha-list-base {
margin: 0 -24px;
}
ha-list-item-button {
--ha-row-item-padding-inline: var(--ha-space-6);
}
ha-list-item-button ha-icon-next {
color: var(--secondary-text-color);
}
.table-row {
display: flex;
justify-content: space-between;
margin-bottom: var(--ha-space-5);
}
.stat-list {
margin-top: var(--ha-space-2);
min-height: 360px;
display: flex;
flex-direction: column;
}
.stat-list ha-spinner {
margin: 0 auto;
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-statistics-adjust-sum": DialogStatisticsFixUnsupportedUnitMetadata;
}
}
@@ -1,277 +0,0 @@
import type { ContextType } from "@lit/context";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { consume } from "../../../../common/decorators/consume";
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
import "../../../../components/chart/statistics-chart";
import "../../../../components/date-picker/ha-date-range-picker";
import "../../../../components/ha-alert";
import "../../../../components/ha-button";
import "../../../../components/ha-dialog";
import "../../../../components/ha-dialog-footer";
import "../../../../components/ha-spinner";
import {
apiContext,
internationalizationContext,
} from "../../../../data/context";
import type { Statistics, StatisticType } from "../../../../data/recorder";
import {
clearStatistics,
fetchStatistics,
StatisticMeanType,
} from "../../../../data/recorder";
import { DialogMixin } from "../../../../dialogs/dialog-mixin";
import { haStyleDialog } from "../../../../resources/styles";
import { showToast } from "../../../../util/toast";
import type { DialogStatisticsClearRangeParams } from "./show-dialog-statistics-clear-range";
// Longer ranges use hourly statistics to keep the preview fast.
const MAX_5MINUTE_PREVIEW_MS = 3 * 24 * 60 * 60 * 1000;
type PreviewPeriod = "5minute" | "hour";
// The recorder also clears the period in which the range starts, so the
// preview starts at the beginning of that period.
const periodStart = (date: Date, period: PreviewPeriod) => {
const periodMs = (period === "hour" ? 60 : 5) * 60 * 1000;
return new Date(Math.floor(date.getTime() / periodMs) * periodMs);
};
@customElement("dialog-statistics-clear-range")
class DialogStatisticsClearRange extends DialogMixin<DialogStatisticsClearRangeParams>(
LitElement
) {
@state()
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@state() private _start = new Date();
@state() private _end = new Date();
@state() private _statistics?: Statistics;
@state() private _previewStart?: Date;
@state() private _busy = false;
@state() private _error?: string;
// Incremented for every fetch, so results of outdated fetches are ignored
private _fetchId = 0;
connectedCallback() {
super.connectedCallback();
this._end.setMinutes(
this._end.getMinutes() - (this._end.getMinutes() % 5),
0,
0
);
this._start = new Date(this._end.getTime() - 24 * 60 * 60 * 1000);
this._fetchStatistics();
}
private get _validRange() {
return this._start.getTime() < this._end.getTime();
}
private get _statTypes(): StatisticType[] {
return this.params!.statistic.mean_type !== StatisticMeanType.NONE
? ["mean", "min", "max"]
: ["change"];
}
protected render() {
if (!this.params) {
return nothing;
}
const localize = this._i18n.localize;
const statisticId = this.params.statistic.statistic_id;
const hasData = Boolean(this._statistics?.[statisticId]?.length);
return html`
<ha-dialog
open
width="large"
.headerTitle=${localize(
"ui.panel.config.tools.tabs.statistics.clear_range.title"
)}
.preventScrimClose=${this._busy}
>
<p>
${localize(
"ui.panel.config.tools.tabs.statistics.clear_range.info_text",
{ name: html`<b>${this.params.name}</b>` }
)}
</p>
<ha-date-range-picker
time-picker
.startDate=${this._start}
.endDate=${this._end}
.disabled=${this._busy}
@value-changed=${this._rangeChanged}
></ha-date-range-picker>
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
${
!this._validRange
? html`<ha-alert alert-type="error">
${localize(
"ui.panel.config.tools.tabs.statistics.clear_range.invalid_range"
)}
</ha-alert>`
: !this._statistics
? html`<div class="preview center">
<ha-spinner></ha-spinner>
</div>`
: !hasData
? html`<div class="preview center">
${localize(
"ui.panel.config.tools.tabs.statistics.clear_range.no_statistics_found"
)}
</div>`
: html`<div class="preview">
<statistics-chart
.statisticsData=${this._statistics}
.metadata=${{ [statisticId]: this.params.statistic }}
.names=${{ [statisticId]: this.params.name }}
.statTypes=${this._statTypes}
.chartType=${
this._statTypes[0] === "change" ? "bar" : "line"
}
.startTime=${this._previewStart}
.endTime=${this._end}
hide-legend
.clickForMoreInfo=${false}
height="240px"
></statistics-chart>
</div>`
}
<ha-dialog-footer slot="footer">
<ha-button
slot="secondaryAction"
appearance="plain"
.disabled=${this._busy}
@click=${this.closeDialog}
>
${localize("ui.common.cancel")}
</ha-button>
<ha-button
slot="primaryAction"
variant="danger"
.loading=${this._busy}
.disabled=${this._busy || !this._validRange || !hasData}
@click=${this._delete}
>
${localize("ui.common.delete")}
</ha-button>
</ha-dialog-footer>
</ha-dialog>
`;
}
private _rangeChanged(
ev: HASSDomEvent<{ value: { startDate: Date; endDate: Date } }>
) {
this._start = ev.detail.value.startDate;
this._end = ev.detail.value.endDate;
this._fetchStatistics();
}
private async _fetchStatistics() {
const fetchId = ++this._fetchId;
this._statistics = undefined;
this._error = undefined;
if (!this._validRange) {
return;
}
const statisticId = this.params!.statistic.statistic_id;
const fetchPreview = async (period: PreviewPeriod) => {
const start = periodStart(this._start, period);
const statistics = await fetchStatistics(
this._api.callWS,
start,
this._end,
[statisticId],
period,
undefined,
this._statTypes.includes("change") ? ["change"] : ["mean", "min", "max"]
);
return { start, statistics };
};
try {
const shortRange =
this._end.getTime() - this._start.getTime() <= MAX_5MINUTE_PREVIEW_MS;
let preview = await fetchPreview(shortRange ? "5minute" : "hour");
// Short term statistics are purged before the hourly statistics.
if (shortRange && !preview.statistics[statisticId]?.length) {
preview = await fetchPreview("hour");
}
if (fetchId === this._fetchId) {
this._previewStart = preview.start;
this._statistics = preview.statistics;
}
} catch (err: any) {
if (fetchId === this._fetchId) {
this._statistics = {};
this._error = err.message || err;
}
}
}
private async _delete() {
this._busy = true;
this._error = undefined;
try {
await clearStatistics(this._api, [this.params!.statistic.statistic_id], {
start: this._start,
end: this._end,
});
} catch (err: any) {
this._busy = false;
this._error = err.message || err;
return;
}
showToast(this, {
message: this._i18n.localize(
"ui.panel.config.tools.tabs.statistics.clear_range.deleted"
),
});
this.closeDialog();
}
static styles = [
haStyleDialog,
css`
p {
margin-top: 0;
}
ha-date-range-picker {
display: block;
margin-bottom: var(--ha-space-4);
}
.preview {
min-height: 240px;
}
.center {
display: flex;
align-items: center;
justify-content: center;
color: var(--secondary-text-color);
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
"dialog-statistics-clear-range": DialogStatisticsClearRange;
}
}
@@ -2,6 +2,30 @@ import type { StatisticsValidationResult } from "../../../../data/recorder";
import { showFixStatisticsDialog } from "./show-dialog-statistics-fix";
import { showFixStatisticsUnitsChangedDialog } from "./show-dialog-statistics-fix-units-changed";
const FIX_ISSUES_ORDER: Record<StatisticsValidationResult["type"], number> = {
no_state: 0,
entity_no_longer_recorded: 1,
entity_not_recorded: 1,
state_class_removed: 2,
units_changed: 3,
mean_type_changed: 4,
};
export const FIXABLE_ISSUES: StatisticsValidationResult["type"][] = [
"no_state",
"entity_no_longer_recorded",
"state_class_removed",
"units_changed",
"mean_type_changed",
];
export const sortStatisticsIssues = (issues: StatisticsValidationResult[]) =>
[...issues].sort(
(itemA, itemB) =>
(FIX_ISSUES_ORDER[itemA.type] ?? 99) -
(FIX_ISSUES_ORDER[itemB.type] ?? 99)
);
export const fixStatisticsIssue = async (
element: HTMLElement,
issue: StatisticsValidationResult
@@ -0,0 +1,27 @@
import { fireEvent } from "../../../../common/dom/fire_event";
import type {
StatisticsMetaData,
StatisticsValidationResult,
} from "../../../../data/recorder";
export const loadStatisticDialog = () => import("./dialog-statistic");
export interface DialogStatisticParams {
statistic: StatisticsMetaData;
name: string;
area?: string;
device?: string;
issues?: StatisticsValidationResult[];
issueFixedCallback?: () => void;
}
export const showStatisticDialog = (
element: HTMLElement,
dialogParams: DialogStatisticParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-statistic",
dialogImport: loadStatisticDialog,
dialogParams,
});
};
@@ -1,20 +0,0 @@
import { fireEvent } from "../../../../common/dom/fire_event";
import type { StatisticsMetaData } from "../../../../data/recorder";
export const loadAdjustSumDialog = () =>
import("./dialog-statistics-adjust-sum");
export interface DialogStatisticsAdjustSumParams {
statistic: StatisticsMetaData;
}
export const showStatisticsAdjustSumDialog = (
element: HTMLElement,
detailParams: DialogStatisticsAdjustSumParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-statistics-adjust-sum",
dialogImport: loadAdjustSumDialog,
dialogParams: detailParams,
});
};
@@ -1,21 +0,0 @@
import { fireEvent } from "../../../../common/dom/fire_event";
import type { StatisticsMetaData } from "../../../../data/recorder";
export const loadClearRangeDialog = () =>
import("./dialog-statistics-clear-range");
export interface DialogStatisticsClearRangeParams {
statistic: StatisticsMetaData;
name: string;
}
export const showStatisticsClearRangeDialog = (
element: HTMLElement,
dialogParams: DialogStatisticsClearRangeParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-statistics-clear-range",
dialogImport: loadClearRangeDialog,
dialogParams,
});
};
@@ -2,10 +2,8 @@ import {
mdiArrowDown,
mdiArrowUp,
mdiClose,
mdiDeleteClock,
mdiFormatListChecks,
mdiMenuDown,
mdiSlopeUphill,
mdiTableCog,
mdiUnfoldLessHorizontal,
mdiUnfoldMoreHorizontal,
@@ -28,11 +26,9 @@ import { consume } from "../../../../common/decorators/consume";
import { QueryParamsController } from "../../../../common/controllers/query-params-controller";
import { transform } from "../../../../common/decorators/transform";
import type {
HASSDomCurrentTargetEvent,
HASSDomEvent,
HASSDomTargetEvent,
} from "../../../../common/dom/fire_event";
import { fireEvent } from "../../../../common/dom/fire_event";
import { computeAreaName } from "../../../../common/entity/compute_area_name";
import {
computeDeviceName,
@@ -87,26 +83,7 @@ import type {
HomeAssistantRegistries,
} from "../../../../types";
import { showConfirmationDialog } from "../../../../dialogs/generic/show-dialog-box";
import { fixStatisticsIssue } from "./fix-statistics";
import { showStatisticsAdjustSumDialog } from "./show-dialog-statistics-adjust-sum";
import { showStatisticsClearRangeDialog } from "./show-dialog-statistics-clear-range";
const FIX_ISSUES_ORDER: Record<StatisticsValidationResult["type"], number> = {
no_state: 0,
entity_no_longer_recorded: 1,
entity_not_recorded: 1,
state_class_removed: 2,
units_changed: 3,
mean_type_changed: 4,
};
const FIXABLE_ISSUES: StatisticsValidationResult["type"][] = [
"no_state",
"entity_no_longer_recorded",
"state_class_removed",
"units_changed",
"mean_type_changed",
];
import { showStatisticDialog } from "./show-dialog-statistic";
type StatisticData = StatisticsMetaData & {
issues?: StatisticsValidationResult[];
@@ -318,70 +295,6 @@ class HaPanelDevStatistics extends KeyboardShortcutMixin(LitElement) {
localize("ui.panel.config.tools.tabs.statistics.no_issue")
}`,
},
fix: {
title: "",
label: localize("ui.panel.config.tools.tabs.statistics.fix_issue.fix"),
type: "icon",
template: (statistic) =>
html`${
statistic.issues
? html`<ha-button
@click=${this._fixIssue}
.data=${statistic.issues}
appearance="plain"
size="s"
>
${localize(
statistic.issues.some((issue) =>
FIXABLE_ISSUES.includes(issue.type)
)
? "ui.panel.config.tools.tabs.statistics.fix_issue.fix"
: "ui.panel.config.tools.tabs.statistics.fix_issue.info"
)}
</ha-button>`
: "—"
}`,
minWidth: "113px",
maxWidth: "113px",
showNarrow: true,
},
clear_range: {
title: "",
label: localize(
"ui.panel.config.tools.tabs.statistics.clear_range.title"
),
type: "icon-button",
showNarrow: true,
template: (statistic) => html`
<ha-icon-button
.label=${localize(
"ui.panel.config.tools.tabs.statistics.clear_range.title"
)}
.path=${mdiDeleteClock}
.statistic=${statistic}
@click=${this._showStatisticsClearRangeDialog}
></ha-icon-button>
`,
},
actions: {
title: "",
label: localize("ui.panel.config.tools.tabs.statistics.adjust_sum"),
type: "icon-button",
showNarrow: true,
template: (statistic) =>
statistic.has_sum
? html`
<ha-icon-button
.label=${localize(
"ui.panel.config.tools.tabs.statistics.adjust_sum"
)}
.path=${mdiSlopeUphill}
.statistic=${statistic}
@click=${this._showStatisticsAdjustSumDialog}
></ha-icon-button>
`
: nothing,
},
})
);
@@ -825,35 +738,28 @@ class HaPanelDevStatistics extends KeyboardShortcutMixin(LitElement) {
this._dataTable.selectAll((statistic) => statistic.issues);
}
private _showStatisticsAdjustSumDialog(
ev: HASSDomCurrentTargetEvent<HTMLElement & { statistic: StatisticData }>
) {
ev.stopPropagation();
showStatisticsAdjustSumDialog(this, {
statistic: ev.currentTarget.statistic,
});
}
private _showStatisticsClearRangeDialog(
ev: HASSDomCurrentTargetEvent<
HTMLElement & { statistic: DisplayedStatisticData }
>
) {
ev.stopPropagation();
const statistic = ev.currentTarget.statistic;
showStatisticsClearRangeDialog(this, {
private _rowClicked(ev: HASSDomEvent<RowClickedEvent>) {
const statistic = this._displayData(
this._data,
this._i18n.localize,
this._registries.entities,
this._registries.devices,
this._registries.areas,
this._formatEntityName
).find((stat) => stat.statistic_id === ev.detail.id);
if (!statistic) {
return;
}
showStatisticDialog(this, {
statistic,
name: statistic.displayName,
area: statistic.area,
device: statistic.device,
issues: statistic.issues,
issueFixedCallback: () => this._validateStatistics(),
});
}
private _rowClicked(ev: HASSDomEvent<RowClickedEvent>) {
const id = ev.detail.id;
if (id in this._states) {
fireEvent(this, "hass-more-info", { entityId: id });
}
}
private async _validateStatistics() {
try {
const [statisticIds, issues] = await Promise.all([
@@ -918,21 +824,6 @@ class HaPanelDevStatistics extends KeyboardShortcutMixin(LitElement) {
});
};
private _fixIssue = async (
ev: HASSDomCurrentTargetEvent<
HTMLElement & { data: StatisticsValidationResult[] }
>
) => {
const issues = ev.currentTarget.data.sort(
(itemA, itemB) =>
(FIX_ISSUES_ORDER[itemA.type] ?? 99) -
(FIX_ISSUES_ORDER[itemB.type] ?? 99)
);
const issue = issues[0];
await fixStatisticsIssue(this, issue);
this._validateStatistics();
};
protected supportedShortcuts(): SupportedShortcuts {
return {
f: () => this._searchInput.focus(),
@@ -419,7 +419,7 @@ export class EntityVoiceSettings extends SubscribeMixin(LitElement) {
);
if (this.entry) {
const entry = await getExtendedEntityRegistryEntry(
this.hass.callWS,
this.hass,
this.entityId
);
fireEvent(this, "entity-entry-updated", entry);
@@ -437,7 +437,7 @@ export class EntityVoiceSettings extends SubscribeMixin(LitElement) {
exposeEntities(this.hass, assistants, [this.entityId], ev.target.checked);
if (this.entry) {
const entry = await getExtendedEntityRegistryEntry(
this.hass.callWS,
this.hass,
this.entityId
);
fireEvent(this, "entity-entry-updated", entry);
+5 -8
View File
@@ -17,7 +17,6 @@ import { DirtyStateProviderMixin } from "../../../mixins/dirty-state-provider-mi
import { haStyleDialog } from "../../../resources/styles";
import type { HomeAssistant, ValueChangedEvent } from "../../../types";
import "../../../components/entity/ha-favorites-editor";
import { computeFavoriteCardsSize } from "../../lovelace/strategies/helpers/favorite-cards";
import "../components/home-shortcuts-editor";
import type { EditHomeDialogParams } from "./show-dialog-edit-home";
@@ -28,9 +27,9 @@ interface EditorState {
shortcuts: ShortcutItem[];
}
// The common-controls strategy caps the section at 8 slots (or the slots the
// favorites use, whichever is larger); once favorites reach the cap,
// predictions never render so the suggested-entities toggle has no effect.
// The common-controls strategy caps the section at 8 (or the favorites count,
// whichever is larger); once favorites reach the cap, predictions never render
// so the suggested-entities toggle has no effect.
const SUGGESTED_ENTITIES_CAP = 8;
const WELCOME_SCHEMA: HaFormSchema[] = [
@@ -141,8 +140,7 @@ export class DialogEditHome
show_suggested_entities: this._state.show_suggested_entities,
}}
.schema=${this._suggestedSchema(
computeFavoriteCardsSize(this._state.favorite_entities) >=
SUGGESTED_ENTITIES_CAP
this._state.favorite_entities.length >= SUGGESTED_ENTITIES_CAP
)}
.computeLabel=${this._computeSuggestedLabel}
.computeHelper=${this._computeSuggestedHelper}
@@ -215,8 +213,7 @@ export class DialogEditHome
private _computeSuggestedHelper = (): string => {
const favoritesFull =
computeFavoriteCardsSize(this._state?.favorite_entities ?? []) >=
SUGGESTED_ENTITIES_CAP;
(this._state?.favorite_entities.length ?? 0) >= SUGGESTED_ENTITIES_CAP;
return this.hass.localize(
favoritesFull
? "ui.panel.home.editor.suggested_entities_disabled_description"
@@ -1,5 +1,5 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing, unsafeCSS } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import { consume } from "../../../common/decorators/consume";
@@ -14,7 +14,6 @@ import { computeAttributeNameDisplay } from "../../../common/entity/compute_attr
import { computeDomain } from "../../../common/entity/compute_domain";
import { stateColorCss } from "../../../common/entity/state_color";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-control-slider";
import type { CoverEntity } from "../../../data/cover";
import { coverSupportsTiltPosition } from "../../../data/cover";
import {
@@ -25,6 +24,7 @@ import {
import { UNAVAILABLE } from "../../../data/entity/entity";
import { DOMAIN_ATTRIBUTES_UNITS } from "../../../data/entity/entity_attributes";
import type { FrontendLocaleData } from "../../../data/translation";
import { generateTiltSliderTrackBackgroundGradient } from "../../../state-control/cover/ha-state-control-cover-tilt-position";
import type {
HomeAssistant,
HomeAssistantApi,
@@ -37,33 +37,6 @@ import type {
LovelaceCardFeatureContext,
} from "./types";
function generateTiltSliderTrackBackgroundGradient() {
const count = 24;
const minStrokeWidth = 0.2;
const gradient: [number, string][] = [];
for (let i = 0; i < count; i++) {
const stopOffset1 = i / count;
const stopOffset2 =
stopOffset1 +
(i / count ** 2) * (1 - minStrokeWidth) +
minStrokeWidth / count;
if (i !== 0) {
gradient.push([stopOffset1, "transparent"]);
}
gradient.push([stopOffset1, "var(--control-slider-color)"]);
gradient.push([stopOffset2, "var(--control-slider-color)"]);
gradient.push([stopOffset2, "transparent"]);
}
return unsafeCSS(
gradient
.map(([stop, color]) => `${color} ${(stop as number) * 100}%`)
.join(", ")
);
}
const GRADIENT = generateTiltSliderTrackBackgroundGradient();
const supportsCoverTiltPositionCardFeatureFromState = (
@@ -192,10 +192,7 @@ export abstract class HuiNumericFavoriteCardFeatureBase<
private async _loadEntityEntry(entityId: string): Promise<void> {
try {
const entry = await getExtendedEntityRegistryEntry(
this._api.callWS,
entityId
);
const entry = await getExtendedEntityRegistryEntry(this._api, entityId);
if (this.context?.entity_id === entityId) {
this._entry = entry;
@@ -159,11 +159,7 @@ class HuiEnergyCarbonGaugeCard extends LitElement implements LovelaceCard {
id="info"
.path=${mdiInformationOutline}
></ha-svg-icon>
<ha-tooltip
trigger="hover focus click"
for="info"
placement="left"
>
<ha-tooltip for="info" placement="left">
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.carbon_consumed_gauge.card_indicates_energy_used"
)}
@@ -129,11 +129,7 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
<span class="imported" id="eq-imported">
${fmtEnergy(imported)}
</span>
<ha-tooltip
trigger="hover focus click"
for="eq-imported"
placement="top"
>
<ha-tooltip for="eq-imported" placement="top">
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.grid_balance.imported",
{ value: fmt(imported) }
@@ -143,11 +139,7 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
<span class="exported" id="eq-exported">
${fmtEnergy(exported)}
</span>
<ha-tooltip
trigger="hover focus click"
for="eq-exported"
placement="top"
>
<ha-tooltip for="eq-exported" placement="top">
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.grid_balance.exported",
{ value: fmt(exported) }
@@ -160,11 +152,7 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
>
${fmtEnergy(net)}
</span>
<ha-tooltip
trigger="hover focus click"
for="eq-net"
placement="top"
>
<ha-tooltip for="eq-net" placement="top">
${this._i18n.localize(
`ui.panel.lovelace.cards.energy.grid_balance.net_${isConsumption ? "import" : "export"}`,
{ value: fmt(Math.abs(net)) }
@@ -180,11 +168,7 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
class="bar-fill return"
style="width: ${leftPercent}%"
></div>
<ha-tooltip
trigger="hover focus click"
for="bar-exported"
placement="top"
>
<ha-tooltip for="bar-exported" placement="top">
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.grid_balance.exported",
{ value: fmt(exported) }
@@ -197,11 +181,7 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
class="bar-net return"
style="width: ${netBarWidth}%"
></div>
<ha-tooltip
trigger="hover focus click"
for="bar-net-left"
placement="top"
>
<ha-tooltip for="bar-net-left" placement="top">
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.grid_balance.net_export",
{
@@ -219,11 +199,7 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
class="bar-fill consumption"
style="width: ${rightPercent}%"
></div>
<ha-tooltip
trigger="hover focus click"
for="bar-imported"
placement="top"
>
<ha-tooltip for="bar-imported" placement="top">
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.grid_balance.imported",
{ value: fmt(imported) }
@@ -236,11 +212,7 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
class="bar-net consumption"
style="width: ${netBarWidth}%"
></div>
<ha-tooltip
trigger="hover focus click"
for="bar-net-right"
placement="top"
>
<ha-tooltip for="bar-net-right" placement="top">
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.grid_balance.net_import",
{
@@ -126,11 +126,7 @@ class HuiEnergyGridGaugeCard extends LitElement implements LovelaceCard {
id="info"
.path=${mdiInformationOutline}
></ha-svg-icon>
<ha-tooltip
trigger="hover focus click"
for="info"
placement="left"
>
<ha-tooltip for="info" placement="left">
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.grid_neutrality_gauge.energy_dependency"
)}
@@ -18,15 +18,11 @@ import type {
EnergyConsumptionData,
EnergyData,
EnergySourceByType,
EnergySumData,
} from "../../../../data/energy";
import {
computeConsumptionData,
computeEnergyDeviceLabels,
energySourcesByType,
getBatteryEnergyStatIds,
getBatteryFlowStatIds,
getBatteryName,
getSummedData,
validateEnergyCollectionKey,
} from "../../../../data/energy";
@@ -335,7 +331,7 @@ class HuiEnergySankeyCard
typeNodes,
typeLinks,
consumption,
summedData,
summedData.timestamps,
computedStyle
);
nodes.push(...separate.nodes);
@@ -444,47 +440,33 @@ class HuiEnergySankeyCard
typeNodes: Node[],
typeLinks: Link[],
consumption: EnergyConsumptionData,
summedData: EnergySumData,
timestamps: number[],
computedStyle: CSSStyleDeclaration
): { nodes: Node[]; links: Link[] } {
interface SourceNode {
id: string;
values?: Record<number, number>;
// Flows of a battery with direction statistics, by the other node
measured?: Record<string, Record<number, number>>;
}
const nodes: Node[] = [];
const sumSeries = (statIds: (string | undefined)[]) => {
const values: Record<number, number> = {};
let total = 0;
statIds.forEach((statId) => {
if (!statId) {
return;
}
this._data!.stats[statId]?.forEach(({ start, change }) => {
if (change === null || change === undefined) {
return;
}
values[start] = (values[start] ?? 0) + change;
total += change;
});
});
return { values, total };
};
const addNode = (
type: string,
statIds: string[],
statId: string,
colorVariable: string,
idx: number,
index: number,
name: string | undefined,
measured?: SourceNode["measured"]
name: string | undefined
): SourceNode => {
const statId = statIds[0];
const id = `${type}:${statId}`;
const { values, total } = sumSeries(statIds);
const values: Record<number, number> = {};
let total = 0;
this._data!.stats[statId]?.forEach(({ start, change }) => {
if (change === null || change === undefined) {
return;
}
values[start] = (values[start] ?? 0) + change;
total += change;
});
nodes.push({
id,
label:
@@ -505,11 +487,10 @@ class HuiEnergySankeyCard
idx
),
index,
entityId:
statIds.length === 1 && statId in this._states ? statId : undefined,
entityId: statId in this._states ? statId : undefined,
group: type,
});
return { id, values, measured };
return { id, values };
};
const addGroup = <T>(
@@ -524,62 +505,41 @@ class HuiEnergySankeyCard
return sources.map(toNode);
};
const batteryName = (
source: NonNullable<EnergySourceByType["battery"]>[number],
key: "named_battery_discharged" | "named_battery_charged"
) => {
const name = getBatteryName(
this._states,
this._formatEntityName,
source,
this._data!.statsMetadata
);
return (
name &&
this._i18n.localize(
`ui.panel.lovelace.cards.energy.energy_sources_table.${key}`,
{ name }
)
);
};
const series = (statId?: string) => sumSeries([statId]).values;
const batteryOut = addGroup("battery", split.battery, (source, idx) => {
const flows = getBatteryFlowStatIds(source);
return addNode(
const batteryOut = addGroup("battery", split.battery, (source, idx) =>
addNode(
"battery",
getBatteryEnergyStatIds(source).discharge,
source.stat_energy_from,
"--energy-battery-out-color",
idx,
0,
batteryName(source, "named_battery_discharged"),
flows && {
home: series(flows.battery_to_home),
grid_return: series(flows.battery_to_grid),
}
);
});
const batteryIn = addGroup("battery_in", split.battery, (source, idx) => {
const flows = getBatteryFlowStatIds(source);
return addNode(
source.name &&
this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.named_battery_discharged",
{ name: source.name }
)
)
);
const batteryIn = addGroup("battery_in", split.battery, (source, idx) =>
addNode(
"battery_in",
getBatteryEnergyStatIds(source).charge,
source.stat_energy_to,
"--energy-battery-in-color",
idx,
1,
batteryName(source, "named_battery_charged"),
flows && {
grid: series(flows.grid_to_battery),
solar: series(flows.solar_to_battery),
}
);
});
source.name &&
this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.named_battery_charged",
{ name: source.name }
)
)
);
const gridIn = addGroup(
"grid",
split.grid?.filter((source) => source.stat_energy_from),
(source, idx) =>
addNode(
"grid",
[source.stat_energy_from!],
source.stat_energy_from!,
"--energy-grid-consumption-color",
idx,
0,
@@ -594,7 +554,7 @@ class HuiEnergySankeyCard
const solar = addGroup("solar", split.solar, (source, idx) =>
addNode(
"solar",
[source.stat_energy_from],
source.stat_energy_from,
"--energy-solar-color",
idx,
0,
@@ -607,7 +567,7 @@ class HuiEnergySankeyCard
(source, idx) =>
addNode(
"grid_return",
[source.stat_energy_to!],
source.stat_energy_to!,
"--energy-grid-return-color",
idx,
1,
@@ -637,57 +597,22 @@ class HuiEnergySankeyCard
"battery>grid_return": consumption.battery_to_grid,
"solar>grid_return": consumption.solar_to_grid,
};
const measuredFlows: Record<string, Record<number, number> | undefined> = {
"battery>home": summedData.battery_to_home,
"grid>battery_in": summedData.grid_to_battery,
"solar>battery_in": summedData.solar_to_battery,
"battery>grid_return": summedData.battery_to_grid,
};
const isSplit = (id: string) => groups[id][0]?.id !== id;
// Batteries with direction statistics get their own flows, the rest of
// a flow is split across the others
const shares = (id: string, t: number): SankeyFlowShare[] =>
groups[id]
.filter((node) => !node.measured)
.map(({ id: nodeId, values }) => [
nodeId,
values ? (values[t] ?? 0) : 1,
]);
const exact = (node: SourceNode, other: string, t: number) =>
Math.max(node.measured![other]?.[t] ?? 0, 0);
groups[id].map(({ id: nodeId, values }) => [
nodeId,
values ? (values[t] ?? 0) : 1,
]);
const links = typeLinks.flatMap((link) => {
if (!isSplit(link.source) && !isSplit(link.target)) {
return [link];
}
const key = `${link.source}>${link.target}`;
const flow = flows[key];
const measuredSources = groups[link.source].filter((n) => n.measured);
const measuredTargets = groups[link.target].filter((n) => n.measured);
const measuredFlow =
measuredSources.length || measuredTargets.length
? measuredFlows[key]
: undefined;
const flow = flows[`${link.source}>${link.target}`];
const splitLinks = new Map<string, Link & { value: number }>();
for (const t of summedData.timestamps) {
measuredSources.forEach((node) =>
addSplitSankeyLinks(
splitLinks,
exact(node, link.target, t),
[[node.id, 1]],
shares(link.target, t)
)
);
measuredTargets.forEach((node) =>
addSplitSankeyLinks(
splitLinks,
exact(node, link.source, t),
shares(link.source, t),
[[node.id, 1]]
)
);
for (const t of timestamps) {
addSplitSankeyLinks(
splitLinks,
(flow[t] ?? 0) - Math.max(measuredFlow?.[t] ?? 0, 0),
flow[t] ?? 0,
shares(link.source, t),
shares(link.target, t)
);
@@ -125,11 +125,7 @@ class HuiEnergySelfSufficiencyGaugeCard
id="info"
.path=${mdiInformationOutline}
></ha-svg-icon>
<ha-tooltip
trigger="hover focus click"
for="info"
placement="left"
>
<ha-tooltip for="info" placement="left">
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.self_sufficiency_gauge.card_indicates_self_sufficiency_quota"
)}
@@ -114,11 +114,7 @@ class HuiEnergySolarGaugeCard extends LitElement implements LovelaceCard {
id="info"
.path=${mdiInformationOutline}
></ha-svg-icon>
<ha-tooltip
trigger="hover focus click"
for="info"
placement="left"
>
<ha-tooltip for="info" placement="left">
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.solar_consumed_gauge.card_indicates_solar_energy_used"
)}
@@ -24,8 +24,6 @@ import {
import type { EnergyData, EnergySourceByType } from "../../../../data/energy";
import {
energySourcesByType,
getBatteryEnergyStatIds,
getBatteryName,
validateEnergyCollectionKey,
} from "../../../../data/energy";
import { EnergyCollectionController } from "../../../../data/energy-collection-controller";
@@ -184,8 +182,7 @@ export class HuiEnergySourcesTableCard
compareCost: number | null,
showCosts: boolean,
compare: boolean,
name?: string,
moreInfo = true
name?: string
) {
const displayPrecision =
type === "gas" && this._gasUnits?.[statId] === energyUnit
@@ -224,10 +221,10 @@ export class HuiEnergySourcesTableCard
return html`<tr
class="mdc-data-table__row ${classMap({
clickable: moreInfo && !isExternalStatistic(statId),
clickable: !isExternalStatistic(statId),
})}"
@click=${this._handleMoreInfo}
.entity=${moreInfo ? statId : undefined}
.entity=${statId}
>
<td class="mdc-data-table__cell cell-bullet">
<div
@@ -255,16 +252,46 @@ export class HuiEnergySourcesTableCard
<th class="mdc-data-table__cell cell-source" scope="row" .title=${label}>
${label}
</th>
${this._renderValueCell(
formattedEnergy,
compare ? formattedCompareEnergy : undefined
)}
${
compare
? html`<td class="mdc-data-table__cell mdc-data-table__cell--numeric">
${formattedCompareEnergy}
</td>
${
showCosts
? html`<td
class="mdc-data-table__cell mdc-data-table__cell--numeric"
>
${
compareCost !== null
? formatNumber(compareCost, this._i18n.locale, {
style: "currency",
currency: this._hassConfig.currency!,
})
: ""
}
</td>`
: ""
}`
: ""
}
<td class="mdc-data-table__cell mdc-data-table__cell--numeric">
${formattedEnergy}
</td>
${
showCosts
? this._renderValueCell(
this._formatCost(cost),
compare ? this._formatCost(compareCost) : undefined
)
? html` <td
class="mdc-data-table__cell mdc-data-table__cell--numeric"
>
${
cost !== null
? formatNumber(cost, this._i18n.locale, {
style: "currency",
currency: this._hassConfig.currency!,
})
: ""
}
</td>`
: ""
}
</tr>`;
@@ -321,37 +348,49 @@ export class HuiEnergySourcesTableCard
<th class="mdc-data-table__cell cell-source" scope="row" .title=${label}>
${label}
</th>
${this._renderValueCell(
formattedEnergy,
compare ? formattedCompareEnergy : undefined
)}
${
compare
? html`<td class="mdc-data-table__cell mdc-data-table__cell--numeric">
${formattedCompareEnergy}
</td>
${
showCosts
? html`<td
class="mdc-data-table__cell mdc-data-table__cell--numeric"
>
${
compareCost !== null
? formatNumber(compareCost, this._i18n.locale, {
style: "currency",
currency: this._hassConfig.currency!,
})
: ""
}
</td>`
: ""
}`
: ""
}
<td class="mdc-data-table__cell mdc-data-table__cell--numeric">
${formattedEnergy}
</td>
${
showCosts
? this._renderValueCell(
this._formatCost(cost),
compare ? this._formatCost(compareCost) : undefined
)
? html`<td class="mdc-data-table__cell mdc-data-table__cell--numeric">
${
cost !== null
? formatNumber(cost, this._i18n.locale, {
style: "currency",
currency: this._hassConfig.currency!,
})
: ""
}
</td>`
: ""
}
</tr>`;
}
private _formatCost(cost: number | null): string {
return cost !== null
? formatNumber(cost, this._i18n.locale, {
style: "currency",
currency: this._hassConfig.currency!,
})
: "";
}
private _renderValueCell(value: string, compareValue: string | undefined) {
return html`<td class="mdc-data-table__cell mdc-data-table__cell--numeric">
<div>${value}</div>
${compareValue ? html`<div class="compare">${compareValue}</div>` : nothing}
</td>`;
}
protected render() {
if (!this._config) {
return nothing;
@@ -523,19 +562,6 @@ export class HuiEnergySourcesTableCard
};
};
const _sumStatData = (statIds: string[]) =>
statIds.reduce(
(sum, statId) => {
const data = _extractStatData(statId, null);
return {
hasData: sum.hasData || data.hasData,
energy: sum.energy + data.energy,
energyCompare: sum.energyCompare + data.energyCompare,
};
},
{ hasData: false, energy: 0, energyCompare: 0 }
);
const showOnlyTotals = this._config.show_only_totals;
const combine =
!showOnlyTotals &&
@@ -689,6 +715,32 @@ export class HuiEnergySourcesTableCard
"ui.panel.lovelace.cards.energy.energy_sources_table.source"
)}
</th>
${
compare
? html`<th
class="mdc-data-table__header-cell mdc-data-table__header-cell--numeric"
role="columnheader"
scope="col"
>
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.previous_energy"
)}
</th>
${
showCosts
? html`<th
class="mdc-data-table__header-cell mdc-data-table__header-cell--numeric"
role="columnheader"
scope="col"
>
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.previous_cost"
)}
</th>`
: ""
}`
: ""
}
<th
class="mdc-data-table__header-cell mdc-data-table__header-cell--numeric"
role="columnheader"
@@ -697,15 +749,6 @@ export class HuiEnergySourcesTableCard
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.energy"
)}
${
compare
? html`<div class="compare">
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.previous_energy"
)}
</div>`
: nothing
}
</th>
${
showCosts
@@ -717,15 +760,6 @@ export class HuiEnergySourcesTableCard
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.cost"
)}
${
compare
? html`<div class="compare">
${this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.previous_cost"
)}
</div>`
: nothing
}
</th>`
: ""
}
@@ -756,17 +790,16 @@ export class HuiEnergySourcesTableCard
})}
${_renderSimpleCategory("solar")}
${types.battery?.map((source, idx) => {
const { charge, discharge } = getBatteryEnergyStatIds(source);
const {
hasData: hasFromData,
energy: energyFrom,
energyCompare: energyFromCompare,
} = _sumStatData(discharge);
} = _extractStatData(source.stat_energy_from, null);
const {
hasData: hasToData,
energy: energyTo,
energyCompare: energyToCompare,
} = _sumStatData(charge);
} = _extractStatData(source.stat_energy_to, null);
if (!hasFromData && !hasToData) {
return nothing;
@@ -789,16 +822,10 @@ export class HuiEnergySourcesTableCard
return nothing;
}
const name = getBatteryName(
this._states,
this._formatEntityName,
source,
this._data!.statsMetadata
);
return html` ${this._renderRow(
computedStyles,
"battery_out",
discharge[0],
source.stat_energy_from,
idx,
energyFrom,
energyFromCompare,
@@ -807,17 +834,16 @@ export class HuiEnergySourcesTableCard
null,
showCosts,
compare,
name
source.name
? this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.named_battery_discharged",
{ name }
{ name: source.name }
)
: "",
discharge.length === 1
: ""
)}${this._renderRow(
computedStyles,
"battery_in",
charge[0],
source.stat_energy_to,
idx,
-energyTo,
-energyToCompare,
@@ -826,13 +852,12 @@ export class HuiEnergySourcesTableCard
null,
showCosts,
compare,
name
source.name
? this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.named_battery_charged",
{ name }
{ name: source.name }
)
: "",
charge.length === 1
: ""
)}`;
})}
${renderCombinedRow(
@@ -1198,14 +1223,6 @@ export class HuiEnergySourcesTableCard
white-space: nowrap;
width: 1%;
}
.compare {
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
}
.mdc-data-table__header-cell .compare {
font-weight: var(--ha-font-weight-normal);
white-space: normal;
}
.mdc-data-table__header-cell--numeric {
text-align: var(--float-end);
white-space: nowrap;
@@ -32,9 +32,6 @@ import type {
import {
computeConsumptionData,
energySourcesByType,
getBatteryEnergyStatIds,
getBatteryFlowStatIds,
getBatteryName,
getSuggestedPeriod,
getSummedData,
validateEnergyCollectionKey,
@@ -75,13 +72,6 @@ const colorPropertyMap = {
used_home: "--primary-color",
};
interface BatteryStatIds {
// Series of batteries with direction statistics, by series key
series: Record<"to_battery" | "from_battery", Record<string, string[]>>;
// Every statistic of a category, for combined sources
combined: Record<"to_battery" | "from_battery", string[]>;
}
const stackOrder = {
to_battery: 1,
to_grid: 2,
@@ -363,11 +353,6 @@ export class HuiEnergyUsageGraphCard
from_battery: {},
};
const batteryStatIds: BatteryStatIds = {
series: { to_battery: {}, from_battery: {} },
combined: { to_battery: [], from_battery: [] },
};
for (const source of energyData.prefs.energy_sources) {
if (source.type === "solar") {
if (statIds.solar) {
@@ -379,40 +364,23 @@ export class HuiEnergyUsageGraphCard
}
if (source.type === "battery") {
const { charge, discharge } = getBatteryEnergyStatIds(source);
const chargeKey = charge[0];
const dischargeKey = discharge[0];
if (statIds.to_battery) {
statIds.to_battery.push(chargeKey);
statIds.from_battery!.push(dischargeKey);
statIds.to_battery.push(source.stat_energy_to);
statIds.from_battery!.push(source.stat_energy_from);
} else {
statIds.to_battery = [chargeKey];
statIds.from_battery = [dischargeKey];
statIds.to_battery = [source.stat_energy_to];
statIds.from_battery = [source.stat_energy_from];
}
batteryStatIds.combined.to_battery.push(...charge);
batteryStatIds.combined.from_battery.push(...discharge);
const flows = getBatteryFlowStatIds(source);
if (flows) {
// Discharge shows only what reached the home
batteryStatIds.series.to_battery[chargeKey] = charge;
batteryStatIds.series.from_battery[dischargeKey] =
flows.battery_to_home ? [flows.battery_to_home] : [];
}
const name = getBatteryName(
this._states,
this._formatters.formatEntityName,
source,
energyData.statsMetadata
);
if (name) {
statLabels.to_battery[chargeKey] = this._i18n.localize(
if (source.name) {
statLabels.to_battery[source.stat_energy_to] = this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.named_battery_charged",
{ name }
);
statLabels.from_battery[dischargeKey] = this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.named_battery_discharged",
{ name }
{ name: source.name }
);
statLabels.from_battery[source.stat_energy_from] =
this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_sources_table.named_battery_discharged",
{ name: source.name }
);
}
continue;
}
@@ -550,7 +518,6 @@ export class HuiEnergyUsageGraphCard
computedStyles,
typeLabels,
statLabels,
batteryStatIds,
trackY,
combineTypes,
true
@@ -580,7 +547,6 @@ export class HuiEnergyUsageGraphCard
computedStyles,
typeLabels,
statLabels,
batteryStatIds,
trackY,
combineTypes,
false
@@ -672,7 +638,6 @@ export class HuiEnergyUsageGraphCard
to_battery: Record<string, string>;
from_battery: Record<string, string>;
},
batteryStatIds: BatteryStatIds,
trackY: (v: number) => void,
combineTypes: Set<string>,
compare = false
@@ -703,24 +668,13 @@ export class HuiEnergyUsageGraphCard
statIds!.forEach((id) => {
sets[id] = {};
});
sumEnergyStatistics(
statistics,
batteryStatIds.combined[key] ?? statIds!
).forEach((stat) => {
sumEnergyStatistics(statistics, statIds!).forEach((stat) => {
sets[statIds![0]][stat.start] = stat.change!;
});
combinedData[key] = sets;
return;
}
statIds!.forEach((id) => {
const summedIds = batteryStatIds.series[key]?.[id];
if (summedIds) {
sets[id] = {};
sumEnergyStatistics(statistics, summedIds).forEach((stat) => {
sets[id][stat.start] = stat.change!;
});
return;
}
const stats = statistics[id];
if (!stats) {
sets[id] = {};
@@ -751,55 +705,30 @@ export class HuiEnergyUsageGraphCard
combinedData.used_solar = { used_solar: consumptionData.used_solar };
}
const measuredToHome = summedData.battery_to_home;
if (combinedData.from_battery) {
// Discharge that did not reach the home
const batteryNotUsed: Record<number, number> = {};
let bySource = combinedData.from_battery;
let used = consumptionData.used_battery;
if (measuredToHome && !combineTypes.has("battery")) {
// Measured batteries have their own bars, only the rest is estimated
bySource = Object.fromEntries(
Object.entries(bySource).filter(
([id]) => !(id in batteryStatIds.series.from_battery)
)
);
used = {};
for (const start of summedData.timestamps) {
used[start] =
consumptionData.used_battery[start] -
Math.max(measuredToHome[start] ?? 0, 0);
batteryNotUsed[start] =
(summedData.from_battery_totals?.[start] ?? 0) - used[start];
}
} else {
for (const start of summedData.timestamps) {
batteryNotUsed[start] =
(summedData.from_battery?.[start] ?? 0) -
consumptionData.used_battery[start];
}
for (const start of summedData.timestamps) {
batteryNotUsed[start] =
(summedData.from_battery?.[start] ?? 0) -
consumptionData.used_battery[start];
}
combinedData.used_battery = {
used_battery: buildCombinedUsed(bySource, batteryNotUsed, used) ?? {},
used_battery:
buildCombinedUsed(
combinedData.from_battery,
batteryNotUsed,
consumptionData.used_battery
) ?? {},
};
}
if (combinedData.from_grid && summedData.to_battery) {
let gridNotUsed = consumptionData.grid_to_battery;
if (measuredToHome) {
// Measured flows can leave grid import that no estimate covers
gridNotUsed = {};
for (const start of summedData.timestamps) {
gridNotUsed[start] =
(summedData.from_grid?.[start] ?? 0) -
consumptionData.used_grid[start];
}
}
combinedData.used_grid = {
used_grid:
buildCombinedUsed(
combinedData.from_grid,
gridNotUsed,
consumptionData.grid_to_battery,
consumptionData.used_grid
) ?? {},
};
@@ -16,21 +16,14 @@ import {
uiContext,
} from "../../../../data/context";
import type {
BatteryFlowStatIds,
EnergyData,
EnergyPreferences,
EnergySourceByType,
MeasuredBatteryFlows,
} from "../../../../data/energy";
import {
BATTERY_FLOW_KEYS,
computeConsumptionSingle,
computeEnergyDeviceLabels,
energySourcesByType,
formatPowerShort,
getBatteryFlowPowerIds,
getBatteryName,
getBatteryPrimaryStat,
getPowerFromState,
validateEnergyCollectionKey,
} from "../../../../data/energy";
@@ -83,18 +76,8 @@ interface PowerData {
used_grid: number;
used_battery: number;
used_total: number;
// Live flows of the batteries with direction sensors
measured?: MeasuredBatteryFlows;
}
// Type links that a battery with direction sensors measures
const MEASURED_LINKS: Record<string, keyof BatteryFlowStatIds> = {
"battery>home": "battery_to_home",
"battery>grid_return": "battery_to_grid",
"grid>battery_in": "grid_to_battery",
"solar>battery_in": "solar_to_battery",
};
@customElement("hui-power-sankey-card")
class HuiPowerSankeyCard
extends MobileAwareMixin(LitElement)
@@ -131,22 +114,11 @@ class HuiPowerSankeyCard
const prefs = this._data?.prefs;
if (states && prefs) {
[
...prefs.energy_sources.flatMap((source) => {
if (source.type === "gas" || source.type === "water") {
return [];
}
if (source.type === "battery") {
const rates = getBatteryFlowPowerIds(source);
if (rates) {
return [
...Object.values(rates),
// Names a battery that has no name of its own
source.name ? undefined : getBatteryPrimaryStat(source),
];
}
}
return [source.stat_rate];
}),
...prefs.energy_sources.map((source) =>
source.type === "gas" || source.type === "water"
? undefined
: source.stat_rate
),
...prefs.device_consumption.map((device) => device.stat_rate),
].forEach((entityId) => {
if (entityId && states[entityId]) {
@@ -272,7 +244,6 @@ class HuiPowerSankeyCard
typeLinks.push({
source: "battery",
target: "home",
value: powerData.used_battery,
});
}
@@ -292,14 +263,12 @@ class HuiPowerSankeyCard
typeLinks.push({
source: "grid",
target: "battery_in",
value: powerData.grid_to_battery,
});
}
if (powerData.solar_to_battery > 0) {
typeLinks.push({
source: "solar",
target: "battery_in",
value: powerData.solar_to_battery,
});
}
}
@@ -320,7 +289,6 @@ class HuiPowerSankeyCard
typeLinks.push({
source: "grid",
target: "home",
value: powerData.used_grid,
});
}
@@ -338,7 +306,6 @@ class HuiPowerSankeyCard
typeLinks.push({
source: "solar",
target: "home",
value: powerData.used_solar,
});
}
@@ -359,14 +326,12 @@ class HuiPowerSankeyCard
typeLinks.push({
source: "battery",
target: "grid_return",
value: powerData.battery_to_grid,
});
}
if (powerData.solar_to_grid > 0) {
typeLinks.push({
source: "solar",
target: "grid_return",
value: powerData.solar_to_grid,
});
}
}
@@ -391,7 +356,6 @@ class HuiPowerSankeyCard
[homeNode, ...typeNodes].filter((node) => node.value > 0),
typeLinks
),
powerData.measured,
computedStyle
);
nodes.push(...separate.nodes);
@@ -493,25 +457,17 @@ class HuiPowerSankeyCard
split: EnergySourceByType,
typeNodes: Node[],
typeLinks: (Link & { value: number })[],
measured: MeasuredBatteryFlows | undefined,
computedStyle: CSSStyleDeclaration
): { nodes: Node[]; links: Link[] } {
const nodes: Node[] = [];
const flowPower = (entityId?: string) =>
entityId ? Math.max(this._getCurrentPower(entityId), 0) : 0;
const flowIds = (...ids: (string | undefined)[]) =>
ids.filter((id): id is string => !!id);
// Nodes of batteries with direction sensors get exact links instead of a
// share of the type links
const addNodes = <T extends { stat_rate?: string; name?: string }>(
type: string,
sources: T[] | undefined,
sign: 1 | -1,
colorVariable: string,
index: number,
getName: (source: T) => string | undefined,
getFlowIds?: (source: T) => string[] | undefined
getName: (source: T) => string | undefined
): SankeyFlowShare[] => {
if (!sources) {
nodes.push(...typeNodes.filter((node) => node.id === type));
@@ -519,18 +475,14 @@ class HuiPowerSankeyCard
}
const shares: SankeyFlowShare[] = [];
sources.forEach((source, idx) => {
const ids = getFlowIds?.(source);
const statId = ids ? ids[0] : source.stat_rate;
if (!statId) {
if (!source.stat_rate) {
return;
}
const value = ids
? ids.reduce((sum, id) => sum + flowPower(id), 0)
: sign * this._getCurrentPower(statId);
const value = sign * this._getCurrentPower(source.stat_rate);
if (value <= 0) {
return;
}
const id = `${type}:${statId}`;
const id = `${type}:${source.stat_rate}`;
nodes.push({
id,
label:
@@ -538,8 +490,8 @@ class HuiPowerSankeyCard
getStatisticLabel(
this._states,
this._formatEntityName,
statId,
this._data!.statsMetadata[statId]
source.stat_rate,
this._data!.statsMetadata[source.stat_rate]
),
value,
color: getEnergyColor(
@@ -553,34 +505,21 @@ class HuiPowerSankeyCard
index,
group: type,
entityId:
(!ids || ids.length === 1) && statId in this._states
? statId
: undefined,
source.stat_rate in this._states ? source.stat_rate : undefined,
});
if (!ids) {
shares.push([id, value]);
}
shares.push([id, value]);
});
return shares;
};
const batteryName =
(key: "named_battery_discharged" | "named_battery_charged") =>
(source: NonNullable<EnergySourceByType["battery"]>[number]) => {
const name = getBatteryName(
this._states,
this._formatEntityName,
source,
this._data!.statsMetadata
(source: { name?: string }) =>
source.name &&
this._i18n.localize(
`ui.panel.lovelace.cards.energy.energy_sources_table.${key}`,
{ name: source.name }
);
return (
name &&
this._i18n.localize(
`ui.panel.lovelace.cards.energy.energy_sources_table.${key}`,
{ name }
)
);
};
const batteryOut = addNodes(
"battery",
@@ -588,11 +527,7 @@ class HuiPowerSankeyCard
1,
"--energy-battery-out-color",
0,
batteryName("named_battery_discharged"),
(source) => {
const rates = getBatteryFlowPowerIds(source);
return rates && flowIds(rates.battery_to_home, rates.battery_to_grid);
}
batteryName("named_battery_discharged")
);
const batteryIn = addNodes(
"battery_in",
@@ -600,11 +535,7 @@ class HuiPowerSankeyCard
-1,
"--energy-battery-in-color",
1,
batteryName("named_battery_charged"),
(source) => {
const rates = getBatteryFlowPowerIds(source);
return rates && flowIds(rates.grid_to_battery, rates.solar_to_battery);
}
batteryName("named_battery_charged")
);
const gridIn = addNodes(
"grid",
@@ -661,54 +592,15 @@ class HuiPowerSankeyCard
batteryOut,
batteryIn
);
split.battery.forEach((source) => {
const rates = getBatteryFlowPowerIds(source);
if (!rates) {
return;
}
const outId = flowIds(rates.battery_to_home, rates.battery_to_grid)[0];
const inId = flowIds(rates.grid_to_battery, rates.solar_to_battery)[0];
if (outId) {
const out: SankeyFlowShare[] = [[`battery:${outId}`, 1]];
addSplitSankeyLinks(
links,
flowPower(rates.battery_to_home),
out,
sharesByNode.home
);
addSplitSankeyLinks(
links,
flowPower(rates.battery_to_grid),
out,
sharesByNode.grid_return
);
}
if (inId) {
const into: SankeyFlowShare[] = [[`battery_in:${inId}`, 1]];
addSplitSankeyLinks(
links,
flowPower(rates.grid_to_battery),
sharesByNode.grid,
into
);
addSplitSankeyLinks(
links,
flowPower(rates.solar_to_battery),
sharesByNode.solar,
into
);
}
});
}
typeLinks.forEach((link) => {
const flow = MEASURED_LINKS[`${link.source}>${link.target}`];
typeLinks.forEach((link) =>
addSplitSankeyLinks(
links,
link.value - (split.battery && flow ? (measured?.[flow] ?? 0) : 0),
link.value,
sharesByNode[link.source],
sharesByNode[link.target]
);
});
)
);
return { nodes, links: [...links.values()] };
}
@@ -753,32 +645,14 @@ class HuiPowerSankeyCard
// Collect battery power (positive = discharge, negative = charge)
// Sum all battery values first, then determine net direction.
// Momentary power should only flow in one direction across all batteries.
// Batteries with direction sensors are measured instead.
let net_battery = 0;
let hasMeasured = false;
const measured: Record<keyof BatteryFlowStatIds, number> = {
grid_to_battery: 0,
solar_to_battery: 0,
battery_to_home: 0,
battery_to_grid: 0,
};
prefs.energy_sources.forEach((source) => {
if (source.type !== "battery") {
return;
}
const rates = getBatteryFlowPowerIds(source);
if (rates) {
hasMeasured = true;
BATTERY_FLOW_KEYS.forEach((key) => {
const entityId = rates[key];
if (entityId) {
measured[key] += Math.max(this._getCurrentPower(entityId), 0);
}
});
} else if (source.stat_rate) {
net_battery += this._getCurrentPower(source.stat_rate);
}
});
prefs.energy_sources
.filter((source) => source.type === "battery")
.forEach((source) => {
if (source.type === "battery" && source.stat_rate) {
net_battery += this._getCurrentPower(source.stat_rate);
}
});
if (net_battery > 0) {
from_battery = net_battery;
} else if (net_battery < 0) {
@@ -791,33 +665,75 @@ class HuiPowerSankeyCard
const homePower = homeStatRate
? getPowerFromState(this._states[homeStatRate])
: undefined;
const used_total =
homePower ?? from_grid + solar + from_battery - to_grid - to_battery;
const hasGridPower = gridValues.length > 0;
const hasSolarPower = prefs.energy_sources.some(
(source) => source.type === "solar" && source.stat_rate
);
const flows = computeConsumptionSingle(
{
from_grid: hasGridPower ? from_grid : undefined,
to_grid: hasGridPower ? to_grid : undefined,
solar: hasSolarPower ? solar : undefined,
to_battery,
from_battery,
},
{ measured: hasMeasured ? measured : undefined, used_total: homePower }
// Determine power routing using priority logic
// Priority: Solar -> Battery_In, Solar -> Grid_Out, Battery_Out -> Grid_Out,
// Grid_In -> Battery_In, Solar -> Consumption, Battery_Out -> Consumption, Grid_In -> Consumption
let solar_remaining = solar;
let grid_remaining = from_grid;
let battery_remaining = from_battery;
let to_battery_remaining = to_battery;
let to_grid_remaining = to_grid;
let used_total_remaining = Math.max(used_total, 0);
let grid_to_battery = 0;
// Handle excess grid input to battery first
const excess_grid_in_after_consumption = Math.max(
0,
Math.min(to_battery_remaining, grid_remaining - used_total_remaining)
);
grid_to_battery += excess_grid_in_after_consumption;
to_battery_remaining -= excess_grid_in_after_consumption;
grid_remaining -= excess_grid_in_after_consumption;
// Solar -> Battery_In
const solar_to_battery = Math.min(solar_remaining, to_battery_remaining);
to_battery_remaining -= solar_to_battery;
solar_remaining -= solar_to_battery;
// Solar -> Grid_Out
const solar_to_grid = Math.min(solar_remaining, to_grid_remaining);
to_grid_remaining -= solar_to_grid;
solar_remaining -= solar_to_grid;
// Battery_Out -> Grid_Out
const battery_to_grid = Math.min(battery_remaining, to_grid_remaining);
battery_remaining -= battery_to_grid;
// Grid_In -> Battery_In (second pass)
const grid_to_battery_2 = Math.min(grid_remaining, to_battery_remaining);
grid_to_battery += grid_to_battery_2;
grid_remaining -= grid_to_battery_2;
// Solar -> Consumption
const used_solar = Math.min(used_total_remaining, solar_remaining);
used_total_remaining -= used_solar;
// Battery_Out -> Consumption
const used_battery = Math.min(battery_remaining, used_total_remaining);
used_total_remaining -= used_battery;
// Grid_In -> Consumption
const used_grid = Math.min(used_total_remaining, grid_remaining);
return {
...flows,
solar,
from_grid,
to_grid,
from_battery:
from_battery + measured.battery_to_home + measured.battery_to_grid,
to_battery:
to_battery + measured.grid_to_battery + measured.solar_to_battery,
used_total: Math.max(0, flows.used_total),
measured: hasMeasured ? measured : undefined,
from_battery,
to_battery,
grid_to_battery,
battery_to_grid,
solar_to_battery,
solar_to_grid,
used_solar,
used_grid,
used_battery,
used_total: Math.max(0, used_total),
};
}
@@ -248,7 +248,7 @@ class HuiAlarmPanelCard extends LitElement implements LovelaceCard {
}
try {
this._entry = await getExtendedEntityRegistryEntry(
this._api.callWS,
this._api,
this._config!.entity
);
} catch (_e) {
@@ -33,7 +33,6 @@ import {
getSummedData,
} from "../../../data/energy";
import { EnergyCollectionController } from "../../../data/energy-collection-controller";
import { filterGroupsWithListedMembers } from "../../../data/group";
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
import type {
HomeAssistantConfig,
@@ -177,10 +176,7 @@ export class HuiHomeSummaryCard extends LitElement implements LovelaceCard {
generateEntityFilter(states, entities, devices, areas, floors, filter)
);
const lightEntities = filterGroupsWithListedMembers(
findEntities(allEntities, lightsFilters),
states
);
const lightEntities = findEntities(allEntities, lightsFilters);
const onLights = lightEntities.filter((entityId) => {
const s = states[entityId]?.state;
@@ -44,7 +44,6 @@ import {
formatDateMonth,
formatDateMonthShort,
formatDateVeryShort,
formatDateWeekdayVeryShortDate,
formatDateYear,
} from "../../../common/datetime/format_date";
import { consume } from "../../../common/decorators/consume";
@@ -368,7 +367,7 @@ export class HuiEnergyPeriodSelector extends LitElement {
this._hassConfig
)}`
: simpleRange === "day"
? html`${formatDateWeekdayVeryShortDate(
? html`${formatDateVeryShort(
this._startDate,
this._i18n.locale,
this._hassConfig
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more