mirror of
https://github.com/home-assistant/frontend.git
synced 2026-12-02 17:50:19 +00:00
Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1cc32d50e | ||
|
|
73f8c04e7a | ||
|
|
3fd97a5db0 | ||
|
|
3cc626b816 | ||
|
|
712e65db1d | ||
|
|
bfd20530d7 | ||
|
|
be90211d76 | ||
|
|
19ffa27a7f | ||
|
|
95eb9500e8 | ||
|
|
49f921bb8c | ||
|
|
a3b730d86a | ||
|
|
11e01b83f3 | ||
|
|
289851ca65 | ||
|
|
ae75b0fbb3 | ||
|
|
f821581318 | ||
|
|
d2ed5c57de | ||
|
|
0c343898e6 | ||
|
|
7a8696c237 | ||
|
|
f1cd21de5d | ||
|
|
570a781d60 | ||
|
|
db9e222753 | ||
|
|
dd29acff7c | ||
|
|
db8a8b5b41 |
No files matched your search
@@ -508,12 +508,8 @@ const createRspackConfig = ({
|
||||
"@formatjs/intl-locale/should-polyfill.js",
|
||||
"@formatjs/intl-locale/polyfill-force":
|
||||
"@formatjs/intl-locale/polyfill-force.js",
|
||||
"@formatjs/intl-numberformat/should-polyfill":
|
||||
"@formatjs/intl-numberformat/should-polyfill.js",
|
||||
"@formatjs/intl-numberformat/polyfill-force":
|
||||
"@formatjs/intl-numberformat/polyfill-force.js",
|
||||
"@formatjs/intl-pluralrules/should-polyfill":
|
||||
"@formatjs/intl-pluralrules/should-polyfill.js",
|
||||
"@formatjs/intl-pluralrules/polyfill-force":
|
||||
"@formatjs/intl-pluralrules/polyfill-force.js",
|
||||
"@formatjs/intl-relativetimeformat/should-polyfill":
|
||||
|
||||
@@ -73,7 +73,8 @@ class HcLovelace extends LitElement {
|
||||
|
||||
if (index !== undefined) {
|
||||
const title = getPanelTitleFromUrlPath(
|
||||
this.hass,
|
||||
this.hass.localize,
|
||||
this.hass.panels,
|
||||
this.urlPath || "lovelace"
|
||||
);
|
||||
|
||||
|
||||
@@ -355,7 +355,8 @@ export class HcMain extends HassElement {
|
||||
|
||||
private _handleNewLovelaceConfig(lovelaceConfig: LovelaceConfig) {
|
||||
const title = getPanelTitleFromUrlPath(
|
||||
this.hass!,
|
||||
this.hass!.localize,
|
||||
this.hass!.panels,
|
||||
this._urlPath || "lovelace"
|
||||
);
|
||||
castContext.setApplicationState(title || "");
|
||||
|
||||
@@ -207,6 +207,7 @@ export class HaEmbedProvider extends LitElement {
|
||||
}));
|
||||
hass.mockWS("energy/info", (): EnergyInfo => ({
|
||||
cost_sensors: {},
|
||||
fixed_cost_sensors: {},
|
||||
solar_forecast_domains: [],
|
||||
}));
|
||||
this._applyColorScheme();
|
||||
|
||||
@@ -120,10 +120,12 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
stat_consumption: "sensor.gas_heat_pump",
|
||||
},
|
||||
],
|
||||
fixed_costs: [],
|
||||
};
|
||||
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
|
||||
hass.mockWS("energy/info", (): EnergyInfo => ({
|
||||
cost_sensors: {},
|
||||
fixed_cost_sensors: {},
|
||||
solar_forecast_domains: [],
|
||||
}));
|
||||
hass.mockWS("energy/validate", () => ({
|
||||
@@ -131,6 +133,7 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
device_consumption: prefs.device_consumption.map(() => []),
|
||||
device_consumption_water: prefs.device_consumption_water.map(() => []),
|
||||
device_consumption_gas: prefs.device_consumption_gas.map(() => []),
|
||||
fixed_costs: prefs.fixed_costs.map(() => []),
|
||||
}));
|
||||
hass.mockWS(
|
||||
"energy/fossil_energy_consumption",
|
||||
|
||||
@@ -22,6 +22,14 @@ const baseRepository = {
|
||||
status: "default" as const,
|
||||
};
|
||||
|
||||
// The names of the connectivity of the demo repositories. Home Assistant
|
||||
// translates them, the mocked hass has no backend translations.
|
||||
export const marketplaceBackendTranslations = {
|
||||
"component.homeassistant.integration_connectivity.mqtt.name": "MQTT",
|
||||
"component.homeassistant.integration_connectivity.network.name":
|
||||
"Local network",
|
||||
};
|
||||
|
||||
const repositories: RepositoryBase[] = [
|
||||
{
|
||||
...baseRepository,
|
||||
@@ -32,6 +40,7 @@ const repositories: RepositoryBase[] = [
|
||||
description: "Watch camera streams with low latency through WebRTC.",
|
||||
authors: ["@AlexxIT"],
|
||||
domain: "webrtc",
|
||||
connectivity: ["network"],
|
||||
config_flow: true,
|
||||
available_version: "v3.6.1",
|
||||
downloads: 98000,
|
||||
@@ -68,6 +77,7 @@ const repositories: RepositoryBase[] = [
|
||||
description: "Use the cameras and events of a Frigate NVR.",
|
||||
authors: ["@blakeblackshear", "@dermotduffy", "@NickM-27"],
|
||||
domain: "frigate",
|
||||
connectivity: ["network", "mqtt"],
|
||||
config_flow: true,
|
||||
available_version: "v5.9.0",
|
||||
installed: true,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { LocalizeFunc } from "../../../src/common/translations/localize";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
import { connectivityBackendTranslations } from "./connectivity/fixtures";
|
||||
import { marketplaceBackendTranslations } from "./marketplace";
|
||||
|
||||
export const mockTranslations = (
|
||||
hass: MockHomeAssistant,
|
||||
@@ -20,7 +21,11 @@ export const mockTranslations = (
|
||||
// this merges on top of them.
|
||||
(localizePromise ?? Promise.resolve()).then(() =>
|
||||
hass.addTranslations(
|
||||
Object.assign({}, ...Object.values(connectivityBackendTranslations))
|
||||
Object.assign(
|
||||
{},
|
||||
...Object.values(connectivityBackendTranslations),
|
||||
marketplaceBackendTranslations
|
||||
)
|
||||
)
|
||||
);
|
||||
};
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { html, css, LitElement } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import "../../../src/components/ha-switch";
|
||||
import { handleAction } from "../../../src/panels/lovelace/common/handle-action";
|
||||
import type { HomeAssistant } from "../../../src/types";
|
||||
import "./demo-card";
|
||||
import type { DemoCardConfig } from "./demo-card";
|
||||
@@ -14,6 +16,16 @@ class DemoCards extends LitElement {
|
||||
|
||||
@state() private _showConfig = false;
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProps);
|
||||
// Handles card actions like the app's action mixin
|
||||
this.addEventListener("hass-action", (ev) => {
|
||||
ev.stopPropagation();
|
||||
const node = (ev.composedPath()[0] as HTMLElement | undefined) ?? this;
|
||||
handleAction(node, this.hass, ev.detail.config, ev.detail.action);
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<ha-demo-options>
|
||||
|
||||
@@ -22,20 +22,27 @@ export class DemoHaCircularSlider extends LitElement {
|
||||
@state()
|
||||
private changingHigh?: number;
|
||||
|
||||
// A handle that passes the other one pushes it along, like the slider does
|
||||
private _lowChanged(ev) {
|
||||
this.low = ev.detail.value;
|
||||
this.high = Math.max(this.high, this.low);
|
||||
}
|
||||
|
||||
private _lowChanging(ev) {
|
||||
this.changingLow = ev.detail.value;
|
||||
const value = ev.detail.value;
|
||||
this.changingLow = value;
|
||||
this.changingHigh = value != null && value > this.high ? value : undefined;
|
||||
}
|
||||
|
||||
private _highChanged(ev) {
|
||||
this.high = ev.detail.value;
|
||||
this.low = Math.min(this.low, this.high);
|
||||
}
|
||||
|
||||
private _highChanging(ev) {
|
||||
this.changingHigh = ev.detail.value;
|
||||
const value = ev.detail.value;
|
||||
this.changingHigh = value;
|
||||
this.changingLow = value != null && value < this.low ? value : undefined;
|
||||
}
|
||||
|
||||
private _currentChanged(ev) {
|
||||
|
||||
@@ -22,6 +22,13 @@ const ENTITIES = [
|
||||
friendly_name: "Bed Light",
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "light.living_room_ceiling_accent_lights",
|
||||
state: "on",
|
||||
attributes: {
|
||||
friendly_name: "Living Room Ceiling Accent Lights",
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "person.paulus",
|
||||
state: "home",
|
||||
@@ -73,6 +80,14 @@ const CONFIGS = [
|
||||
entity: "person.paulus",
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Long name",
|
||||
config: {
|
||||
type: "picture-entity",
|
||||
image: "/images/living_room.png",
|
||||
entity: "light.living_room_ceiling_accent_lights",
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Hidden name",
|
||||
config: {
|
||||
|
||||
+1
-1
@@ -84,7 +84,7 @@
|
||||
"@vvo/tzdb": "6.208.0",
|
||||
"@webcomponents/scoped-custom-element-registry": "0.0.11",
|
||||
"barcode-detector": "3.2.5",
|
||||
"cally": "0.10.0",
|
||||
"cally": "0.10.1",
|
||||
"color-name": "2.1.1",
|
||||
"comlink": "4.4.2",
|
||||
"core-js": "3.51.0",
|
||||
|
||||
Generated
+5
-5
@@ -331,8 +331,8 @@ importers:
|
||||
specifier: 3.2.5
|
||||
version: 3.2.5
|
||||
cally:
|
||||
specifier: 0.10.0
|
||||
version: 0.10.0
|
||||
specifier: 0.10.1
|
||||
version: 0.10.1
|
||||
color-name:
|
||||
specifier: 2.1.1
|
||||
version: 2.1.1
|
||||
@@ -4434,8 +4434,8 @@ packages:
|
||||
resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
[email protected].0:
|
||||
resolution: {integrity: sha512-awpa0UByh5O0bETxTpMX1MpTHiijKVxbPj/+Kgfmpsfh1/onEeYx6ag1swtbKzYFpCci2Zo65H1fU/M2Uwu/eA==}
|
||||
[email protected].1:
|
||||
resolution: {integrity: sha512-zBz8ygOnVpkkuaGq0RKa4/j8ZAkrePonivLhuXmm7Qu9bbK2+MXJCGeZX7rlUDWPnd+5GDyoudwjE5uQz/meaA==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-gxGWBrTT1JuMx6R+o5PTXMmUnhnVzLQ9SNutD4YqKtI6ap897t3tKECYla6gCWEkplXnlNybEkZg9GEGxKFCgw==}
|
||||
@@ -12289,7 +12289,7 @@ snapshots:
|
||||
call-bind-apply-helpers: 1.0.2
|
||||
get-intrinsic: 1.3.1
|
||||
|
||||
[email protected].0:
|
||||
[email protected].1:
|
||||
dependencies:
|
||||
atomico: 1.79.2
|
||||
|
||||
|
||||
@@ -244,7 +244,7 @@ export class ConditionEvaluatorController implements ReactiveController {
|
||||
return;
|
||||
}
|
||||
if (message.error !== undefined) {
|
||||
this._serverResults[subtree.id] = false;
|
||||
this._serverResults[subtree.id] = undefined;
|
||||
this._subtreeErrors[subtree.id] =
|
||||
typeof message.error === "string"
|
||||
? message.error
|
||||
@@ -265,7 +265,7 @@ export class ConditionEvaluatorController implements ReactiveController {
|
||||
if (generation !== this._generation) {
|
||||
return;
|
||||
}
|
||||
this._serverResults[subtree.id] = false;
|
||||
this._serverResults[subtree.id] = undefined;
|
||||
this._subtreeErrors[subtree.id] =
|
||||
getWsErrorMessage(err) ?? hass.localize("ui.common.unknown_error");
|
||||
this._recompute();
|
||||
@@ -299,18 +299,19 @@ export class ConditionEvaluatorController implements ReactiveController {
|
||||
}
|
||||
};
|
||||
|
||||
// A failed subtree stays unknown, so it only hides the card when the
|
||||
// result depends on it (a true `or` sibling still wins).
|
||||
const value = this._split.evaluate(clientEvaluator, this._serverResults);
|
||||
const error = firstDefined(this._subtreeErrors);
|
||||
// Don't treat a server error as `false` that a client `not` would invert.
|
||||
if (error !== undefined) {
|
||||
if (value === undefined && error !== undefined) {
|
||||
this._setResult("hidden", error);
|
||||
return;
|
||||
}
|
||||
|
||||
const value = this._split.evaluate(clientEvaluator, this._serverResults);
|
||||
const result: ConditionEvaluation =
|
||||
value === undefined ? "unknown" : value ? "visible" : "hidden";
|
||||
|
||||
this._setResult(result, firstDefined(this._subtreeTemplateErrors));
|
||||
this._setResult(result, error ?? firstDefined(this._subtreeTemplateErrors));
|
||||
}
|
||||
|
||||
private _setResult(
|
||||
|
||||
@@ -209,6 +209,16 @@ const formatDurationMinuteMem = memoizeOne((locale: FrontendLocaleData) =>
|
||||
})
|
||||
);
|
||||
|
||||
// Splits a value into whole units and whole sub-units, e.g. 1.15 h into 1 h
|
||||
// and 9 min. The value is converted to sub-units and rounded before flooring,
|
||||
// as floating point math puts many of them just below a whole number:
|
||||
// (1.15 - 1) * 60 is 8.999999999999995.
|
||||
const splitDuration = (value: number, subUnits: number): [number, number] => {
|
||||
const total = Math.floor(round(value * subUnits, 6));
|
||||
const units = Math.floor(total / subUnits);
|
||||
return [units, total - units * subUnits];
|
||||
};
|
||||
|
||||
export const formatDuration = (
|
||||
locale: FrontendLocaleData,
|
||||
duration: string,
|
||||
@@ -222,8 +232,7 @@ export const formatDuration = (
|
||||
|
||||
switch (unit) {
|
||||
case "d": {
|
||||
const days = Math.floor(value);
|
||||
const hours = Math.floor((value - days) * 24);
|
||||
const [days, hours] = splitDuration(value, 24);
|
||||
const input = {
|
||||
days,
|
||||
hours,
|
||||
@@ -231,8 +240,7 @@ export const formatDuration = (
|
||||
return formatDurationDayMem(locale)(input);
|
||||
}
|
||||
case "h": {
|
||||
const hours = Math.floor(value);
|
||||
const minutes = Math.floor((value - hours) * 60);
|
||||
const [hours, minutes] = splitDuration(value, 60);
|
||||
const input = {
|
||||
hours,
|
||||
minutes,
|
||||
@@ -240,8 +248,7 @@ export const formatDuration = (
|
||||
return formatDurationHourMem(locale)(input);
|
||||
}
|
||||
case "min": {
|
||||
const minutes = Math.floor(value);
|
||||
const seconds = Math.floor((value - minutes) * 60);
|
||||
const [minutes, seconds] = splitDuration(value, 60);
|
||||
const input = {
|
||||
minutes,
|
||||
seconds,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { parseISO } from "date-fns";
|
||||
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
|
||||
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
|
||||
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
getNumberFormatOptions,
|
||||
isNumericFromAttributes,
|
||||
} from "../number/format_number";
|
||||
import { isDate } from "../string/is_date";
|
||||
import { blankBeforeUnit } from "../translations/blank_before_unit";
|
||||
import type { LocalizeFunc } from "../translations/localize";
|
||||
import { computeDomain } from "./compute_domain";
|
||||
@@ -196,7 +198,9 @@ const computeStateToPartsFromEntityAttributes = (
|
||||
return [{ type: "value", value: value }];
|
||||
}
|
||||
|
||||
if (DATE_TIME_DOMAINS.has(domain)) {
|
||||
const isDateSensor = isSensorDomain && attributes.device_class === "date";
|
||||
|
||||
if (DATE_TIME_DOMAINS.has(domain) || isDateSensor) {
|
||||
// If trying to display an explicit state, need to parse the explicit state to `Date` then format.
|
||||
// Attributes aren't available, we have to use `state`.
|
||||
|
||||
@@ -217,15 +221,15 @@ const computeStateToPartsFromEntityAttributes = (
|
||||
];
|
||||
}
|
||||
if (components.length === 1) {
|
||||
if (state.includes("-")) {
|
||||
// Date only.
|
||||
if (isDate(state)) {
|
||||
// Parse and format date-only values in UTC to preserve the calendar day.
|
||||
return [
|
||||
{
|
||||
type: "value",
|
||||
value: formatDate(
|
||||
new Date(`${state}T00:00`),
|
||||
{ ...locale, time_zone: TimeZone.local },
|
||||
config
|
||||
parseISO(`${state}T00:00:00Z`),
|
||||
{ ...locale, time_zone: TimeZone.server },
|
||||
{ ...config, time_zone: "UTC" }
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import memoizeOne from "memoize-one";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { ensureArray } from "../array/ensure-array";
|
||||
import { computeDomain } from "./compute_domain";
|
||||
import { getEntityContext } from "./context/get_entity_context";
|
||||
import { getEntityIds } from "./get_entity_ids";
|
||||
|
||||
type EntityCategory = "none" | "config" | "diagnostic";
|
||||
|
||||
@@ -179,3 +181,66 @@ export const findFilteredEntities = (
|
||||
);
|
||||
return findEntities(Object.keys(sources.states), filterFuncs);
|
||||
};
|
||||
|
||||
export type EntityFinder = (
|
||||
states: HomeAssistant["states"],
|
||||
entities: HomeAssistant["entities"],
|
||||
devices: HomeAssistant["devices"],
|
||||
areas: HomeAssistant["areas"],
|
||||
floors: HomeAssistant["floors"]
|
||||
) => string[];
|
||||
|
||||
/**
|
||||
* Finds the same entities as `findFilteredEntities`, for repeated calls.
|
||||
* Of a state, the filters only read its device class, so everything else is
|
||||
* matched again only when the entity ids or the registries change.
|
||||
*/
|
||||
export const createEntityFinder = (filters: EntityFilter[]): EntityFinder => {
|
||||
const registryFilters = filters.map(
|
||||
({ device_class: _deviceClass, ...filter }) => filter
|
||||
);
|
||||
const deviceClasses = filters.map((filter) =>
|
||||
filter.device_class ? new Set(ensureArray(filter.device_class)) : undefined
|
||||
);
|
||||
let candidatesKey: unknown[] = [];
|
||||
let candidates: string[][] = [];
|
||||
|
||||
return memoizeOne<EntityFinder>(
|
||||
(states, entities, devices, areas, floors) => {
|
||||
const entityIds = getEntityIds(states);
|
||||
const key = [entityIds, entities, devices, areas, floors];
|
||||
if (key.some((value, i) => value !== candidatesKey[i])) {
|
||||
candidatesKey = key;
|
||||
candidates = registryFilters.map((filter) =>
|
||||
entityIds.filter(
|
||||
generateEntityFilter(
|
||||
states,
|
||||
entities,
|
||||
devices,
|
||||
areas,
|
||||
floors,
|
||||
filter
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
const results: string[] = [];
|
||||
candidates.forEach((candidateIds, i) => {
|
||||
const classes = deviceClasses[i];
|
||||
for (const entityId of candidateIds) {
|
||||
if (
|
||||
!seen.has(entityId) &&
|
||||
(!classes ||
|
||||
classes.has(states[entityId].attributes.device_class || "none"))
|
||||
) {
|
||||
seen.add(entityId);
|
||||
results.push(entityId);
|
||||
}
|
||||
}
|
||||
});
|
||||
return results;
|
||||
}
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { HomeAssistant } from "../../types";
|
||||
|
||||
let lastStates: HomeAssistant["states"] | undefined;
|
||||
let lastEntityIds: string[] = [];
|
||||
|
||||
/**
|
||||
* Returns the ids of `states`, as the same array for as long as they stay the
|
||||
* same, so callers can memoize on it.
|
||||
*/
|
||||
export const getEntityIds = (states: HomeAssistant["states"]): string[] => {
|
||||
if (states !== lastStates) {
|
||||
lastStates = states;
|
||||
const entityIds = Object.keys(states);
|
||||
if (
|
||||
entityIds.length !== lastEntityIds.length ||
|
||||
entityIds.some((entityId, i) => entityId !== lastEntityIds[i])
|
||||
) {
|
||||
lastEntityIds = entityIds;
|
||||
}
|
||||
}
|
||||
return lastEntityIds;
|
||||
};
|
||||
@@ -849,6 +849,9 @@ export class MapLibreMapEngine implements MapEngine {
|
||||
if (!interactive) {
|
||||
// Leaflet lets input through non-interactive markers; MapLibre does not
|
||||
element.style.pointerEvents = "none";
|
||||
} else {
|
||||
// Leaflet points at what takes a click; MapLibre leaves the map's grab
|
||||
element.style.cursor = "pointer";
|
||||
}
|
||||
setMarkerAccessibility(element, options.title, focusable);
|
||||
element.style.zIndex = options.raised ? "1" : "";
|
||||
@@ -1046,6 +1049,8 @@ export class MapLibreMapEngine implements MapEngine {
|
||||
setMarkerAccessibility(centerEl, options.title, !!options.onClick);
|
||||
if (options.moveable) {
|
||||
centerEl.style.cursor = "move";
|
||||
} else if (options.onClick) {
|
||||
centerEl.style.cursor = "pointer";
|
||||
}
|
||||
this._placedElements.add(centerEl);
|
||||
const centerMarker = new maplibre.Marker({
|
||||
@@ -1650,6 +1655,7 @@ export class MapLibreMapEngine implements MapEngine {
|
||||
this._hideEmerging(members);
|
||||
};
|
||||
setMarkerAccessibility(icon.element, this._groupTitle(group), true);
|
||||
icon.element.style.cursor = "pointer";
|
||||
icon.element.addEventListener("click", (ev) => {
|
||||
ev.stopPropagation();
|
||||
zoomToMembers();
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
|
||||
import type { FrontendLocaleData } from "../../data/translation";
|
||||
import { NumberFormat } from "../../data/translation";
|
||||
import { getLocaleDataVersion } from "../../resources/polyfills/locale-data-polyfill";
|
||||
import { blankBeforeUnit } from "../translations/blank_before_unit";
|
||||
|
||||
/**
|
||||
@@ -42,11 +43,20 @@ export const numberFormatToLocale = (
|
||||
// (locale, options) combinations is small and bounded in practice, so cache the
|
||||
// instances instead of rebuilding them on every call.
|
||||
const numberFormatCache = new Map<string, Intl.NumberFormat>();
|
||||
let numberFormatCacheVersion = getLocaleDataVersion();
|
||||
|
||||
const getNumberFormatter = (
|
||||
locale: string | string[] | undefined,
|
||||
options: Intl.NumberFormatOptions
|
||||
): Intl.NumberFormat => {
|
||||
// The Intl polyfill falls back to another locale while the data for the
|
||||
// requested one is still loading, e.g. right after a language change.
|
||||
// Start over when locale data is added, so the cache doesn't keep those.
|
||||
const version = getLocaleDataVersion();
|
||||
if (version !== numberFormatCacheVersion) {
|
||||
numberFormatCache.clear();
|
||||
numberFormatCacheVersion = version;
|
||||
}
|
||||
const key = JSON.stringify([locale, options]);
|
||||
let formatter = numberFormatCache.get(key);
|
||||
if (!formatter) {
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
// The filters of the Marketplace tables. Search, sorting and grouping are kept
|
||||
// by the data table, see data-table-query-params.
|
||||
export const marketplaceFilterQueryParamConfig = {
|
||||
list: ["status", "type", "source", "integration_category"],
|
||||
list: ["status", "type", "source", "integration_category", "connectivity"],
|
||||
} as const satisfies QueryParamConfig;
|
||||
|
||||
export type MarketplaceFilterQueryParams = QueryParamValues<
|
||||
|
||||
@@ -37,3 +37,29 @@ export const preserveUnchangedRecord = <T>(
|
||||
}
|
||||
return changed ? next : previous;
|
||||
};
|
||||
|
||||
/**
|
||||
* List variant of {@link preserveUnchangedRecord}: replaces each item in `next`
|
||||
* with the equal `previous` item that has the same key, in place.
|
||||
*/
|
||||
export const preserveUnchangedItems = <T>(
|
||||
previous: readonly T[] | undefined,
|
||||
next: T[],
|
||||
getKey: (item: T) => string,
|
||||
equal: (a: T, b: T) => boolean
|
||||
): T[] => {
|
||||
if (!previous?.length) {
|
||||
return next;
|
||||
}
|
||||
const previousByKey = new Map<string, T>();
|
||||
for (const item of previous) {
|
||||
previousByKey.set(getKey(item), item);
|
||||
}
|
||||
for (let i = 0; i < next.length; i++) {
|
||||
const previousItem = previousByKey.get(getKey(next[i]));
|
||||
if (previousItem !== undefined && equal(previousItem, next[i])) {
|
||||
next[i] = previousItem;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
};
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
import { differenceInMinutes } from "date-fns";
|
||||
import type {
|
||||
DataZoomComponentOption,
|
||||
GridComponentOption,
|
||||
MarkAreaComponentOption,
|
||||
} from "echarts/components";
|
||||
import type { EChartsType } from "echarts/core";
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
eventOptions,
|
||||
property,
|
||||
query,
|
||||
queryAll,
|
||||
state,
|
||||
} from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
@@ -150,6 +152,9 @@ const processSeriesTooltipFormatter = (s: HaECSeriesItem): RawSeriesOption => {
|
||||
|
||||
export type CustomLegendOption = ECOption["legend"] & {
|
||||
type: "custom";
|
||||
// "y-axis" lists the items beside the chart, each one next to its category,
|
||||
// in place of the y-axis labels.
|
||||
position?: "bottom" | "y-axis";
|
||||
data?: {
|
||||
id?: string;
|
||||
secondaryIds?: string[]; // Other dataset IDs that should be controlled by this legend item.
|
||||
@@ -248,6 +253,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
|
||||
@query(".chart") private _chartContainer?: HTMLDivElement;
|
||||
|
||||
@queryAll(".chart-legend button[data-id]")
|
||||
private _legendButtons!: NodeListOf<HTMLElement>;
|
||||
|
||||
@query(".sonification-output")
|
||||
private _sonificationOutput?: HTMLDivElement;
|
||||
|
||||
@@ -319,6 +327,25 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
},
|
||||
});
|
||||
|
||||
// The axis legend takes width from the chart without resizing the host
|
||||
private _chartResizeController = new ResizeController(this, {
|
||||
target: null,
|
||||
callback: (entries) => {
|
||||
const contentRect = entries[entries.length - 1]?.contentRect;
|
||||
if (
|
||||
this.chart &&
|
||||
contentRect &&
|
||||
(Math.round(contentRect.width) !== this.chart.getWidth() ||
|
||||
Math.round(contentRect.height) !== this.chart.getHeight())
|
||||
) {
|
||||
this._shouldResizeChart = true;
|
||||
this._resizeChartIfNeeded();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
private _focusedLegendButton?: { id: string; toggle: boolean };
|
||||
|
||||
private _loading = false;
|
||||
|
||||
private _reducedMotion = false;
|
||||
@@ -441,6 +468,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
if (!this.isConnected) {
|
||||
return;
|
||||
}
|
||||
this._chartResizeController.observe(this._chartContainer!);
|
||||
// The only measurement taken here: neither observer has reported yet, and a
|
||||
// chart first rendered inside a hidden container has to defer its setup
|
||||
// rather than build against a guessed width.
|
||||
@@ -489,6 +517,16 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
}
|
||||
|
||||
public willUpdate(changedProps: PropertyValues): void {
|
||||
const focused = this.shadowRoot?.activeElement as HTMLElement | null;
|
||||
this._focusedLegendButton =
|
||||
focused?.dataset.id &&
|
||||
focused.closest(".chart-legend") &&
|
||||
focused.matches(":focus-visible")
|
||||
? {
|
||||
id: focused.dataset.id,
|
||||
toggle: focused.classList.contains("legend-toggle"),
|
||||
}
|
||||
: undefined;
|
||||
if (!this.chart) {
|
||||
return;
|
||||
}
|
||||
@@ -596,6 +634,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
this._resizeChartIfNeeded();
|
||||
}
|
||||
this._renderedLegendFit = this._legendFit.fit;
|
||||
this._restoreLegendFocus();
|
||||
if (changedProps.has("options") || changedProps.has("data")) {
|
||||
// New values keep the widest widths, but other items are fitted afresh
|
||||
const legendItemsKey = JSON.stringify(
|
||||
@@ -610,11 +649,30 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
}
|
||||
}
|
||||
|
||||
// The legend reuses its buttons when items move, which would leave focus on
|
||||
// whichever item now sits where the focused one was
|
||||
private _restoreLegendFocus() {
|
||||
const focused = this._focusedLegendButton;
|
||||
const active = this.shadowRoot?.activeElement as HTMLElement | null;
|
||||
if (!focused || active?.dataset.id === focused.id) {
|
||||
return;
|
||||
}
|
||||
const className = focused.toggle ? "legend-toggle" : "label";
|
||||
Array.from(this._legendButtons)
|
||||
.find(
|
||||
(button) =>
|
||||
button.dataset.id === focused.id &&
|
||||
button.classList.contains(className)
|
||||
)
|
||||
?.focus();
|
||||
}
|
||||
|
||||
protected render() {
|
||||
const sonifiable =
|
||||
!this._sonificationUnavailable &&
|
||||
canSonifyChart(this.data, this._hiddenDatasets);
|
||||
const showZoomSlider = this._showZoomSlider();
|
||||
const axisLegend = this._hasAxisLegend();
|
||||
return html`
|
||||
<div
|
||||
class="container ${classMap({ "has-height": !!this.height })}"
|
||||
@@ -626,11 +684,14 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
})}
|
||||
>
|
||||
<div
|
||||
class="chart-container"
|
||||
class="chart-container ${classMap({
|
||||
"has-axis-legend": axisLegend,
|
||||
})}"
|
||||
style=${styleMap({
|
||||
height: this.height ? undefined : `${this._getDefaultHeight()}px`,
|
||||
})}
|
||||
>
|
||||
${axisLegend ? this._renderAxisLegend() : nothing}
|
||||
<div
|
||||
class="chart ${classMap({
|
||||
"touch-scrub": this._isTouchDevice && this._hasZoomableXAxis(),
|
||||
@@ -656,7 +717,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
${showZoomSlider ? this._renderZoomSlider() : nothing}
|
||||
</div>
|
||||
<div class="sonification-output"></div>
|
||||
${this._renderLegend()}
|
||||
${axisLegend ? nothing : this._renderLegend()}
|
||||
<div class="top-controls ${classMap({ small: this.smallControls })}">
|
||||
<slot name="search"></slot>
|
||||
<div
|
||||
@@ -683,14 +744,22 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
`;
|
||||
}
|
||||
|
||||
private _getLegendItems() {
|
||||
if (!this.options?.legend || !this.data) {
|
||||
private _getCustomLegend() {
|
||||
if (!this.options?.legend) {
|
||||
return undefined;
|
||||
}
|
||||
const legend = ensureArray(this.options.legend).find(
|
||||
return ensureArray(this.options.legend).find(
|
||||
(l) => l.show && l.type === "custom"
|
||||
) as CustomLegendOption | undefined;
|
||||
if (!legend) {
|
||||
}
|
||||
|
||||
private _hasAxisLegend() {
|
||||
return this._getCustomLegend()?.position === "y-axis";
|
||||
}
|
||||
|
||||
private _getLegendItems() {
|
||||
const legend = this._getCustomLegend();
|
||||
if (!legend || !this.data) {
|
||||
return undefined;
|
||||
}
|
||||
const datasets = ensureArray(this.data);
|
||||
@@ -707,20 +776,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
if (!items) {
|
||||
return nothing;
|
||||
}
|
||||
const datasets = ensureArray(this.data!);
|
||||
// Index datasets by id and name so each legend item is an O(1) lookup
|
||||
// instead of scanning every dataset twice. Charts can have many series.
|
||||
const datasetById = new Map<unknown, (typeof datasets)[number]>();
|
||||
const datasetByName = new Map<unknown, (typeof datasets)[number]>();
|
||||
for (const dataset of datasets) {
|
||||
if (dataset.id !== undefined && !datasetById.has(dataset.id)) {
|
||||
datasetById.set(dataset.id, dataset);
|
||||
}
|
||||
if (dataset.name !== undefined && !datasetByName.has(dataset.name)) {
|
||||
datasetByName.set(dataset.name, dataset);
|
||||
}
|
||||
}
|
||||
|
||||
const fit = this._legendFit.fit ?? items.length;
|
||||
return html`<div
|
||||
class=${classMap({
|
||||
@@ -729,73 +784,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
})}
|
||||
>
|
||||
<ul ${this._legendFit.target()}>
|
||||
${items.map((item, index) => {
|
||||
let itemStyle: Record<string, any> = {};
|
||||
let value = "";
|
||||
let noLabelClick = false;
|
||||
const name = typeof item === "string" ? item : (item.name ?? "");
|
||||
let id: string;
|
||||
if (typeof item === "string") {
|
||||
id = item;
|
||||
} else {
|
||||
id = item.id ?? name;
|
||||
value = item.value ?? "";
|
||||
itemStyle = item.itemStyle ?? {};
|
||||
noLabelClick = item.noLabelClick ?? false;
|
||||
}
|
||||
const labelClickable = this.clickLabelForMoreInfo && !noLabelClick;
|
||||
const dataset = datasetById.get(id) ?? datasetByName.get(id);
|
||||
itemStyle = {
|
||||
color: dataset?.color as string,
|
||||
...(dataset?.itemStyle as { borderColor?: string }),
|
||||
...itemStyle,
|
||||
};
|
||||
const color = itemStyle?.color as string;
|
||||
return html`<li
|
||||
.id=${id}
|
||||
@pointerdown=${this._legendPointerDown}
|
||||
@pointerup=${this._legendPointerCancel}
|
||||
@pointerleave=${this._legendPointerCancel}
|
||||
@pointercancel=${this._legendPointerCancel}
|
||||
@contextmenu=${this._legendContextMenu}
|
||||
class=${classMap({
|
||||
hidden: this._hiddenDatasets.has(id),
|
||||
overflow: !this.expandLegend && index >= fit,
|
||||
})}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="legend-toggle"
|
||||
data-id=${id}
|
||||
aria-pressed=${!this._hiddenDatasets.has(id)}
|
||||
.title=${this._i18n.localize(
|
||||
"ui.components.history_charts.toggle_visibility"
|
||||
)}
|
||||
@click=${this._toggleDataset}
|
||||
>
|
||||
<ha-svg-icon
|
||||
.path=${
|
||||
this._hiddenDatasets.has(id)
|
||||
? mdiCircleOutline
|
||||
: mdiCheckCircle
|
||||
}
|
||||
style=${styleMap({
|
||||
color: this._hiddenDatasets.has(id) ? undefined : color,
|
||||
})}
|
||||
></ha-svg-icon>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class=${classMap({ label: true, clickable: labelClickable })}
|
||||
data-id=${id}
|
||||
.title=${name}
|
||||
@click=${this._labelClick}
|
||||
>
|
||||
${name}
|
||||
</button>
|
||||
${value ? html`<div class="value">${value}</div>` : nothing}
|
||||
</li>`;
|
||||
})}
|
||||
${this._renderLegendItems(items, fit)}
|
||||
${
|
||||
items.length
|
||||
? html`<li
|
||||
@@ -829,6 +818,107 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private _renderAxisLegend() {
|
||||
const items = this._getLegendItems() ?? [];
|
||||
const grid = ensureArray(this._getGridOption()!)[0];
|
||||
return html`<div class="chart-legend axis-legend">
|
||||
<ul
|
||||
@pointerover=${this._axisLegendPointerOver}
|
||||
@pointerleave=${this._axisLegendPointerLeave}
|
||||
style=${styleMap({
|
||||
paddingTop: `${grid.top}px`,
|
||||
paddingBottom: `${grid.bottom}px`,
|
||||
})}
|
||||
>
|
||||
${this._renderLegendItems(items, items.length)}
|
||||
</ul>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private _renderLegendItems(
|
||||
items: NonNullable<ReturnType<HaChartBase["_getLegendItems"]>>,
|
||||
fit: number
|
||||
) {
|
||||
const datasets = ensureArray(this.data!);
|
||||
// Index datasets by id and name so each legend item is an O(1) lookup
|
||||
// instead of scanning every dataset twice. Charts can have many series.
|
||||
const datasetById = new Map<unknown, (typeof datasets)[number]>();
|
||||
const datasetByName = new Map<unknown, (typeof datasets)[number]>();
|
||||
for (const dataset of datasets) {
|
||||
if (dataset.id !== undefined && !datasetById.has(dataset.id)) {
|
||||
datasetById.set(dataset.id, dataset);
|
||||
}
|
||||
if (dataset.name !== undefined && !datasetByName.has(dataset.name)) {
|
||||
datasetByName.set(dataset.name, dataset);
|
||||
}
|
||||
}
|
||||
return items.map((item, index) => {
|
||||
let itemStyle: Record<string, any> = {};
|
||||
let value = "";
|
||||
let noLabelClick = false;
|
||||
const name = typeof item === "string" ? item : (item.name ?? "");
|
||||
let id: string;
|
||||
if (typeof item === "string") {
|
||||
id = item;
|
||||
} else {
|
||||
id = item.id ?? name;
|
||||
value = item.value ?? "";
|
||||
itemStyle = item.itemStyle ?? {};
|
||||
noLabelClick = item.noLabelClick ?? false;
|
||||
}
|
||||
const labelClickable = this.clickLabelForMoreInfo && !noLabelClick;
|
||||
const dataset = datasetById.get(id) ?? datasetByName.get(id);
|
||||
itemStyle = {
|
||||
color: dataset?.color as string,
|
||||
...(dataset?.itemStyle as { borderColor?: string }),
|
||||
...itemStyle,
|
||||
};
|
||||
const color = itemStyle?.color as string;
|
||||
return html`<li
|
||||
.id=${id}
|
||||
@pointerdown=${this._legendPointerDown}
|
||||
@pointerup=${this._legendPointerCancel}
|
||||
@pointerleave=${this._legendPointerCancel}
|
||||
@pointercancel=${this._legendPointerCancel}
|
||||
@contextmenu=${this._legendContextMenu}
|
||||
class=${classMap({
|
||||
hidden: this._hiddenDatasets.has(id),
|
||||
overflow: !this.expandLegend && index >= fit,
|
||||
})}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="legend-toggle"
|
||||
data-id=${id}
|
||||
aria-pressed=${!this._hiddenDatasets.has(id)}
|
||||
.title=${this._i18n.localize(
|
||||
"ui.components.history_charts.toggle_visibility"
|
||||
)}
|
||||
@click=${this._toggleDataset}
|
||||
>
|
||||
<ha-svg-icon
|
||||
.path=${
|
||||
this._hiddenDatasets.has(id) ? mdiCircleOutline : mdiCheckCircle
|
||||
}
|
||||
style=${styleMap({
|
||||
color: this._hiddenDatasets.has(id) ? undefined : color,
|
||||
})}
|
||||
></ha-svg-icon>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class=${classMap({ label: true, clickable: labelClickable })}
|
||||
data-id=${id}
|
||||
.title=${name}
|
||||
@click=${this._labelClick}
|
||||
>
|
||||
${name}
|
||||
</button>
|
||||
${value ? html`<div class="value">${value}</div>` : nothing}
|
||||
</li>`;
|
||||
});
|
||||
}
|
||||
|
||||
// Chart2Music adds ~45 kB gzipped, so it is only fetched once someone actually
|
||||
// moves keyboard focus into a chart.
|
||||
private async _handleChartFocus() {
|
||||
@@ -1309,14 +1399,28 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
|
||||
private _getGridOption() {
|
||||
const grid = this.options?.grid;
|
||||
if (!grid || !this._zoomSliderRoom) {
|
||||
const axisLegend = this._hasAxisLegend();
|
||||
if (!axisLegend && (!grid || !this._zoomSliderRoom)) {
|
||||
return grid;
|
||||
}
|
||||
const [first, ...rest] = ensureArray(grid);
|
||||
return [
|
||||
{ ...first, bottom: this._getGridBottom() + this._getZoomSliderSpace() },
|
||||
...rest,
|
||||
];
|
||||
const [first, ...rest] = ensureArray(grid ?? {});
|
||||
const result: GridComponentOption = { ...first };
|
||||
if (axisLegend) {
|
||||
// The legend rows are laid out from these, so labels must not move them
|
||||
result.top = this._getGridTop();
|
||||
result.bottom = this._getGridBottom();
|
||||
result.containLabel = false;
|
||||
result.outerBoundsMode = "none";
|
||||
}
|
||||
if (this._zoomSliderRoom) {
|
||||
result.bottom = this._getGridBottom() + this._getZoomSliderSpace();
|
||||
}
|
||||
return [result, ...rest];
|
||||
}
|
||||
|
||||
private _getGridTop() {
|
||||
const top = this.options?.grid && ensureArray(this.options.grid)[0].top;
|
||||
return typeof top === "number" ? top : 0;
|
||||
}
|
||||
|
||||
private _getGridBottom() {
|
||||
@@ -1389,6 +1493,22 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
} as XAXisOption;
|
||||
});
|
||||
}
|
||||
let yAxis = this.options?.yAxis;
|
||||
if (this._hasAxisLegend()) {
|
||||
const [first, ...rest] = ensureArray(yAxis ?? {});
|
||||
yAxis = [
|
||||
{
|
||||
...first,
|
||||
type: "category",
|
||||
inverse: true,
|
||||
data: this._getLegendItems()?.map((item) =>
|
||||
typeof item === "string" ? item : (item.id ?? item.name)
|
||||
),
|
||||
axisLabel: { ...first.axisLabel, show: false },
|
||||
} as YAXisOption,
|
||||
...rest,
|
||||
];
|
||||
}
|
||||
let legend = this.options?.legend;
|
||||
if (legend) {
|
||||
legend = ensureArray(legend).map((l) =>
|
||||
@@ -1418,6 +1538,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
grid: this._getGridOption(),
|
||||
legend,
|
||||
xAxis,
|
||||
yAxis,
|
||||
};
|
||||
|
||||
if (options.tooltip) {
|
||||
@@ -1881,6 +2002,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
series.option.center = null;
|
||||
series.option.zoom = 1;
|
||||
});
|
||||
fireEvent(this, "chart-zoom-reset");
|
||||
}
|
||||
|
||||
private _getGraphRoams(): {
|
||||
@@ -2018,6 +2140,24 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
}
|
||||
};
|
||||
|
||||
private _axisLegendPointerOver(ev: PointerEvent) {
|
||||
if (ev.pointerType !== "mouse" || !this.chart) {
|
||||
return;
|
||||
}
|
||||
const id = (ev.target as HTMLElement).closest("li")?.id;
|
||||
if (!id || this._hiddenDatasets.has(id)) {
|
||||
this._hideTooltip();
|
||||
return;
|
||||
}
|
||||
this.chart.dispatchAction({ type: "showTip", seriesIndex: 0, name: id });
|
||||
}
|
||||
|
||||
private _axisLegendPointerLeave(ev: PointerEvent) {
|
||||
if (ev.pointerType === "mouse") {
|
||||
this._hideTooltip();
|
||||
}
|
||||
}
|
||||
|
||||
private _hideTooltip() {
|
||||
this.chart?.dispatchAction({ type: "hideTip" });
|
||||
this.chart?.dispatchAction({
|
||||
@@ -2322,6 +2462,15 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
.has-height .chart-container {
|
||||
flex: 1;
|
||||
}
|
||||
.chart-container.has-axis-legend {
|
||||
display: flex;
|
||||
/* The chart is not mirrored in RTL, so its legend stays on the left */
|
||||
direction: ltr;
|
||||
}
|
||||
.has-axis-legend .chart {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.chart {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
@@ -2422,6 +2571,29 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
position: absolute;
|
||||
visibility: hidden;
|
||||
}
|
||||
.chart-legend.axis-legend {
|
||||
flex: none;
|
||||
max-width: min(200px, 40%);
|
||||
max-height: none;
|
||||
padding: 0;
|
||||
overflow: visible;
|
||||
direction: var(--direction);
|
||||
}
|
||||
.chart-legend.axis-legend ul {
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
flex-direction: column;
|
||||
flex-wrap: nowrap;
|
||||
align-items: stretch;
|
||||
gap: 0;
|
||||
}
|
||||
.chart-legend.axis-legend li,
|
||||
.chart-legend.axis-legend li:has(.legend-toggle) {
|
||||
flex: 1 1 0;
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
max-width: none;
|
||||
}
|
||||
.chart-legend .hidden {
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
@@ -2526,5 +2698,7 @@ declare global {
|
||||
};
|
||||
"chart-sankeyroam": { zoom: number };
|
||||
"chart-setup": undefined;
|
||||
// The user reset the zoom
|
||||
"chart-zoom-reset": undefined;
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import type {
|
||||
import { mdiFormatTextVariant, mdiGoogleCirclesGroup } from "@mdi/js";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import type { HASSDomEvent } from "../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import { reducedMotionContext } from "../../data/context";
|
||||
@@ -128,6 +130,25 @@ export class HaNetworkGraph extends LitElement {
|
||||
*/
|
||||
@property({ attribute: false }) public selectedNode?: string;
|
||||
|
||||
/**
|
||||
* Highlight the neighbors of a node on hover and fade the rest.
|
||||
*/
|
||||
@property({ attribute: false }) public hoverFocus = true;
|
||||
|
||||
/**
|
||||
* Distance in pixels from the center of a node within which a click next to
|
||||
* it still clicks the node, so small nodes are easier to hit. 0 is off.
|
||||
* Such a click fires a `chart-click` with only `dataType` and `data.id`.
|
||||
*/
|
||||
@property({ attribute: false }) public nodeClickRadius = 0;
|
||||
|
||||
/**
|
||||
* Names of the legend categories that are switched off. Keep it up to date
|
||||
* with `network-legend-changed`, or leave it out to let the legend keep its
|
||||
* own selection.
|
||||
*/
|
||||
@property({ attribute: false }) public hiddenCategories?: string[];
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _highlightedNodes?: Set<string>;
|
||||
@@ -162,6 +183,8 @@ export class HaNetworkGraph extends LitElement {
|
||||
|
||||
private _followedChart?: EChartsType;
|
||||
|
||||
private _cancelSettledHide?: () => void;
|
||||
|
||||
@query("ha-chart-base") private _baseChart?: HaChartBase;
|
||||
|
||||
constructor() {
|
||||
@@ -180,6 +203,10 @@ export class HaNetworkGraph extends LitElement {
|
||||
this._physicsEnabled =
|
||||
this.data.nodes.length <= PHYSICS_DISABLE_THRESHOLD;
|
||||
}
|
||||
// Before the first render, which counts the visible nodes
|
||||
if (changedProperties.has("hiddenCategories") && this.hiddenCategories) {
|
||||
this._hiddenCategories = this.hiddenCategories;
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
@@ -203,14 +230,19 @@ export class HaNetworkGraph extends LitElement {
|
||||
isMobile,
|
||||
hasHighlightedNodes,
|
||||
this.selectedNode,
|
||||
this.hoverFocus,
|
||||
this._nodePositions,
|
||||
this._pinnedNodes,
|
||||
this._fewVisibleNodes()
|
||||
)}
|
||||
.options=${this._createOptions(this.data?.categories)}
|
||||
.options=${this._createOptions(
|
||||
this.data?.categories,
|
||||
this.hiddenCategories
|
||||
)}
|
||||
height="100%"
|
||||
.extraComponents=${[GraphChart]}
|
||||
@chart-setup=${this._handleChartSetup}
|
||||
@chart-click=${this._handleBaseChartClick}
|
||||
>
|
||||
<slot name="search" slot="search"></slot>
|
||||
<slot name="button" slot="button"></slot>
|
||||
@@ -234,7 +266,10 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
|
||||
private _createOptions = memoizeOne(
|
||||
(categories?: NetworkData["categories"]): HaECOption => ({
|
||||
(
|
||||
categories?: NetworkData["categories"],
|
||||
hiddenCategories?: string[]
|
||||
): HaECOption => ({
|
||||
tooltip: {
|
||||
trigger: "item",
|
||||
confine: true,
|
||||
@@ -246,6 +281,15 @@ export class HaNetworkGraph extends LitElement {
|
||||
...category,
|
||||
icon: category.symbol,
|
||||
})),
|
||||
// Every category, as a category left out keeps its last selection
|
||||
...(hiddenCategories && {
|
||||
selected: Object.fromEntries(
|
||||
(categories ?? []).map((category) => [
|
||||
category.name,
|
||||
!hiddenCategories.includes(category.name),
|
||||
])
|
||||
),
|
||||
}),
|
||||
bottom: 8,
|
||||
},
|
||||
dataZoom: {
|
||||
@@ -311,6 +355,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
isMobile: boolean,
|
||||
hasHighlightedNodes?: boolean,
|
||||
selectedNode?: string,
|
||||
hoverFocus = true,
|
||||
nodePositions: Record<string, { x: number; y: number }> = {},
|
||||
pinnedNodes: string[] = [],
|
||||
fewVisibleNodes = true
|
||||
@@ -345,7 +390,11 @@ export class HaNetworkGraph extends LitElement {
|
||||
},
|
||||
},
|
||||
emphasis: {
|
||||
focus: hasHighlightedNodes ? "self" : isMobile ? "none" : "adjacency",
|
||||
focus: hasHighlightedNodes
|
||||
? "self"
|
||||
: isMobile || !hoverFocus
|
||||
? "none"
|
||||
: "adjacency",
|
||||
},
|
||||
force: {
|
||||
repulsion: [400, 600],
|
||||
@@ -570,12 +619,23 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
// Fired for every drawn frame, so the page can place things next to nodes
|
||||
// while the graph moves, and stays idle when it does not
|
||||
private _handleRendered = () => {
|
||||
fireEvent(this, "network-graph-rendered", undefined, {
|
||||
bubbles: false,
|
||||
composed: false,
|
||||
});
|
||||
};
|
||||
|
||||
private _handleChartSetup() {
|
||||
const chart = this._baseChart?.chart;
|
||||
chart?.getZr().on("click", this._handleEmptyClick);
|
||||
chart?.on("mousedown", this._handleNodeMouseDown);
|
||||
chart?.getZr().on("dragstart", this._handleDragStart);
|
||||
chart?.getZr().on("drag", this._handleDrag);
|
||||
chart?.getZr().on("dragend", this._handleDragEnd);
|
||||
chart?.on("rendered", this._handleRendered);
|
||||
for (const event of LEGEND_SELECT_EVENTS) {
|
||||
chart?.on(event, this._handleLegendChange);
|
||||
}
|
||||
@@ -588,18 +648,22 @@ export class HaNetworkGraph extends LitElement {
|
||||
// last render
|
||||
this.requestUpdate();
|
||||
this._updateFollowing();
|
||||
// The base chart drew the first frame before the listener was added
|
||||
this._handleRendered();
|
||||
}
|
||||
|
||||
private _handleLegendChange = (params: unknown) => {
|
||||
const { selected } = params as { selected: Record<string, boolean> };
|
||||
const fewVisibleNodes = this._fewVisibleNodes();
|
||||
this._setHiddenCategories(
|
||||
(params as { selected: Record<string, boolean> }).selected
|
||||
);
|
||||
this._setHiddenCategories(selected);
|
||||
if (this._fewVisibleNodes() !== fewVisibleNodes) {
|
||||
// The new series option lays out again from where the nodes are now
|
||||
this._saveNodePositions();
|
||||
this.requestUpdate();
|
||||
}
|
||||
fireEvent(this, "network-legend-changed", {
|
||||
hidden: this._hiddenCategories,
|
||||
});
|
||||
};
|
||||
|
||||
private _setHiddenCategories(selected: Record<string, boolean>) {
|
||||
@@ -608,6 +672,65 @@ export class HaNetworkGraph extends LitElement {
|
||||
);
|
||||
}
|
||||
|
||||
// A click next to a small node hits nothing, or a link that runs to its
|
||||
// center, so it clicks the nearest node within nodeClickRadius instead
|
||||
private _handleEmptyClick = (ev: {
|
||||
target?: unknown;
|
||||
offsetX: number;
|
||||
offsetY: number;
|
||||
}) => {
|
||||
if (!ev.target) {
|
||||
this._clickNearestNode(ev.offsetX, ev.offsetY);
|
||||
}
|
||||
};
|
||||
|
||||
// The base chart forwards a click on a link, which is replaced by the node
|
||||
// click, so the page gets one click
|
||||
private _handleBaseChartClick = (
|
||||
ev: HASSDomEvent<HASSDomEvents["chart-click"]>
|
||||
) => {
|
||||
const { dataType, event } = ev.detail;
|
||||
if (
|
||||
dataType === "edge" &&
|
||||
event &&
|
||||
this._clickNearestNode(event.offsetX, event.offsetY)
|
||||
) {
|
||||
ev.stopPropagation();
|
||||
}
|
||||
};
|
||||
|
||||
// Returns whether a node was clicked
|
||||
private _clickNearestNode(offsetX: number, offsetY: number): boolean {
|
||||
const chart = this._baseChart?.chart;
|
||||
if (!this.nodeClickRadius || !chart || chart.isDisposed()) {
|
||||
return false;
|
||||
}
|
||||
const series = this._getGraphSeries(chart);
|
||||
let nearest: { id: string; distance: number } | undefined;
|
||||
series?.getGraph().eachNode((node: any) => {
|
||||
const layout: number[] | undefined = node.getLayout();
|
||||
if (!layout) {
|
||||
return;
|
||||
}
|
||||
const [x, y] = chart.convertToPixel({ seriesId: "network" }, layout);
|
||||
const distance = Math.hypot(x - offsetX, y - offsetY);
|
||||
if (
|
||||
distance <= this.nodeClickRadius &&
|
||||
(!nearest || distance < nearest.distance)
|
||||
) {
|
||||
nearest = { id: node.id, distance };
|
||||
}
|
||||
});
|
||||
if (!nearest) {
|
||||
return false;
|
||||
}
|
||||
fireEvent(this, "chart-click", {
|
||||
dataType: "node",
|
||||
data: { id: nearest.id },
|
||||
} as unknown as HASSDomEvents["chart-click"]);
|
||||
return true;
|
||||
}
|
||||
|
||||
private _handleNodeMouseDown = (params: {
|
||||
dataType?: string;
|
||||
data?: unknown;
|
||||
@@ -735,6 +858,62 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The position of a node in pixels within the graph, or undefined when the
|
||||
* node is not drawn.
|
||||
*/
|
||||
public getNodePosition(id: string): { x: number; y: number } | undefined {
|
||||
const chart = this._baseChart?.chart;
|
||||
if (!chart || chart.isDisposed()) {
|
||||
return undefined;
|
||||
}
|
||||
const series = this._getGraphSeries(chart);
|
||||
const node = series?.getGraph().getNodeById(id);
|
||||
if (!node) {
|
||||
return undefined;
|
||||
}
|
||||
// The layout already holds where a moving node ends up, the drawn symbol
|
||||
// where it is now
|
||||
const transform: number[] | null | undefined = series
|
||||
.getData()
|
||||
.getItemGraphicEl(node.dataIndex)
|
||||
?.getComputedTransform();
|
||||
if (transform) {
|
||||
return { x: transform[4], y: transform[5] };
|
||||
}
|
||||
const position: number[] | undefined = node.getLayout();
|
||||
if (!position) {
|
||||
return undefined;
|
||||
}
|
||||
const [x, y] = chart.convertToPixel({ seriesId: "network" }, position);
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
public hideTooltip(): void {
|
||||
const chart = this._baseChart?.chart;
|
||||
if (!chart || chart.isDisposed()) {
|
||||
return;
|
||||
}
|
||||
chart.dispatchAction({ type: "hideTip" });
|
||||
this._cancelSettledHide?.();
|
||||
// A resize waits for running animations and shows the tooltip again, so
|
||||
// it is hidden once more when the chart has settled. Without a resize it
|
||||
// would hide the next tooltip, so moving the pointer cancels it.
|
||||
const zr = chart.getZr();
|
||||
const hideWhenSettled = () => {
|
||||
this._cancelSettledHide?.();
|
||||
chart.dispatchAction({ type: "hideTip" });
|
||||
};
|
||||
const cancel = () => {
|
||||
chart.off("finished", hideWhenSettled);
|
||||
zr.off("mousemove", cancel);
|
||||
this._cancelSettledHide = undefined;
|
||||
};
|
||||
chart.on("finished", hideWhenSettled);
|
||||
zr.on("mousemove", cancel);
|
||||
this._cancelSettledHide = cancel;
|
||||
}
|
||||
|
||||
private _centerOnSelectedNode = () => {
|
||||
const chart = this._followedChart;
|
||||
if (!chart) {
|
||||
@@ -861,5 +1040,8 @@ declare global {
|
||||
}
|
||||
interface HASSDomEvents {
|
||||
"node-selected": { id: string };
|
||||
// The names of the legend categories that are switched off
|
||||
"network-legend-changed": { hidden: string[] };
|
||||
"network-graph-rendered": undefined;
|
||||
}
|
||||
}
|
||||
@@ -111,6 +111,11 @@ export class HaControlCircularSlider extends LitElement {
|
||||
|
||||
@state() public _lastSlider?: ActiveSlider;
|
||||
|
||||
// Position of the other handle before the active one started pushing it
|
||||
private _lowBeforePush?: number;
|
||||
|
||||
private _highBeforePush?: number;
|
||||
|
||||
private _valueToPercentage(value: number) {
|
||||
return (
|
||||
(clamp(value, this.min, this.max) - this.min) / (this.max - this.min)
|
||||
@@ -122,19 +127,12 @@ export class HaControlCircularSlider extends LitElement {
|
||||
}
|
||||
|
||||
private _steppedValue(value: number) {
|
||||
return Math.round(value / this.step) * this.step;
|
||||
// Rounding to the step can overshoot min/max when they aren't multiples of it
|
||||
return clamp(Math.round(value / this.step) * this.step, this.min, this.max);
|
||||
}
|
||||
|
||||
private _boundedValue(value: number) {
|
||||
const min =
|
||||
this._activeSlider === "high"
|
||||
? Math.min(this._localLow ?? this.max)
|
||||
: this.min;
|
||||
const max =
|
||||
this._activeSlider === "low"
|
||||
? Math.max(this._localHigh ?? this.min)
|
||||
: this.max;
|
||||
return Math.min(Math.max(value, min), max);
|
||||
return Math.min(Math.max(value, this.min), this.max);
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues): void {
|
||||
@@ -152,6 +150,8 @@ export class HaControlCircularSlider extends LitElement {
|
||||
});
|
||||
}
|
||||
if (!this._activeSlider) {
|
||||
this._lowBeforePush = undefined;
|
||||
this._highBeforePush = undefined;
|
||||
if (changedProps.has("value")) {
|
||||
this._localValue = this.value;
|
||||
}
|
||||
@@ -235,9 +235,19 @@ export class HaControlCircularSlider extends LitElement {
|
||||
switch (this._activeSlider) {
|
||||
case "high":
|
||||
this._localHigh = value;
|
||||
// Push the low handle along instead of stopping at it, and let it
|
||||
// return to where it was if the drag comes back
|
||||
if (this._localLow != null) {
|
||||
this._lowBeforePush ??= this._localLow;
|
||||
this._localLow = Math.min(this._lowBeforePush, value);
|
||||
}
|
||||
break;
|
||||
case "low":
|
||||
this._localLow = value;
|
||||
if (this._localHigh != null) {
|
||||
this._highBeforePush ??= this._localHigh;
|
||||
this._localHigh = Math.max(this._highBeforePush, value);
|
||||
}
|
||||
break;
|
||||
case "value":
|
||||
this._localValue = value;
|
||||
|
||||
@@ -82,7 +82,6 @@ const SELECTOR_FALLBACK_VALUES = {
|
||||
},
|
||||
ui_action: undefined,
|
||||
ui_clock_date_format: undefined,
|
||||
ui_clock_time_format: undefined,
|
||||
ui_color: undefined,
|
||||
ui_condition: undefined,
|
||||
ui_state_content: undefined,
|
||||
|
||||
@@ -117,7 +117,6 @@ const SELECTOR_INITIAL_VALUES = {
|
||||
},
|
||||
ui_action: undefined,
|
||||
ui_clock_date_format: undefined,
|
||||
ui_clock_time_format: undefined,
|
||||
ui_color: undefined,
|
||||
ui_condition: () => [],
|
||||
ui_state_content: undefined,
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
import { mdiDelete, mdiPlayBox, mdiPlus } from "@mdi/js";
|
||||
import type { HassEntities } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../common/decorators/consume";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { transform } from "../common/decorators/transform";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { supportsFeature } from "../common/entity/supports-feature";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { statesContext } from "../data/context";
|
||||
import type { MediaPickedEvent } from "../data/media-player";
|
||||
import {
|
||||
MediaClassBrowserSettings,
|
||||
MediaPlayerEntityFeature,
|
||||
} from "../data/media-player";
|
||||
import type { MediaSelector, MediaSelectorValue } from "../data/selector";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import "./ha-alert";
|
||||
import "./ha-form/ha-form";
|
||||
import type { SchemaUnion } from "./ha-form/types";
|
||||
@@ -31,8 +37,6 @@ const EMPTY_FORM = {};
|
||||
|
||||
@customElement("ha-media-item-picker")
|
||||
export class HaMediaItemPicker extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public selector!: MediaSelector;
|
||||
|
||||
@property({ attribute: false }) public value?: MediaSelectorValue;
|
||||
@@ -51,6 +55,26 @@ export class HaMediaItemPicker extends LitElement {
|
||||
filter_entity?: string | string[];
|
||||
};
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@state()
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
@transform<HassEntities | null, boolean>({
|
||||
transformer: function (this: HaMediaItemPicker, states) {
|
||||
const entityId = this._getActiveEntityId();
|
||||
if (!entityId) {
|
||||
return true;
|
||||
}
|
||||
const stateObj = states?.[entityId];
|
||||
return (
|
||||
!!stateObj &&
|
||||
supportsFeature(stateObj, MediaPlayerEntityFeature.BROWSE_MEDIA)
|
||||
);
|
||||
},
|
||||
watch: ["value", "context"],
|
||||
})
|
||||
private _supportsBrowse?: boolean;
|
||||
|
||||
private _contextEntities: string[] | undefined;
|
||||
|
||||
private get _hasAccept(): boolean {
|
||||
@@ -68,13 +92,6 @@ export class HaMediaItemPicker extends LitElement {
|
||||
protected render() {
|
||||
const entityId = this._getActiveEntityId();
|
||||
|
||||
const stateObj = entityId ? this.hass.states[entityId] : undefined;
|
||||
|
||||
const supportsBrowse =
|
||||
!entityId ||
|
||||
(stateObj &&
|
||||
supportsFeature(stateObj, MediaPlayerEntityFeature.BROWSE_MEDIA));
|
||||
|
||||
if (this.selector.media?.image_upload && !this.value) {
|
||||
return html`${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
<ha-picture-upload
|
||||
@@ -98,7 +115,7 @@ export class HaMediaItemPicker extends LitElement {
|
||||
.value=${entityId}
|
||||
.label=${
|
||||
this.label ||
|
||||
this.hass.localize(
|
||||
this._localize(
|
||||
"ui.components.selectors.media.pick_media_player"
|
||||
)
|
||||
}
|
||||
@@ -114,20 +131,19 @@ export class HaMediaItemPicker extends LitElement {
|
||||
`
|
||||
}
|
||||
${
|
||||
!supportsBrowse
|
||||
this._supportsBrowse === false
|
||||
? html`
|
||||
${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
<ha-alert>
|
||||
${this.hass.localize(
|
||||
${this._localize(
|
||||
"ui.components.selectors.media.browse_not_supported"
|
||||
)}
|
||||
</ha-alert>
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${this.value || EMPTY_FORM}
|
||||
.schema=${MANUAL_SCHEMA}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
.computeHelper=${this._computeHelperCallback}
|
||||
.computeLabel=${this._computeLabel(this._localize)}
|
||||
.computeHelper=${this._computeHelper(this._localize)}
|
||||
></ha-form>
|
||||
`
|
||||
: html`${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
@@ -137,9 +153,7 @@ export class HaMediaItemPicker extends LitElement {
|
||||
role="button"
|
||||
aria-label=${
|
||||
!this.value?.media_content_id
|
||||
? this.hass.localize(
|
||||
"ui.components.selectors.media.pick_media"
|
||||
)
|
||||
? this._localize("ui.components.selectors.media.pick_media")
|
||||
: this.value.metadata?.title || this.value.media_content_id
|
||||
}
|
||||
@click=${this._pickMedia}
|
||||
@@ -196,7 +210,7 @@ export class HaMediaItemPicker extends LitElement {
|
||||
<div class="title">
|
||||
${
|
||||
!this.value?.media_content_id
|
||||
? this.hass.localize(
|
||||
? this._localize(
|
||||
"ui.components.selectors.media.pick_media"
|
||||
)
|
||||
: this.value.metadata?.title ||
|
||||
@@ -209,7 +223,7 @@ export class HaMediaItemPicker extends LitElement {
|
||||
: html`
|
||||
<div class="delete">
|
||||
<ha-icon-button
|
||||
.label=${this.hass.localize("ui.common.delete")}
|
||||
.label=${this._localize("ui.common.delete")}
|
||||
.path=${mdiDelete}
|
||||
@click=${this._clearValue}
|
||||
></ha-icon-button>
|
||||
@@ -227,7 +241,7 @@ export class HaMediaItemPicker extends LitElement {
|
||||
variant="danger"
|
||||
@click=${this._clearValue}
|
||||
>
|
||||
${this.hass.localize(
|
||||
${this._localize(
|
||||
"ui.components.picture-upload.clear_picture"
|
||||
)}
|
||||
</ha-button>
|
||||
@@ -243,15 +257,17 @@ export class HaMediaItemPicker extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<typeof MANUAL_SCHEMA>
|
||||
): string =>
|
||||
this.hass.localize(`ui.components.selectors.media.${schema.name}`);
|
||||
private _computeLabel = memoizeOne(
|
||||
(localize: LocalizeFunc) =>
|
||||
(schema: SchemaUnion<typeof MANUAL_SCHEMA>): string =>
|
||||
localize(`ui.components.selectors.media.${schema.name}`)
|
||||
);
|
||||
|
||||
private _computeHelperCallback = (
|
||||
schema: SchemaUnion<typeof MANUAL_SCHEMA>
|
||||
): string =>
|
||||
this.hass.localize(`ui.components.selectors.media.${schema.name}_detail`);
|
||||
private _computeHelper = memoizeOne(
|
||||
(localize: LocalizeFunc) =>
|
||||
(schema: SchemaUnion<typeof MANUAL_SCHEMA>): string =>
|
||||
localize(`ui.components.selectors.media.${schema.name}_detail`)
|
||||
);
|
||||
|
||||
private _entityChanged(ev: CustomEvent) {
|
||||
ev.stopPropagation();
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { mdiMagnify, mdiMapSearchOutline } from "@mdi/js";
|
||||
import type { HassConfig } from "home-assistant-js-websocket";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import { transform } from "../../common/decorators/transform";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import { configContext, internationalizationContext } from "../../data/context";
|
||||
import type {
|
||||
LocationSelector,
|
||||
LocationSelectorValue,
|
||||
@@ -14,7 +18,10 @@ import {
|
||||
formatOpenStreetMapPlace,
|
||||
searchPlaces,
|
||||
} from "../../data/openstreetmap";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import type {
|
||||
HomeAssistantConfig,
|
||||
HomeAssistantInternationalization,
|
||||
} from "../../types";
|
||||
import type { SchemaUnion } from "../ha-form/types";
|
||||
import type { HaListItemButton } from "../item/ha-list-item-button";
|
||||
import { searchResultsStatus } from "../list/search-results-status";
|
||||
@@ -28,6 +35,7 @@ import "../ha-alert";
|
||||
import "../ha-icon-button";
|
||||
import "../item/ha-list-item-button";
|
||||
import "../list/ha-list-base";
|
||||
import "../animation/ha-fade-in";
|
||||
import "../ha-spinner";
|
||||
import "../ha-svg-icon";
|
||||
import "../input/ha-input";
|
||||
@@ -39,8 +47,6 @@ import {
|
||||
|
||||
@customElement("ha-selector-location")
|
||||
export class HaLocationSelector extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public selector!: LocationSelector;
|
||||
|
||||
@property({ type: Object }) public value?: LocationSelectorValue;
|
||||
@@ -51,6 +57,17 @@ export class HaLocationSelector extends LitElement {
|
||||
|
||||
@property({ type: Boolean, reflect: true }) public disabled = false;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: HomeAssistantInternationalization;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, HassConfig | undefined>({
|
||||
transformer: ({ config }) => config ?? undefined,
|
||||
})
|
||||
private _hassConfig?: HassConfig;
|
||||
|
||||
@state() private _working = false;
|
||||
|
||||
@state() private _places?: OpenStreetMapPlace[] | null;
|
||||
@@ -106,10 +123,10 @@ export class HaLocationSelector extends LitElement {
|
||||
);
|
||||
|
||||
protected willUpdate() {
|
||||
if (!this.value) {
|
||||
if (!this.value && this._hassConfig) {
|
||||
this.value = {
|
||||
latitude: this.hass.config.latitude,
|
||||
longitude: this.hass.config.longitude,
|
||||
latitude: this._hassConfig.latitude,
|
||||
longitude: this._hassConfig.longitude,
|
||||
radius: this.selector.location?.radius ? DEFAULT_RADIUS : undefined,
|
||||
};
|
||||
}
|
||||
@@ -121,7 +138,7 @@ export class HaLocationSelector extends LitElement {
|
||||
|
||||
<div class="location-search" @keydown=${this._searchKeyDown}>
|
||||
<ha-input
|
||||
label=${this.hass.localize(
|
||||
label=${this._i18n.localize(
|
||||
"ui.components.selectors.location.address_label"
|
||||
)}
|
||||
.disabled=${this.disabled}
|
||||
@@ -137,7 +154,7 @@ export class HaLocationSelector extends LitElement {
|
||||
: html`<ha-icon-button
|
||||
slot="end"
|
||||
.path=${mdiMapSearchOutline}
|
||||
.label=${this.hass.localize("ui.common.search")}
|
||||
.label=${this._i18n.localize("ui.common.search")}
|
||||
.disabled=${this.disabled}
|
||||
@click=${this._searchButtonClicked}
|
||||
></ha-icon-button>`
|
||||
@@ -147,7 +164,7 @@ export class HaLocationSelector extends LitElement {
|
||||
${
|
||||
this._searchError
|
||||
? html`<ha-alert alert-type="error">
|
||||
${this.hass.localize(
|
||||
${this._i18n.localize(
|
||||
"ui.components.selectors.location.search_error"
|
||||
)}
|
||||
</ha-alert>`
|
||||
@@ -165,7 +182,7 @@ export class HaLocationSelector extends LitElement {
|
||||
Array.isArray(this._places) && this._places.length
|
||||
? html`
|
||||
<ha-list-base
|
||||
aria-label=${this.hass.localize(
|
||||
aria-label=${this._i18n.localize(
|
||||
"ui.components.selectors.location.search_results_label"
|
||||
)}
|
||||
>
|
||||
@@ -174,13 +191,13 @@ export class HaLocationSelector extends LitElement {
|
||||
`
|
||||
: this._places?.length === 0
|
||||
? html`<p class="search-no-results">
|
||||
${this.hass.localize("ui.components.combo-box.no_match")}
|
||||
${this._i18n.localize("ui.components.combo-box.no_match")}
|
||||
</p>`
|
||||
: nothing
|
||||
}
|
||||
|
||||
<p class="attribution">
|
||||
${this.hass.localize(
|
||||
${this._i18n.localize(
|
||||
"ui.components.selectors.location.search_disclosure",
|
||||
{
|
||||
openstreetmap: html`<a
|
||||
@@ -193,7 +210,7 @@ export class HaLocationSelector extends LitElement {
|
||||
href="https://wiki.osmfoundation.org/wiki/Privacy_Policy"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>${this.hass.localize(
|
||||
>${this._i18n.localize(
|
||||
"ui.components.selectors.location.osm_privacy_policy"
|
||||
)}</a
|
||||
>`,
|
||||
@@ -202,18 +219,27 @@ export class HaLocationSelector extends LitElement {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ha-locations-editor
|
||||
class="flex"
|
||||
.helper=${this.helper}
|
||||
.locations=${this._location(this.selector, this.value)}
|
||||
@location-updated=${this._locationChanged}
|
||||
@radius-updated=${this._radiusChanged}
|
||||
pin-on-click
|
||||
></ha-locations-editor>
|
||||
${
|
||||
this._hassConfig
|
||||
? html`<ha-locations-editor
|
||||
class="flex"
|
||||
.helper=${this.helper}
|
||||
.locations=${this._location(
|
||||
this.selector,
|
||||
this._hassConfig,
|
||||
this.value
|
||||
)}
|
||||
@location-updated=${this._locationChanged}
|
||||
@radius-updated=${this._radiusChanged}
|
||||
pin-on-click
|
||||
></ha-locations-editor>`
|
||||
: html`<ha-fade-in .delay=${500}
|
||||
><ha-spinner></ha-spinner
|
||||
></ha-fade-in>`
|
||||
}
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.schema=${this._schema(
|
||||
this.hass.localize,
|
||||
this._i18n.localize,
|
||||
this.selector.location?.radius,
|
||||
this.selector.location?.radius_readonly
|
||||
)}
|
||||
@@ -228,6 +254,7 @@ export class HaLocationSelector extends LitElement {
|
||||
private _location = memoizeOne(
|
||||
(
|
||||
selector: LocationSelector,
|
||||
hassConfig: HassConfig,
|
||||
value?: LocationSelectorValue
|
||||
): MarkerLocation[] => {
|
||||
const computedStyles = getComputedStyle(this);
|
||||
@@ -240,11 +267,11 @@ export class HaLocationSelector extends LitElement {
|
||||
id: "location",
|
||||
latitude:
|
||||
!value || isNaN(value.latitude)
|
||||
? this.hass.config.latitude
|
||||
? hassConfig.latitude
|
||||
: value.latitude,
|
||||
longitude:
|
||||
!value || isNaN(value.longitude)
|
||||
? this.hass.config.longitude
|
||||
? hassConfig.longitude
|
||||
: value.longitude,
|
||||
radius: selector.location?.radius
|
||||
? value?.radius || DEFAULT_RADIUS
|
||||
@@ -286,7 +313,7 @@ export class HaLocationSelector extends LitElement {
|
||||
entry: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
): string => {
|
||||
if (entry.name) {
|
||||
return this.hass.localize(
|
||||
return this._i18n.localize(
|
||||
`ui.components.selectors.location.${entry.name}`
|
||||
);
|
||||
}
|
||||
@@ -337,12 +364,17 @@ export class HaLocationSelector extends LitElement {
|
||||
this._status = undefined;
|
||||
|
||||
try {
|
||||
this._places = await searchPlaces(searchTerm, this.hass, true, 3);
|
||||
this._places = await searchPlaces(
|
||||
searchTerm,
|
||||
this._i18n.locale.language,
|
||||
true,
|
||||
3
|
||||
);
|
||||
this._status = searchResultsStatus(
|
||||
searchTerm,
|
||||
this._places,
|
||||
() => true,
|
||||
this.hass.localize
|
||||
this._i18n.localize
|
||||
);
|
||||
} catch (_err) {
|
||||
this._places = undefined;
|
||||
@@ -398,7 +430,7 @@ export class HaLocationSelector extends LitElement {
|
||||
this._input?.focus({ preventScroll: true });
|
||||
}
|
||||
this._places = undefined;
|
||||
this._status = this.hass.localize(
|
||||
this._status = this._i18n.localize(
|
||||
"ui.components.selectors.location.selected_location",
|
||||
{ location: place.display_name }
|
||||
);
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { html, LitElement, type TemplateResult } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import type { MediaSelector, MediaSelectorValue } from "../../data/selector";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import "../ha-media-item-picker";
|
||||
import { ensureArray } from "../../common/array/ensure-array";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
|
||||
@customElement("ha-selector-media")
|
||||
export class HaMediaSelector extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public selector!: MediaSelector;
|
||||
|
||||
@property({ attribute: false }) public value?:
|
||||
@@ -34,7 +31,6 @@ export class HaMediaSelector extends LitElement {
|
||||
changeCallback?
|
||||
): TemplateResult {
|
||||
return html`<ha-media-item-picker
|
||||
.hass=${this.hass}
|
||||
.context=${this.context}
|
||||
.selector=${this.selector}
|
||||
.value=${value}
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import { useAmPm } from "../../common/datetime/use_am_pm";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { internationalizationContext } from "../../data/context";
|
||||
import type { UiClockTimeFormatSelector } from "../../data/selector";
|
||||
import type { FrontendLocaleData } from "../../data/translation";
|
||||
import { TimeFormat } from "../../data/translation";
|
||||
import "../ha-select";
|
||||
import type { HaSelectOption, HaSelectSelectEvent } from "../ha-select";
|
||||
|
||||
type ClockTimeFormatOption = TimeFormat | "auto";
|
||||
|
||||
const CLOCK_TIME_FORMAT_OPTIONS: ClockTimeFormatOption[] = [
|
||||
"auto",
|
||||
...Object.values(TimeFormat),
|
||||
];
|
||||
|
||||
// 9:30 PM or 21:30, to show what each format looks like
|
||||
const EXAMPLE_TIME = new Date(2000, 0, 1, 21, 30);
|
||||
|
||||
const formatExample = (locale: FrontendLocaleData, timeFormat?: TimeFormat) => {
|
||||
const formatLocale = timeFormat
|
||||
? { ...locale, time_format: timeFormat }
|
||||
: locale;
|
||||
|
||||
return new Intl.DateTimeFormat(locale.language, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
hourCycle: useAmPm(formatLocale) ? "h12" : "h23",
|
||||
}).format(EXAMPLE_TIME);
|
||||
};
|
||||
|
||||
@customElement("ha-selector-ui_clock_time_format")
|
||||
export class HaSelectorUiClockTimeFormat extends LitElement {
|
||||
@property({ attribute: false }) public selector!: UiClockTimeFormatSelector;
|
||||
|
||||
@property() public value?: TimeFormat;
|
||||
|
||||
@property() public label?: string;
|
||||
|
||||
@property() public helper?: string;
|
||||
|
||||
@property({ type: Boolean }) public disabled = false;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: ContextType<typeof internationalizationContext>;
|
||||
|
||||
private _options = memoizeOne(
|
||||
(i18n: ContextType<typeof internationalizationContext>): HaSelectOption[] =>
|
||||
CLOCK_TIME_FORMAT_OPTIONS.map((value) => ({
|
||||
value,
|
||||
label:
|
||||
value === "auto"
|
||||
? i18n.localize("ui.components.clock-time-format-picker.auto")
|
||||
: i18n.localize(
|
||||
`ui.components.clock-time-format-picker.formats.${value}`
|
||||
),
|
||||
secondary: formatExample(
|
||||
i18n.locale,
|
||||
value === "auto" ? undefined : value
|
||||
),
|
||||
}))
|
||||
);
|
||||
|
||||
protected render() {
|
||||
return html`
|
||||
<ha-select
|
||||
.label=${this.label}
|
||||
.helper=${this.helper}
|
||||
.value=${this.value ?? "auto"}
|
||||
.options=${this._options(this._i18n)}
|
||||
.disabled=${this.disabled}
|
||||
@selected=${this._selected}
|
||||
></ha-select>
|
||||
`;
|
||||
}
|
||||
|
||||
private _selected(ev: HaSelectSelectEvent<ClockTimeFormatOption>): void {
|
||||
ev.stopPropagation();
|
||||
|
||||
const value = ev.detail.value;
|
||||
|
||||
fireEvent(this, "value-changed", {
|
||||
value: value === "auto" ? undefined : value,
|
||||
});
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
ha-select {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-selector-ui_clock_time_format": HaSelectorUiClockTimeFormat;
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,6 @@ const LOAD_ELEMENTS = {
|
||||
color_temp: () => import("./ha-selector-color-temp"),
|
||||
ui_action: () => import("./ha-selector-ui-action"),
|
||||
ui_clock_date_format: () => import("./ha-selector-ui-clock-date-format"),
|
||||
ui_clock_time_format: () => import("./ha-selector-ui-clock-time-format"),
|
||||
ui_color: () => import("./ha-selector-ui-color"),
|
||||
ui_condition: () => import("./ha-selector-ui-condition"),
|
||||
ui_state_content: () => import("./ha-selector-ui-state-content"),
|
||||
|
||||
@@ -474,7 +474,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
}
|
||||
|
||||
private _renderPanel(panel: PanelInfo, isSelected: boolean) {
|
||||
const title = getPanelTitle(this.hass, panel);
|
||||
const title = getPanelTitle(this.hass.localize, panel);
|
||||
const urlPath = panel.url_path;
|
||||
const icon = getPanelIcon(panel);
|
||||
const iconPath = getPanelIconPath(panel);
|
||||
|
||||
@@ -1812,6 +1812,20 @@ export class HaMap extends ReactiveElement {
|
||||
#map.clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
/* Bubble avatars open their entity; the expanded bubble around them
|
||||
takes no click of its own */
|
||||
.maplibregl-marker ha-entity-marker {
|
||||
cursor: pointer;
|
||||
}
|
||||
/* A drag that starts on a marker pans the map like anywhere else;
|
||||
markers that drag themselves keep their own cursor */
|
||||
.maplibregl-canvas-container.maplibregl-interactive:active
|
||||
.maplibregl-marker:not(.maplibregl-marker-draggable),
|
||||
.maplibregl-canvas-container.maplibregl-interactive:active
|
||||
.maplibregl-marker:not(.maplibregl-marker-draggable)
|
||||
ha-entity-marker {
|
||||
cursor: grabbing !important;
|
||||
}
|
||||
.maplibregl-marker {
|
||||
transition:
|
||||
opacity var(--ha-animation-duration-fast),
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
HassEntityBase,
|
||||
} from "home-assistant-js-websocket";
|
||||
import { supportsFeature } from "../common/entity/supports-feature";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { showEnterCodeDialog } from "../dialogs/enter-code/show-enter-code-dialog";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import { getExtendedEntityRegistryEntry } from "./entity/entity_registry";
|
||||
@@ -108,7 +109,9 @@ export const supportedAlarmModes = (stateObj: AlarmControlPanelEntity) =>
|
||||
|
||||
export const setProtectedAlarmControlPanelMode = async (
|
||||
element: HTMLElement,
|
||||
hass: Pick<HomeAssistant, "callService" | "localize" | "callWS">,
|
||||
callService: HomeAssistant["callService"],
|
||||
callWS: HomeAssistant["callWS"],
|
||||
localize: LocalizeFunc,
|
||||
stateObj: AlarmControlPanelEntity,
|
||||
mode: AlarmMode
|
||||
) => {
|
||||
@@ -123,7 +126,7 @@ export const setProtectedAlarmControlPanelMode = async (
|
||||
(mode === "disarmed" && stateObj.attributes.code_format)
|
||||
) {
|
||||
const entry = await getExtendedEntityRegistryEntry(
|
||||
hass.callWS,
|
||||
callWS,
|
||||
stateObj.entity_id
|
||||
).catch(() => undefined);
|
||||
const defaultCode = entry?.options?.alarm_control_panel?.default_code;
|
||||
@@ -133,10 +136,10 @@ export const setProtectedAlarmControlPanelMode = async (
|
||||
|
||||
const response = await showEnterCodeDialog(element, {
|
||||
codeFormat: stateObj.attributes.code_format,
|
||||
title: hass.localize(
|
||||
title: localize(
|
||||
`ui.card.alarm_control_panel.${disarm ? "disarm" : "arm"}`
|
||||
),
|
||||
submitText: hass.localize(
|
||||
submitText: localize(
|
||||
`ui.card.alarm_control_panel.${disarm ? "disarm" : "arm"}`
|
||||
),
|
||||
});
|
||||
@@ -147,7 +150,7 @@ export const setProtectedAlarmControlPanelMode = async (
|
||||
}
|
||||
}
|
||||
|
||||
await hass.callService("alarm_control_panel", service, {
|
||||
await callService("alarm_control_panel", service, {
|
||||
entity_id: stateObj.entity_id,
|
||||
code,
|
||||
});
|
||||
|
||||
@@ -103,3 +103,23 @@ export const CLIMATE_HVAC_MODE_ICONS: Record<HvacMode, string> = {
|
||||
|
||||
export const climateHvacModeIcon = (mode: string) =>
|
||||
CLIMATE_HVAC_MODE_ICONS[mode] || mdiThermostat;
|
||||
|
||||
export type ClimateTarget = "value" | "low" | "high";
|
||||
|
||||
/**
|
||||
* The targets to change when one target is set. A low or high target that
|
||||
* passes the other one pushes it along, so the range never ends up inverted.
|
||||
*/
|
||||
export const pushTargetTemperature = (
|
||||
current: Partial<Record<ClimateTarget, number>>,
|
||||
target: ClimateTarget,
|
||||
value: number
|
||||
): Partial<Record<ClimateTarget, number>> => {
|
||||
if (target === "low" && current.high != null && value > current.high) {
|
||||
return { low: value, high: value };
|
||||
}
|
||||
if (target === "high" && current.low != null && value < current.low) {
|
||||
return { low: value, high: value };
|
||||
}
|
||||
return { [target]: value };
|
||||
};
|
||||
@@ -158,7 +158,12 @@ export const computeNavigationPathInfo = (
|
||||
const isDashboard = panel?.component_name === "lovelace";
|
||||
|
||||
const panelInfo: NavigationPathInfo = {
|
||||
label: getPanelTitleFromUrlPath(options, panelUrlPath) || panelUrlPath,
|
||||
label:
|
||||
getPanelTitleFromUrlPath(
|
||||
options.localize,
|
||||
options.panels,
|
||||
panelUrlPath
|
||||
) || panelUrlPath,
|
||||
icon: panelIcon || (isDashboard ? "mdi:view-dashboard" : undefined),
|
||||
iconPath: panelIconPath || mdiLink,
|
||||
};
|
||||
|
||||
@@ -4,8 +4,9 @@ export const setDateTimeValue = (
|
||||
callService: HomeAssistantApi["callService"],
|
||||
entityId: string,
|
||||
datetime: Date
|
||||
) =>
|
||||
) => {
|
||||
callService("datetime", "set_value", {
|
||||
entity_id: entityId,
|
||||
datetime: datetime.toISOString(),
|
||||
});
|
||||
};
|
||||
@@ -32,6 +32,7 @@ import type { EntityNameItem } from "../common/entity/entity_name_config";
|
||||
import { formatNumberWithUnit } from "../common/number/format_number";
|
||||
import { normalizeValueBySIPrefix } from "../common/number/normalize-by-si-prefix";
|
||||
import { groupBy } from "../common/util/group-by";
|
||||
import { generateUuidV4 } from "../common/util/uuid";
|
||||
import type { HomeAssistant, HomeAssistantRegistries } from "../types";
|
||||
import { fileDownload } from "../util/file_download";
|
||||
import type {
|
||||
@@ -343,6 +344,31 @@ export interface WaterSourceTypeEnergyPreference {
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export type FixedCostType = "grid" | "gas" | "water";
|
||||
|
||||
export type FixedCostPeriod = "day" | "month" | "year";
|
||||
|
||||
export interface FixedCostEnergyPreference {
|
||||
id: string;
|
||||
type: FixedCostType;
|
||||
name: string;
|
||||
// Charged at the start of each period, exactly one of these is set
|
||||
number_amount: number | null;
|
||||
entity_amount: string | null;
|
||||
period: FixedCostPeriod;
|
||||
}
|
||||
|
||||
export const emptyFixedCostEnergyPreference = (
|
||||
type: FixedCostType
|
||||
): FixedCostEnergyPreference => ({
|
||||
id: generateUuidV4(),
|
||||
type,
|
||||
name: "",
|
||||
number_amount: null,
|
||||
entity_amount: null,
|
||||
period: "day",
|
||||
});
|
||||
|
||||
export type EnergySource =
|
||||
| SolarSourceTypeEnergyPreference
|
||||
| HomeSourceTypeEnergyPreference
|
||||
@@ -356,6 +382,7 @@ export interface EnergyPreferences {
|
||||
device_consumption: DeviceConsumptionEnergyPreference[];
|
||||
device_consumption_water: DeviceConsumptionEnergyPreference[];
|
||||
device_consumption_gas: DeviceConsumptionEnergyPreference[];
|
||||
fixed_costs: FixedCostEnergyPreference[];
|
||||
}
|
||||
|
||||
export const EMPTY_PREFERENCES: EnergyPreferences = {
|
||||
@@ -363,10 +390,13 @@ export const EMPTY_PREFERENCES: EnergyPreferences = {
|
||||
device_consumption: [],
|
||||
device_consumption_water: [],
|
||||
device_consumption_gas: [],
|
||||
fixed_costs: [],
|
||||
};
|
||||
|
||||
export interface EnergyInfo {
|
||||
cost_sensors: Record<string, string>;
|
||||
// Fixed cost id to the entity ID of its cost sensor
|
||||
fixed_cost_sensors: Record<string, string>;
|
||||
solar_forecast_domains: string[];
|
||||
}
|
||||
|
||||
@@ -381,6 +411,7 @@ export interface EnergyPreferencesValidation {
|
||||
device_consumption: EnergyValidationIssue[][];
|
||||
device_consumption_water: EnergyValidationIssue[][];
|
||||
device_consumption_gas: EnergyValidationIssue[][];
|
||||
fixed_costs: EnergyValidationIssue[][];
|
||||
}
|
||||
|
||||
export const getEnergyInfo = (callWS: HomeAssistant["callWS"]) =>
|
||||
@@ -443,6 +474,30 @@ export interface EnergySourceByType {
|
||||
export const energySourcesByType = (prefs: EnergyPreferences) =>
|
||||
groupBy(prefs.energy_sources, (item) => item.type) as EnergySourceByType;
|
||||
|
||||
export type FixedCostsByType = Partial<
|
||||
Record<FixedCostType, FixedCostEnergyPreference[]>
|
||||
>;
|
||||
|
||||
export const fixedCostsByType = (prefs: EnergyPreferences) =>
|
||||
groupBy(prefs.fixed_costs, (item) => item.type) as FixedCostsByType;
|
||||
|
||||
/** Sum of the fixed costs, or undefined without cost data. */
|
||||
export const calculateFixedCostTotal = (
|
||||
fixedCosts: FixedCostEnergyPreference[],
|
||||
info: EnergyInfo,
|
||||
stats: Statistics
|
||||
): number | undefined => {
|
||||
let total: number | undefined;
|
||||
for (const fixedCost of fixedCosts) {
|
||||
const statId = info.fixed_cost_sensors[fixedCost.id];
|
||||
const cost = statId ? calculateStatisticSumGrowth(stats[statId]) : null;
|
||||
if (cost !== null) {
|
||||
total = (total ?? 0) + cost;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
};
|
||||
|
||||
/** Import cost minus export compensation, or undefined without cost data. */
|
||||
export const calculateGridNetCost = (
|
||||
sources: GridSourceTypeEnergyPreference[],
|
||||
@@ -758,6 +813,15 @@ export const getReferencedStatisticIds = (
|
||||
...prefs.device_consumption_gas.map((d) => d.stat_consumption)
|
||||
);
|
||||
}
|
||||
for (const fixedCost of prefs.fixed_costs) {
|
||||
if (includeTypes && !includeTypes.includes(fixedCost.type)) {
|
||||
continue;
|
||||
}
|
||||
const costStatId = info.fixed_cost_sensors[fixedCost.id];
|
||||
if (costStatId) {
|
||||
statIDs.push(costStatId);
|
||||
}
|
||||
}
|
||||
|
||||
return statIDs;
|
||||
};
|
||||
@@ -2941,6 +3005,13 @@ export const downloadEnergyData = (
|
||||
printCategory("device_consumption_gas", gasDevices, state.gasUnit);
|
||||
}
|
||||
|
||||
energyData.prefs.fixed_costs.forEach((fixedCost) => {
|
||||
const costId = state.info.fixed_cost_sensors[fixedCost.id];
|
||||
if (costId) {
|
||||
processStat(costId, `${fixedCost.type}_fixed_cost`, currency);
|
||||
}
|
||||
});
|
||||
|
||||
const { summedData } = getSummedData(state);
|
||||
const { consumption } = computeConsumptionData(summedData, undefined);
|
||||
|
||||
|
||||
@@ -77,6 +77,10 @@ export const filterGroupsWithListedMembers = (
|
||||
): string[] => {
|
||||
const listed = new Set(entityIds);
|
||||
const hasListedDescendant = (groupId: string): boolean => {
|
||||
const groupObj = states[groupId];
|
||||
if (!groupObj || !computeGroupMemberIds(groupObj)) {
|
||||
return false;
|
||||
}
|
||||
const seen = new Set([groupId]);
|
||||
const queue = [groupId];
|
||||
while (queue.length) {
|
||||
|
||||
+30
-2
@@ -250,13 +250,16 @@ export type IconCategory =
|
||||
| "services"
|
||||
| "triggers"
|
||||
| "conditions"
|
||||
| "integration_category";
|
||||
| "integration_category"
|
||||
| "integration_connectivity";
|
||||
|
||||
export type IntegrationCategoryIcons = Record<
|
||||
string,
|
||||
{ default: string; subcategory?: Record<string, { default: string }> }
|
||||
>;
|
||||
|
||||
export type IntegrationConnectivityIcons = Record<string, { default: string }>;
|
||||
|
||||
interface CategoryType {
|
||||
entity: PlatformIcons;
|
||||
entity_component: ComponentIcons;
|
||||
@@ -264,6 +267,7 @@ interface CategoryType {
|
||||
triggers: TriggerIcons;
|
||||
conditions: ConditionIcons;
|
||||
integration_category: IntegrationCategoryIcons;
|
||||
integration_connectivity: IntegrationConnectivityIcons;
|
||||
}
|
||||
|
||||
export const getHassIcons = async <T extends IconCategory>(
|
||||
@@ -334,7 +338,10 @@ export const getComponentIcons = async (
|
||||
export const getCategoryIcons = async <
|
||||
T extends Exclude<
|
||||
IconCategory,
|
||||
"entity" | "entity_component" | "integration_category"
|
||||
| "entity"
|
||||
| "entity_component"
|
||||
| "integration_category"
|
||||
| "integration_connectivity"
|
||||
>,
|
||||
>(
|
||||
connection: Connection,
|
||||
@@ -775,3 +782,24 @@ export const getIntegrationCategoryIcons = async (
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
let integrationConnectivityIcons:
|
||||
ReturnType<typeof getHassIcons<"integration_connectivity">> | undefined;
|
||||
|
||||
export const getIntegrationConnectivityIcons = async (
|
||||
connection: Connection
|
||||
): Promise<IntegrationConnectivityIcons | undefined> => {
|
||||
// Cache the request itself, so callers while it loads share it
|
||||
integrationConnectivityIcons ??= getHassIcons(
|
||||
connection,
|
||||
"integration_connectivity",
|
||||
"homeassistant"
|
||||
);
|
||||
try {
|
||||
const result = await integrationConnectivityIcons;
|
||||
return result.resources.homeassistant;
|
||||
} catch (_err) {
|
||||
integrationConnectivityIcons = undefined;
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
@@ -38,8 +38,7 @@ export const setInputDateTimeValue = (
|
||||
date: string | undefined = undefined
|
||||
) => {
|
||||
const param = { entity_id: entityId, time, date };
|
||||
|
||||
return callService("input_datetime", "set_datetime", param);
|
||||
callService("input_datetime", "set_datetime", param);
|
||||
};
|
||||
|
||||
export const fetchInputDateTime = (hass: HomeAssistant) =>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import type { IntegrationConnectivityIcons } from "./icons";
|
||||
|
||||
// The name of a connectivity, like `zigbee`. Empty for one this Home Assistant
|
||||
// doesn't know.
|
||||
export const integrationConnectivityName = (
|
||||
localize: LocalizeFunc,
|
||||
slug: string
|
||||
): string =>
|
||||
localize(`component.homeassistant.integration_connectivity.${slug}.name`);
|
||||
|
||||
export const integrationConnectivityIcon = (
|
||||
icons: IntegrationConnectivityIcons | undefined,
|
||||
slug: string
|
||||
): string | undefined => icons?.[slug]?.default;
|
||||
@@ -10,6 +10,9 @@ export interface RepositoryBase {
|
||||
can_install: boolean;
|
||||
category: RepositoryType;
|
||||
config_flow: boolean;
|
||||
// How an integration connects, like `zigbee` or `cloud`. Empty for other
|
||||
// repositories and for integrations that don't set it.
|
||||
connectivity?: string[];
|
||||
custom: boolean;
|
||||
description: string;
|
||||
domain: string | null;
|
||||
|
||||
@@ -62,14 +62,14 @@ export const formatOpenStreetMapPlace = (
|
||||
|
||||
export const searchPlaces = (
|
||||
address: string,
|
||||
hass: HomeAssistant,
|
||||
language: string,
|
||||
addressdetails?: boolean,
|
||||
limit?: number
|
||||
): Promise<OpenStreetMapPlace[]> => {
|
||||
const params = new URLSearchParams({
|
||||
q: address,
|
||||
format: "jsonv2",
|
||||
"accept-language": hass.locale.language,
|
||||
"accept-language": language,
|
||||
email: "[email protected]",
|
||||
});
|
||||
if (limit) {
|
||||
|
||||
+12
-8
@@ -8,9 +8,12 @@ import {
|
||||
mdiMap,
|
||||
mdiPlayBoxMultiple,
|
||||
} from "@mdi/js";
|
||||
import type { LocalizeKeys } from "../common/translations/localize";
|
||||
import type {
|
||||
LocalizeFunc,
|
||||
LocalizeKeys,
|
||||
} from "../common/translations/localize";
|
||||
import type { PageNavigation } from "../layouts/hass-tabs-subpage";
|
||||
import type { HomeAssistant, PanelInfo } from "../types";
|
||||
import type { HomeAssistant, PanelInfo, Panels } from "../types";
|
||||
import { MARKETPLACE_NAME } from "../common/translations/name-placeholders";
|
||||
|
||||
export const APP_PANEL = "app";
|
||||
@@ -66,7 +69,7 @@ export const getPanelNameTranslationKey = (panel: PanelInfo) => {
|
||||
};
|
||||
|
||||
export const getPanelTitle = (
|
||||
hass: Pick<HomeAssistant, "localize">,
|
||||
localize: LocalizeFunc,
|
||||
panel: PanelInfo
|
||||
): string | undefined => {
|
||||
if (panel.url_path === "marketplace") {
|
||||
@@ -75,18 +78,19 @@ export const getPanelTitle = (
|
||||
|
||||
const translationKey = getPanelNameTranslationKey(panel);
|
||||
|
||||
return hass.localize(translationKey) || panel.title || undefined;
|
||||
return localize(translationKey) || panel.title || undefined;
|
||||
};
|
||||
|
||||
export const getPanelTitleFromUrlPath = (
|
||||
hass: Pick<HomeAssistant, "localize" | "panels">,
|
||||
localize: LocalizeFunc,
|
||||
panels: Panels,
|
||||
urlPath: string
|
||||
): string | undefined => {
|
||||
if (!hass.panels) {
|
||||
if (!panels) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const panel = Object.values(hass.panels).find(
|
||||
const panel = Object.values(panels).find(
|
||||
(p: PanelInfo): boolean => p.url_path === urlPath
|
||||
);
|
||||
|
||||
@@ -94,7 +98,7 @@ export const getPanelTitleFromUrlPath = (
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return getPanelTitle(hass, panel);
|
||||
return getPanelTitle(localize, panel);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -57,7 +57,7 @@ const generateNavigationPanelCommands = (
|
||||
.map(([_panelKey, panel]) => {
|
||||
const icon = getPanelIcon(panel) || "mdi:view-dashboard";
|
||||
|
||||
const primary = getPanelTitle({ localize }, panel) || panel.url_path;
|
||||
const primary = getPanelTitle(localize, panel) || panel.url_path;
|
||||
|
||||
const panelApp = apps?.find(({ slug }) => slug === panel.url_path);
|
||||
|
||||
|
||||
@@ -88,7 +88,6 @@ export type Selector =
|
||||
| SerialPortSelector
|
||||
| UiActionSelector
|
||||
| UiClockDateFormatSelector
|
||||
| UiClockTimeFormatSelector
|
||||
| UiColorSelector
|
||||
| UiConditionSelector
|
||||
| UiStateContentSelector
|
||||
@@ -670,11 +669,6 @@ export interface UiClockDateFormatSelector {
|
||||
ui_clock_date_format: {} | null;
|
||||
}
|
||||
|
||||
// 12 or 24 hour clock, as a TimeFormat. Undefined follows the user's setting.
|
||||
export interface UiClockTimeFormatSelector {
|
||||
ui_clock_time_format: {} | null;
|
||||
}
|
||||
|
||||
export interface UiColorExtraOption {
|
||||
value: string;
|
||||
label: string;
|
||||
|
||||
+1
-2
@@ -6,6 +6,5 @@ export const setTimeValue = (
|
||||
time: string | undefined = undefined
|
||||
) => {
|
||||
const param = { entity_id: entityId, time: time };
|
||||
|
||||
return callService("time", "set_value", param);
|
||||
callService("time", "set_value", param);
|
||||
};
|
||||
@@ -77,7 +77,8 @@ export type TranslationCategory =
|
||||
| "services"
|
||||
| "triggers"
|
||||
| "conditions"
|
||||
| "integration_category";
|
||||
| "integration_category"
|
||||
| "integration_connectivity";
|
||||
|
||||
export const subscribeTranslationPreferences = (
|
||||
hass: HomeAssistant,
|
||||
|
||||
@@ -4,9 +4,11 @@ import type {
|
||||
HassEntityBase,
|
||||
HassEvent,
|
||||
} from "home-assistant-js-websocket";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { BINARY_STATE_OFF, BINARY_STATE_ON } from "../common/const";
|
||||
import { computeDomain } from "../common/entity/compute_domain";
|
||||
import { computeStateDomain } from "../common/entity/compute_state_domain";
|
||||
import { getEntityIds } from "../common/entity/get_entity_ids";
|
||||
import { supportsFeature } from "../common/entity/supports-feature";
|
||||
import { formatNumber } from "../common/number/format_number";
|
||||
import { caseInsensitiveStringCompare } from "../common/string/compare";
|
||||
@@ -152,6 +154,15 @@ export const filterUpdateEntities = (
|
||||
);
|
||||
});
|
||||
|
||||
const findUpdateEntityIds = memoizeOne((entityIds: string[]) =>
|
||||
entityIds.filter((entityId) => computeDomain(entityId) === "update")
|
||||
);
|
||||
|
||||
export const countInstallableUpdates = (states: HassEntities): number =>
|
||||
findUpdateEntityIds(getEntityIds(states)).filter((entityId) =>
|
||||
updateCanInstall(states[entityId] as UpdateEntity)
|
||||
).length;
|
||||
|
||||
export const filterUpdateEntitiesParameterized = (
|
||||
entities: HassEntities,
|
||||
formatEntityName: HomeAssistant["formatEntityName"],
|
||||
|
||||
@@ -31,11 +31,9 @@ class MoreInfoAlarmControlPanel extends LitElement {
|
||||
private async _disarm() {
|
||||
setProtectedAlarmControlPanelMode(
|
||||
this,
|
||||
{
|
||||
callService: this._api.callService,
|
||||
callWS: this._api.callWS,
|
||||
localize: this._localize,
|
||||
},
|
||||
this._api.callService,
|
||||
this._api.callWS,
|
||||
this._localize,
|
||||
this.stateObj!,
|
||||
"disarmed"
|
||||
);
|
||||
|
||||
@@ -158,7 +158,7 @@ class DialogEditSidebar extends DirtyStateProviderMixin<SidebarState>()(
|
||||
].map<DisplayItem>((panel) => ({
|
||||
value: panel.url_path,
|
||||
label:
|
||||
(getPanelTitle(this.hass, panel) || panel.url_path) +
|
||||
(getPanelTitle(this.hass.localize, panel) || panel.url_path) +
|
||||
`${defaultPanel === panel.url_path ? ` (${this.hass.localize("ui.sidebar.default")})` : ""}`,
|
||||
icon: getPanelIcon(panel),
|
||||
iconPath: getPanelIconPath(panel),
|
||||
|
||||
@@ -177,7 +177,7 @@ window.hassConnection.then(({ conn }) => {
|
||||
const noop = () => {
|
||||
// do nothing
|
||||
};
|
||||
subscribeEntities(conn, noop);
|
||||
subscribeEntities(conn, noop, { batchUpdates: true });
|
||||
subscribeEntityRegistryDisplay(conn, noop);
|
||||
subscribeDeviceRegistry(conn, noop);
|
||||
subscribeAreaRegistry(conn, noop);
|
||||
|
||||
@@ -352,7 +352,12 @@ class OnboardingLocation extends LitElement {
|
||||
}
|
||||
);
|
||||
try {
|
||||
this._places = await searchPlaces(address, this.hass, true, 3);
|
||||
this._places = await searchPlaces(
|
||||
address,
|
||||
this.hass.locale.language,
|
||||
true,
|
||||
3
|
||||
);
|
||||
if (this._places?.length) {
|
||||
this._highlightedMarker = this._places[0].place_id;
|
||||
this._location = [
|
||||
|
||||
@@ -86,6 +86,7 @@ export class HaCategoryPicker extends LitElement {
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._unsubscribeCategories();
|
||||
this._categories = undefined;
|
||||
}
|
||||
|
||||
protected willUpdate(changedProperties: PropertyValues) {
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
import { mdiCashClock, mdiDelete, mdiPlus } from "@mdi/js";
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { HassEntities } from "home-assistant-js-websocket";
|
||||
import type { CSSResultGroup, TemplateResult } from "lit";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import { preserveUnchangedEntityStatesRecord } from "../../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../../common/decorators/transform";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import { stopPropagation } from "../../../../common/dom/stop_propagation";
|
||||
import { formatNumber } from "../../../../common/number/format_number";
|
||||
import "../../../../components/automation/ha-automation-row";
|
||||
import "../../../../components/ha-button";
|
||||
import "../../../../components/ha-card";
|
||||
import "../../../../components/ha-icon-button";
|
||||
import "../../../../components/ha-svg-icon";
|
||||
import {
|
||||
configContext,
|
||||
formattersContext,
|
||||
internationalizationContext,
|
||||
statesContext,
|
||||
} from "../../../../data/context";
|
||||
import type {
|
||||
EnergyPreferences,
|
||||
EnergyPreferencesValidation,
|
||||
EnergyValidationIssue,
|
||||
FixedCostEnergyPreference,
|
||||
FixedCostType,
|
||||
} from "../../../../data/energy";
|
||||
import { saveEnergyPreferences } from "../../../../data/energy";
|
||||
import { getStatisticLabel } from "../../../../data/recorder";
|
||||
import {
|
||||
showAlertDialog,
|
||||
showConfirmationDialog,
|
||||
} from "../../../../dialogs/generic/show-dialog-box";
|
||||
import { haStyle } from "../../../../resources/styles";
|
||||
import type {
|
||||
HomeAssistant,
|
||||
HomeAssistantConfig,
|
||||
HomeAssistantFormatters,
|
||||
} from "../../../../types";
|
||||
import { showEnergySettingsDialog } from "../dialogs/show-dialogs-energy";
|
||||
import type { EnergyEditorConfig } from "../editors/energy-editor";
|
||||
import "../ha-energy-editor-page";
|
||||
import type { EnergyEditorPageConfig } from "../ha-energy-editor-page";
|
||||
import "./ha-energy-validation-result";
|
||||
import { energyCardStyles } from "./styles";
|
||||
|
||||
type CostElement = HTMLElement & { cost: FixedCostEnergyPreference };
|
||||
|
||||
@customElement("ha-energy-fixed-cost-settings")
|
||||
export class EnergyFixedCostSettings extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public type!: FixedCostType;
|
||||
|
||||
@property({ attribute: false })
|
||||
public preferences!: EnergyPreferences;
|
||||
|
||||
@property({ attribute: false })
|
||||
public validationResult?: EnergyPreferencesValidation;
|
||||
|
||||
/** Path of the list page, editors open on pages under it instead of dialogs */
|
||||
@property({ attribute: false }) public listPath?: string;
|
||||
|
||||
/** Shows the editor page of the item with this key, or `new` to add one */
|
||||
@property({ attribute: false }) public editKey?: string;
|
||||
|
||||
@property({ type: Boolean }) public narrow = false;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: ContextType<typeof internationalizationContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, string>({
|
||||
transformer: ({ config }) => config.currency,
|
||||
})
|
||||
private _currency!: string;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
@transform<
|
||||
HomeAssistantFormatters,
|
||||
HomeAssistantFormatters["formatEntityName"]
|
||||
>({
|
||||
transformer: ({ formatEntityName }) => formatEntityName,
|
||||
})
|
||||
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
|
||||
|
||||
// Only the amount entities, so other state changes don't render
|
||||
@state()
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
@transform<HassEntities, HassEntities>({
|
||||
transformer: function (this: EnergyFixedCostSettings, states) {
|
||||
const amountStates: HassEntities = {};
|
||||
for (const cost of this._costs()) {
|
||||
const entityId = cost.entity_amount;
|
||||
if (entityId && states?.[entityId]) {
|
||||
amountStates[entityId] = states[entityId];
|
||||
}
|
||||
}
|
||||
return preserveUnchangedEntityStatesRecord(
|
||||
this._amountStates,
|
||||
amountStates
|
||||
);
|
||||
},
|
||||
watch: ["preferences", "type"],
|
||||
})
|
||||
private _amountStates?: HassEntities;
|
||||
|
||||
protected render(): TemplateResult {
|
||||
if (this.listPath && this.editKey !== undefined) {
|
||||
return html`<ha-energy-editor-page
|
||||
.hass=${this.hass}
|
||||
.narrow=${this.narrow}
|
||||
.backPath=${this.listPath}
|
||||
.config=${this._editorPage(this.editKey, this.type)}
|
||||
></ha-energy-editor-page>`;
|
||||
}
|
||||
|
||||
const costs: FixedCostEnergyPreference[] = [];
|
||||
const validation: EnergyValidationIssue[][] = [];
|
||||
|
||||
this.preferences.fixed_costs.forEach((cost, idx) => {
|
||||
if (cost.type !== this.type) {
|
||||
return;
|
||||
}
|
||||
costs.push(cost);
|
||||
|
||||
const issues = this.validationResult?.fixed_costs[idx];
|
||||
if (issues) {
|
||||
validation.push(issues);
|
||||
}
|
||||
});
|
||||
|
||||
return html`
|
||||
<ha-card>
|
||||
<h1 class="card-header">
|
||||
<ha-svg-icon .path=${mdiCashClock}></ha-svg-icon>
|
||||
${this._i18n.localize("ui.panel.config.energy.fixed_costs.title")}
|
||||
</h1>
|
||||
|
||||
<div class="card-content">
|
||||
<p>
|
||||
${this._i18n.localize("ui.panel.config.energy.fixed_costs.sub")}
|
||||
</p>
|
||||
${validation.map(
|
||||
(issues) => html`
|
||||
<ha-energy-validation-result
|
||||
.hass=${this.hass}
|
||||
.issues=${issues}
|
||||
></ha-energy-validation-result>
|
||||
`
|
||||
)}
|
||||
${
|
||||
costs.length > 0
|
||||
? html`
|
||||
<div class="items">
|
||||
${costs.map(
|
||||
(cost) => html`
|
||||
<ha-card outlined>
|
||||
<ha-automation-row
|
||||
.cost=${cost}
|
||||
.href=${this._editorHref(cost)}
|
||||
@click=${this.listPath ? nothing : this._editCost}
|
||||
>
|
||||
<ha-svg-icon
|
||||
slot="leading-icon"
|
||||
.path=${mdiCashClock}
|
||||
></ha-svg-icon>
|
||||
<div slot="header" class="row-header">
|
||||
<span class="label">${cost.name}</span>
|
||||
<span class="label secondary"
|
||||
>${this._amountPerPeriod(cost)}</span
|
||||
>
|
||||
</div>
|
||||
<ha-icon-button
|
||||
slot="icons"
|
||||
.label=${this._i18n.localize(
|
||||
"ui.panel.config.energy.fixed_costs.delete_fixed_cost"
|
||||
)}
|
||||
.path=${mdiDelete}
|
||||
.cost=${cost}
|
||||
@click=${this._deleteCostClicked}
|
||||
@keydown=${stopPropagation}
|
||||
></ha-icon-button>
|
||||
</ha-automation-row>
|
||||
</ha-card>
|
||||
`
|
||||
)}
|
||||
</div>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
<ha-button
|
||||
.href=${this._editorHref()}
|
||||
@click=${this.listPath ? nothing : this._addCost}
|
||||
appearance="filled"
|
||||
size="s"
|
||||
>
|
||||
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.config.energy.fixed_costs.add_fixed_cost"
|
||||
)}
|
||||
</ha-button>
|
||||
</div>
|
||||
</ha-card>
|
||||
`;
|
||||
}
|
||||
|
||||
private _costs(): FixedCostEnergyPreference[] {
|
||||
return (this.preferences?.fixed_costs ?? []).filter(
|
||||
(cost) => cost.type === this.type
|
||||
);
|
||||
}
|
||||
|
||||
private _amountPerPeriod(cost: FixedCostEnergyPreference): string {
|
||||
const amount = cost.entity_amount
|
||||
? getStatisticLabel(
|
||||
this._amountStates ?? {},
|
||||
this._formatEntityName,
|
||||
cost.entity_amount,
|
||||
undefined
|
||||
)
|
||||
: formatNumber(cost.number_amount ?? 0, this._i18n.locale, {
|
||||
style: "currency",
|
||||
currency: this._currency,
|
||||
});
|
||||
return this._i18n.localize(
|
||||
`ui.panel.config.energy.fixed_costs.amount_per_period.${cost.period}`,
|
||||
{ amount }
|
||||
);
|
||||
}
|
||||
|
||||
private _addCost() {
|
||||
this._openEditor();
|
||||
}
|
||||
|
||||
private _editCost(ev: HASSDomCurrentTargetEvent<CostElement>) {
|
||||
this._openEditor(ev.currentTarget.cost);
|
||||
}
|
||||
|
||||
private _openEditor(cost?: FixedCostEnergyPreference) {
|
||||
showEnergySettingsDialog(this, {
|
||||
editor: this._editorConfig(this.type, cost),
|
||||
});
|
||||
}
|
||||
|
||||
private _editorHref(cost?: FixedCostEnergyPreference) {
|
||||
return this.listPath
|
||||
? `${this.listPath}/fixed_cost/${cost ? encodeURIComponent(cost.id) : "new"}`
|
||||
: undefined;
|
||||
}
|
||||
|
||||
private _editorConfig(
|
||||
type: FixedCostType,
|
||||
cost?: FixedCostEnergyPreference
|
||||
): EnergyEditorConfig {
|
||||
return {
|
||||
kind: "fixed_cost",
|
||||
params: {
|
||||
cost: cost ? { ...cost } : undefined,
|
||||
type,
|
||||
saveCallback: (newCost) => this._saveCost(newCost),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private _costIndex(cost: FixedCostEnergyPreference) {
|
||||
return this.preferences.fixed_costs.findIndex(
|
||||
(item) => item.id === cost.id
|
||||
);
|
||||
}
|
||||
|
||||
// Kept per item: a save replaces the preferences right before the page leaves
|
||||
private _editorPage = memoizeOne(
|
||||
(key: string, type: FixedCostType): EnergyEditorPageConfig | undefined => {
|
||||
if (key === "new") {
|
||||
return this._pageConfig(this._editorConfig(type));
|
||||
}
|
||||
const cost = this._costs().find((item) => item.id === key);
|
||||
return cost && this._pageConfig(this._editorConfig(type, cost), cost);
|
||||
}
|
||||
);
|
||||
|
||||
private _pageConfig(
|
||||
editor: EnergyEditorConfig,
|
||||
cost?: FixedCostEnergyPreference
|
||||
): EnergyEditorPageConfig {
|
||||
if (!cost) {
|
||||
return {
|
||||
editor,
|
||||
title: this._i18n.localize(
|
||||
"ui.panel.config.energy.fixed_costs.add_fixed_cost"
|
||||
),
|
||||
};
|
||||
}
|
||||
return {
|
||||
editor,
|
||||
title: cost.name,
|
||||
delete: {
|
||||
label: this._i18n.localize(
|
||||
"ui.panel.config.energy.fixed_costs.delete_fixed_cost"
|
||||
),
|
||||
action: () => this._deleteCost(cost),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async _saveCost(cost: FixedCostEnergyPreference) {
|
||||
const costs = [...this.preferences.fixed_costs];
|
||||
const index = this._costIndex(cost);
|
||||
if (index === -1) {
|
||||
costs.push(cost);
|
||||
} else {
|
||||
costs[index] = cost;
|
||||
}
|
||||
await this._savePreferences({ ...this.preferences, fixed_costs: costs });
|
||||
}
|
||||
|
||||
private _deleteCostClicked(ev: HASSDomCurrentTargetEvent<CostElement>) {
|
||||
ev.stopPropagation();
|
||||
this._deleteCost(ev.currentTarget.cost);
|
||||
}
|
||||
|
||||
private async _deleteCost(cost: FixedCostEnergyPreference): Promise<boolean> {
|
||||
if (
|
||||
!(await showConfirmationDialog(this, {
|
||||
title: this._i18n.localize(
|
||||
"ui.panel.config.energy.fixed_costs.delete_confirm_title"
|
||||
),
|
||||
text: this._i18n.localize(
|
||||
"ui.panel.config.energy.fixed_costs.delete_confirm_text",
|
||||
{ name: cost.name }
|
||||
),
|
||||
confirmText: this._i18n.localize("ui.common.delete"),
|
||||
destructive: true,
|
||||
}))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const index = this._costIndex(cost);
|
||||
if (index === -1) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await this._savePreferences({
|
||||
...this.preferences,
|
||||
fixed_costs: this.preferences.fixed_costs.filter(
|
||||
(_cost, idx) => idx !== index
|
||||
),
|
||||
});
|
||||
} catch (err: any) {
|
||||
showAlertDialog(this, {
|
||||
title: this._i18n.localize(
|
||||
"ui.panel.config.energy.save_config_failed",
|
||||
{ error: err.message }
|
||||
),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private async _savePreferences(preferences: EnergyPreferences) {
|
||||
const result = await saveEnergyPreferences(this.hass, preferences);
|
||||
fireEvent(this, "value-changed", { value: result });
|
||||
return result;
|
||||
}
|
||||
|
||||
static get styles(): CSSResultGroup {
|
||||
return [haStyle, energyCardStyles];
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-energy-fixed-cost-settings": EnergyFixedCostSettings;
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ const HEADERS = {
|
||||
water: "ui.panel.config.energy.device_consumption_water.dialog.header",
|
||||
gas: "ui.panel.config.energy.device_consumption_gas.dialog.header",
|
||||
},
|
||||
fixed_cost: "ui.panel.config.energy.fixed_costs.dialog.header",
|
||||
} as const;
|
||||
|
||||
@customElement("dialog-energy-settings")
|
||||
|
||||
@@ -9,6 +9,8 @@ import type {
|
||||
DeviceConsumptionEnergyPreference,
|
||||
EnergyGasUnitClass,
|
||||
EnergyInfo,
|
||||
FixedCostEnergyPreference,
|
||||
FixedCostType,
|
||||
GasSourceTypeEnergyPreference,
|
||||
GridSourceTypeEnergyPreference,
|
||||
HomeSourceTypeEnergyPreference,
|
||||
@@ -77,6 +79,12 @@ export interface EnergyWaterGasDeviceEditorParams extends EnergyDeviceEditorPara
|
||||
allowedUnitClass?: EnergyGasUnitClass;
|
||||
}
|
||||
|
||||
export interface EnergyFixedCostEditorParams {
|
||||
cost?: FixedCostEnergyPreference;
|
||||
type: FixedCostType;
|
||||
saveCallback: (cost: FixedCostEnergyPreference) => Promise<void>;
|
||||
}
|
||||
|
||||
export type EnergyEditorConfig =
|
||||
| { kind: "grid"; params: EnergyGridSourceEditorParams }
|
||||
| { kind: "solar"; params: EnergySolarSourceEditorParams }
|
||||
@@ -85,7 +93,8 @@ export type EnergyEditorConfig =
|
||||
| { kind: "device"; params: EnergyDeviceEditorParams }
|
||||
| { kind: "gas"; params: EnergyGasSourceEditorParams }
|
||||
| { kind: "water"; params: EnergyWaterSourceEditorParams }
|
||||
| { kind: "water_gas_device"; params: EnergyWaterGasDeviceEditorParams };
|
||||
| { kind: "water_gas_device"; params: EnergyWaterGasDeviceEditorParams }
|
||||
| { kind: "fixed_cost"; params: EnergyFixedCostEditorParams };
|
||||
|
||||
type PreselectedStatistic =
|
||||
(typeof energyEditorQueryParamConfig)["string"][number];
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { html, LitElement, 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 { transform } from "../../../../common/decorators/transform";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/entity/ha-entity-picker";
|
||||
import "../../../../components/ha-alert";
|
||||
import "../../../../components/ha-markdown";
|
||||
import "../../../../components/ha-select";
|
||||
import type {
|
||||
HaSelectOption,
|
||||
HaSelectSelectEvent,
|
||||
} from "../../../../components/ha-select";
|
||||
import "../../../../components/input/ha-input";
|
||||
import type { HaInput } from "../../../../components/input/ha-input";
|
||||
import { configContext } from "../../../../data/context";
|
||||
import type {
|
||||
FixedCostEnergyPreference,
|
||||
FixedCostPeriod,
|
||||
} from "../../../../data/energy";
|
||||
import { emptyFixedCostEnergyPreference } from "../../../../data/energy";
|
||||
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
|
||||
import type { HomeAssistantConfig, ValueChangedEvent } from "../../../../types";
|
||||
import type {
|
||||
EnergyEditorStatus,
|
||||
EnergyFixedCostEditorParams,
|
||||
} from "./energy-editor";
|
||||
import { EnergyEditorMixin, energyEditorStyles } from "./energy-editor";
|
||||
|
||||
type AmountType = "number" | "entity";
|
||||
|
||||
interface FixedCostFormState {
|
||||
cost: FixedCostEnergyPreference;
|
||||
amountType: AmountType;
|
||||
}
|
||||
|
||||
const PERIODS: FixedCostPeriod[] = ["day", "month", "year"];
|
||||
|
||||
@customElement("ha-energy-fixed-cost-editor")
|
||||
export class HaEnergyFixedCostEditor extends EnergyEditorMixin(
|
||||
DirtyStateProviderMixin<FixedCostFormState>()(LitElement)
|
||||
) {
|
||||
@property({ attribute: false })
|
||||
public params!: EnergyFixedCostEditorParams;
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, string>({
|
||||
transformer: ({ config }) => config.currency,
|
||||
})
|
||||
private _currency!: string;
|
||||
|
||||
@state() private _cost?: FixedCostEnergyPreference;
|
||||
|
||||
@state() private _amountType: AmountType = "number";
|
||||
|
||||
@state() private _numberAmountText = "";
|
||||
|
||||
@state() private _error?: string;
|
||||
|
||||
@state() private _saving = false;
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>) {
|
||||
super.willUpdate(changedProps);
|
||||
if (changedProps.has("params")) {
|
||||
this._init();
|
||||
}
|
||||
}
|
||||
|
||||
private _init() {
|
||||
const params = this.params;
|
||||
this._error = undefined;
|
||||
this._saving = false;
|
||||
this._cost = params.cost
|
||||
? { ...params.cost }
|
||||
: emptyFixedCostEnergyPreference(params.type);
|
||||
this._amountType = this._cost.entity_amount ? "entity" : "number";
|
||||
this._numberAmountText =
|
||||
typeof this._cost.number_amount === "number"
|
||||
? String(this._cost.number_amount)
|
||||
: "";
|
||||
this._initDirtyTracking(
|
||||
{ type: "deep" },
|
||||
{ cost: this._cost, amountType: this._amountType }
|
||||
);
|
||||
}
|
||||
|
||||
protected get editorStatus(): EnergyEditorStatus {
|
||||
const cost = this._cost;
|
||||
return {
|
||||
dirty: this.isDirtyState,
|
||||
valid:
|
||||
!!cost?.name.trim() &&
|
||||
(this._amountType === "number"
|
||||
? Number.isFinite(cost.number_amount)
|
||||
: !!cost.entity_amount),
|
||||
saving: this._saving,
|
||||
};
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this._cost) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
${
|
||||
this._error
|
||||
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
|
||||
: nothing
|
||||
}
|
||||
<ha-input
|
||||
.label=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.name"
|
||||
)}
|
||||
type="text"
|
||||
required
|
||||
.disabled=${this._saving}
|
||||
.value=${this._cost.name}
|
||||
@input=${this._nameChanged}
|
||||
></ha-input>
|
||||
<div class="group">
|
||||
<ha-select
|
||||
.label=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_type"
|
||||
)}
|
||||
.value=${this._amountType}
|
||||
.options=${this._amountTypeOptions()}
|
||||
.disabled=${this._saving}
|
||||
@selected=${this._amountTypeChanged}
|
||||
></ha-select>
|
||||
${this._renderAmount()}
|
||||
</div>
|
||||
<ha-select
|
||||
.label=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.period"
|
||||
)}
|
||||
.helper=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.period_helper"
|
||||
)}
|
||||
.value=${this._cost.period}
|
||||
.options=${this._periodOptions()}
|
||||
.disabled=${this._saving}
|
||||
@selected=${this._periodChanged}
|
||||
></ha-select>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderAmount() {
|
||||
if (this._amountType === "entity") {
|
||||
return html`<ha-entity-picker
|
||||
.disabled=${this._saving}
|
||||
include-domains='["sensor", "input_number"]'
|
||||
.value=${this._cost!.entity_amount ?? undefined}
|
||||
.label=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_entity_label"
|
||||
)}
|
||||
.helper=${html`<ha-markdown
|
||||
.content=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_entity_helper",
|
||||
{ currency: this._currency, period: this._cost!.period }
|
||||
)}
|
||||
></ha-markdown>`}
|
||||
@value-changed=${this._amountEntityChanged}
|
||||
></ha-entity-picker>`;
|
||||
}
|
||||
return html`<ha-input
|
||||
.disabled=${this._saving}
|
||||
.label=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_number_label"
|
||||
)}
|
||||
.hint=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_number_helper"
|
||||
)}
|
||||
step="any"
|
||||
type="number"
|
||||
required
|
||||
auto-validate
|
||||
.value=${this._numberAmountText}
|
||||
@input=${this._numberAmountChanged}
|
||||
>
|
||||
<span slot="end">${this._currency}</span>
|
||||
</ha-input>`;
|
||||
}
|
||||
|
||||
private _amountTypeOptions(): HaSelectOption[] {
|
||||
return [
|
||||
{
|
||||
value: "number",
|
||||
label: this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_number"
|
||||
),
|
||||
},
|
||||
{
|
||||
value: "entity",
|
||||
label: this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_entity"
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
private _periodOptions(): HaSelectOption[] {
|
||||
return PERIODS.map((period) => ({
|
||||
value: period,
|
||||
label: this._localize(
|
||||
`ui.panel.config.energy.fixed_costs.dialog.period_${period}`
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
private _nameChanged(ev: HASSDomCurrentTargetEvent<HaInput>) {
|
||||
this._cost = { ...this._cost!, name: ev.currentTarget.value ?? "" };
|
||||
this._updateFormDirtyState();
|
||||
}
|
||||
|
||||
private _amountTypeChanged(ev: HaSelectSelectEvent) {
|
||||
this._amountType = ev.detail.value as AmountType;
|
||||
this._updateFormDirtyState();
|
||||
}
|
||||
|
||||
private _numberAmountChanged(ev: HASSDomCurrentTargetEvent<HaInput>) {
|
||||
// Render the typed text so partial input such as "-" is not rewritten
|
||||
this._numberAmountText = ev.currentTarget.value ?? "";
|
||||
const amount = parseFloat(this._numberAmountText);
|
||||
this._cost = {
|
||||
...this._cost!,
|
||||
number_amount: Number.isFinite(amount) ? amount : null,
|
||||
};
|
||||
this._updateFormDirtyState();
|
||||
}
|
||||
|
||||
private _amountEntityChanged(ev: ValueChangedEvent<string>) {
|
||||
this._cost = { ...this._cost!, entity_amount: ev.detail.value || null };
|
||||
this._updateFormDirtyState();
|
||||
}
|
||||
|
||||
private _periodChanged(ev: HaSelectSelectEvent) {
|
||||
this._cost = {
|
||||
...this._cost!,
|
||||
period: ev.detail.value as FixedCostPeriod,
|
||||
};
|
||||
this._updateFormDirtyState();
|
||||
}
|
||||
|
||||
private _updateFormDirtyState(): void {
|
||||
this._updateDirtyState({ cost: this._cost!, amountType: this._amountType });
|
||||
}
|
||||
|
||||
public async save(): Promise<boolean> {
|
||||
const params = this.params;
|
||||
const cost = this._cost!;
|
||||
const isNumber = this._amountType === "number";
|
||||
const isCurrent = () => this.params === params && this.isConnected;
|
||||
this._error = undefined;
|
||||
this._saving = true;
|
||||
try {
|
||||
await params.saveCallback({
|
||||
...cost,
|
||||
name: cost.name.trim(),
|
||||
number_amount: isNumber ? cost.number_amount : null,
|
||||
entity_amount: isNumber ? null : cost.entity_amount,
|
||||
});
|
||||
if (isCurrent()) {
|
||||
this._markDirtyStateClean();
|
||||
}
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
if (isCurrent()) {
|
||||
this._error = err.message;
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
if (isCurrent()) {
|
||||
this._saving = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static get styles(): CSSResultGroup {
|
||||
return energyEditorStyles;
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-energy-fixed-cost-editor": HaEnergyFixedCostEditor;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { html, nothing } from "lit";
|
||||
import type { EnergyEditorConfig } from "./energy-editor";
|
||||
import "./ha-energy-battery-source-editor";
|
||||
import "./ha-energy-device-editor";
|
||||
import "./ha-energy-fixed-cost-editor";
|
||||
import "./ha-energy-gas-source-editor";
|
||||
import "./ha-energy-grid-source-editor";
|
||||
import "./ha-energy-home-source-editor";
|
||||
@@ -51,6 +52,11 @@ export const renderEnergyEditor = (config: EnergyEditorConfig) => {
|
||||
class="energy-editor"
|
||||
.params=${config.params}
|
||||
></ha-energy-water-gas-device-editor>`;
|
||||
case "fixed_cost":
|
||||
return html`<ha-energy-fixed-cost-editor
|
||||
class="energy-editor"
|
||||
.params=${config.params}
|
||||
></ha-energy-fixed-cost-editor>`;
|
||||
default:
|
||||
return nothing;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import type {
|
||||
EnergyPreferencesValidation,
|
||||
EnergyInfo,
|
||||
EnergyPreferences,
|
||||
FixedCostType,
|
||||
} from "../../../data/energy";
|
||||
import {
|
||||
getEnergyPreferenceValidation,
|
||||
@@ -35,6 +36,7 @@ import type { HomeAssistant, Route } from "../../../types";
|
||||
import "../../../components/ha-alert";
|
||||
import "./components/ha-energy-device-settings";
|
||||
import "./components/ha-energy-device-settings-water-gas";
|
||||
import "./components/ha-energy-fixed-cost-settings";
|
||||
import "./components/ha-energy-grid-settings";
|
||||
import "./components/ha-energy-solar-settings";
|
||||
import "./components/ha-energy-home-settings";
|
||||
@@ -55,6 +57,7 @@ const INITIAL_CONFIG: EnergyPreferences = {
|
||||
device_consumption: [],
|
||||
device_consumption_water: [],
|
||||
device_consumption_gas: [],
|
||||
fixed_costs: [],
|
||||
};
|
||||
|
||||
const TABS: PageNavigation[] = [
|
||||
@@ -80,9 +83,15 @@ const TABS: PageNavigation[] = [
|
||||
|
||||
// Editor pages are at <tab>/<kind>/<key>, with `new` as the key of a new item
|
||||
const EDITOR_KINDS: Record<string, string[]> = {
|
||||
electricity: ["grid", "solar", "home", "battery", "device"],
|
||||
gas: ["gas", "device"],
|
||||
water: ["water", "device"],
|
||||
electricity: ["grid", "solar", "home", "battery", "device", "fixed_cost"],
|
||||
gas: ["gas", "device", "fixed_cost"],
|
||||
water: ["water", "device", "fixed_cost"],
|
||||
};
|
||||
|
||||
const FIXED_COST_TYPES: Record<string, FixedCostType> = {
|
||||
electricity: "grid",
|
||||
gas: "gas",
|
||||
water: "water",
|
||||
};
|
||||
|
||||
@customElement("ha-config-energy")
|
||||
@@ -251,6 +260,7 @@ class HaConfigEnergy extends LitElement {
|
||||
.validationResult=${this._validationResult}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-grid-settings>
|
||||
${this._renderFixedCostSettings("grid", listPath)}
|
||||
<ha-energy-solar-settings
|
||||
.hass=${this.hass}
|
||||
.preferences=${this._preferences!}
|
||||
@@ -294,6 +304,7 @@ class HaConfigEnergy extends LitElement {
|
||||
.validationResult=${this._validationResult}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-gas-settings>
|
||||
${this._renderFixedCostSettings("gas", listPath)}
|
||||
<ha-energy-device-settings-water-gas
|
||||
.hass=${this.hass}
|
||||
.resource=${"gas"}
|
||||
@@ -314,6 +325,7 @@ class HaConfigEnergy extends LitElement {
|
||||
.validationResult=${this._validationResult}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-water-settings>
|
||||
${this._renderFixedCostSettings("water", listPath)}
|
||||
<ha-energy-device-settings-water-gas
|
||||
.hass=${this.hass}
|
||||
.resource=${"water"}
|
||||
@@ -329,6 +341,26 @@ class HaConfigEnergy extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
private _renderFixedCostSettings(type: FixedCostType, listPath: string) {
|
||||
const prefs = this._preferences!;
|
||||
// The dashboard only shows fixed costs next to a source of their type,
|
||||
// without one the card stays so existing costs can be deleted
|
||||
if (
|
||||
!prefs.energy_sources.some((source) => source.type === type) &&
|
||||
!prefs.fixed_costs.some((cost) => cost.type === type)
|
||||
) {
|
||||
return nothing;
|
||||
}
|
||||
return html`<ha-energy-fixed-cost-settings
|
||||
.hass=${this.hass}
|
||||
.type=${type}
|
||||
.preferences=${prefs}
|
||||
.listPath=${listPath}
|
||||
.validationResult=${this._validationResult}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-fixed-cost-settings>`;
|
||||
}
|
||||
|
||||
private _renderEditorPage(kind: string, key: string) {
|
||||
const listPath = `${this.route.prefix}/${this._currTab}`;
|
||||
switch (`${this._currTab}/${kind}`) {
|
||||
@@ -433,6 +465,19 @@ class HaConfigEnergy extends LitElement {
|
||||
.editKey=${key}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-device-settings-water-gas>`;
|
||||
case "electricity/fixed_cost":
|
||||
case "gas/fixed_cost":
|
||||
case "water/fixed_cost":
|
||||
return html`<ha-energy-fixed-cost-settings
|
||||
class="editor-page"
|
||||
.hass=${this.hass}
|
||||
.narrow=${this.narrow}
|
||||
.type=${FIXED_COST_TYPES[this._currTab]}
|
||||
.preferences=${this._preferences!}
|
||||
.listPath=${listPath}
|
||||
.editKey=${key}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-fixed-cost-settings>`;
|
||||
default:
|
||||
return nothing;
|
||||
}
|
||||
@@ -574,7 +619,8 @@ class HaConfigEnergy extends LitElement {
|
||||
ha-energy-gas-settings,
|
||||
ha-energy-water-settings,
|
||||
ha-energy-device-settings,
|
||||
ha-energy-device-settings-water-gas {
|
||||
ha-energy-device-settings-water-gas,
|
||||
ha-energy-fixed-cost-settings {
|
||||
display: block;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
@@ -363,7 +363,8 @@ export class HaConfigLovelaceDashboards extends LitElement {
|
||||
}
|
||||
const item: DataTableItem = {
|
||||
icon: getPanelIcon(panelInfo),
|
||||
title: getPanelTitle(this.hass, panelInfo) || panelInfo.url_path,
|
||||
title:
|
||||
getPanelTitle(this.hass.localize, panelInfo) || panelInfo.url_path,
|
||||
show_in_sidebar: panelInfo.show_in_sidebar || false,
|
||||
mode: "storage",
|
||||
url_path: panelInfo.url_path,
|
||||
@@ -547,7 +548,7 @@ export class HaConfigLovelaceDashboards extends LitElement {
|
||||
const defaultPanel = this.hass.systemData?.default_panel || DEFAULT_PANEL;
|
||||
showPanelDetailDialog(this, {
|
||||
urlPath: panelInfo.url_path,
|
||||
title: getPanelTitle(this.hass, panelInfo) || panelInfo.url_path,
|
||||
title: getPanelTitle(this.hass.localize, panelInfo) || panelInfo.url_path,
|
||||
icon: getPanelIcon(panelInfo),
|
||||
requireAdmin: panelInfo.require_admin || false,
|
||||
showInSidebar: panelInfo.show_in_sidebar || false,
|
||||
|
||||
@@ -35,6 +35,7 @@ export class EnergySetupWizard extends LitElement implements LovelaceCard {
|
||||
device_consumption: [],
|
||||
device_consumption_water: [],
|
||||
device_consumption_gas: [],
|
||||
fixed_costs: [],
|
||||
};
|
||||
|
||||
public getCardSize() {
|
||||
|
||||
@@ -133,11 +133,9 @@ class HuiAlarmModeCardFeature
|
||||
private async _setMode(mode: AlarmMode) {
|
||||
await setProtectedAlarmControlPanelMode(
|
||||
this,
|
||||
{
|
||||
callService: this._api.callService,
|
||||
callWS: this._api.callWS,
|
||||
localize: this._localize,
|
||||
},
|
||||
this._api.callService,
|
||||
this._api.callWS,
|
||||
this._localize,
|
||||
this._stateObj!,
|
||||
mode
|
||||
);
|
||||
|
||||
@@ -19,7 +19,10 @@ import "../../../components/ha-control-button-group";
|
||||
import "../../../components/ha-control-number-buttons";
|
||||
import "../../../components/ha-control-slider";
|
||||
import type { ClimateEntity } from "../../../data/climate";
|
||||
import { ClimateEntityFeature } from "../../../data/climate";
|
||||
import {
|
||||
ClimateEntityFeature,
|
||||
pushTargetTemperature,
|
||||
} from "../../../data/climate";
|
||||
import {
|
||||
apiContext,
|
||||
configContext,
|
||||
@@ -187,17 +190,9 @@ class HuiTargetTemperatureCardFeature
|
||||
const target =
|
||||
(ev.currentTarget as HTMLElement & { target?: Target }).target ?? "value";
|
||||
|
||||
// Sliders span the full range, so keep low and high from crossing
|
||||
let newValue = value;
|
||||
|
||||
if (target === "low") {
|
||||
newValue = Math.min(value, this._targetTemperature.high ?? value);
|
||||
} else if (target === "high") {
|
||||
newValue = Math.max(value, this._targetTemperature.low ?? value);
|
||||
}
|
||||
this._targetTemperature = {
|
||||
...this._targetTemperature,
|
||||
[target]: newValue,
|
||||
...pushTargetTemperature(this._targetTemperature, target, value),
|
||||
};
|
||||
this._pendingSync.schedule();
|
||||
this._debouncedCallService(target);
|
||||
@@ -380,10 +375,7 @@ class HuiTargetTemperatureCardFeature
|
||||
.value=${this._targetTemperature.low}
|
||||
.unit=${this._hassConfig?.unit_system.temperature}
|
||||
.min=${this._min}
|
||||
.max=${Math.min(
|
||||
this._max,
|
||||
this._targetTemperature.high ?? this._max
|
||||
)}
|
||||
.max=${this._max}
|
||||
.step=${this._step}
|
||||
@value-changed=${this._valueChanged}
|
||||
.label=${this._formatters.formatEntityAttributeName(
|
||||
@@ -402,10 +394,7 @@ class HuiTargetTemperatureCardFeature
|
||||
.target=${"high"}
|
||||
.value=${this._targetTemperature.high}
|
||||
.unit=${this._hassConfig?.unit_system.temperature}
|
||||
.min=${Math.max(
|
||||
this._min,
|
||||
this._targetTemperature.low ?? this._min
|
||||
)}
|
||||
.min=${this._min}
|
||||
.max=${this._max}
|
||||
.step=${this._step}
|
||||
@value-changed=${this._valueChanged}
|
||||
|
||||
@@ -1,477 +0,0 @@
|
||||
import { TZDate } from "@date-fns/tz";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../common/decorators/transform";
|
||||
import { resolveTimeZone } from "../../../common/datetime/resolve-time-zone";
|
||||
import { useAmPm } from "../../../common/datetime/use_am_pm";
|
||||
import { computeDomain } from "../../../common/entity/compute_domain";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-control-select-menu";
|
||||
import type { SelectOption } from "../../../components/ha-control-select-menu";
|
||||
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
|
||||
import {
|
||||
apiContext,
|
||||
configContext,
|
||||
internationalizationContext,
|
||||
} from "../../../data/context";
|
||||
import { setDateTimeValue } from "../../../data/datetime";
|
||||
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
|
||||
import { setInputDateTimeValue } from "../../../data/input_datetime";
|
||||
import { setTimeValue } from "../../../data/time";
|
||||
import type { FrontendLocaleData, TimeFormat } from "../../../data/translation";
|
||||
import type {
|
||||
HomeAssistant,
|
||||
HomeAssistantApi,
|
||||
HomeAssistantConfig,
|
||||
HomeAssistantInternationalization,
|
||||
} from "../../../types";
|
||||
import type { LovelaceCardFeature, LovelaceCardFeatureEditor } from "../types";
|
||||
import { cardFeatureStyles } from "./common/card-feature-styles";
|
||||
import type {
|
||||
LovelaceCardFeatureContext,
|
||||
TimeSetCardFeatureConfig,
|
||||
} from "./types";
|
||||
|
||||
interface TimeParts {
|
||||
hours: number;
|
||||
minutes: number;
|
||||
seconds: number;
|
||||
}
|
||||
|
||||
type Period = "AM" | "PM";
|
||||
|
||||
const TIME_REGEX = /^(\d{1,2}):(\d{2})(?::(\d{2}))?/;
|
||||
|
||||
const supportsTimeSetCardFeatureFromState = (stateObj: HassEntity) => {
|
||||
const domain = computeDomain(stateObj.entity_id);
|
||||
|
||||
return (
|
||||
domain === "time" ||
|
||||
domain === "datetime" ||
|
||||
(domain === "input_datetime" && Boolean(stateObj.attributes.has_time))
|
||||
);
|
||||
};
|
||||
|
||||
export const supportsTimeSetCardFeature = (
|
||||
hass: HomeAssistant,
|
||||
context: LovelaceCardFeatureContext
|
||||
) => {
|
||||
const stateObj = context.entity_id
|
||||
? hass.states[context.entity_id]
|
||||
: undefined;
|
||||
|
||||
if (!stateObj) return false;
|
||||
|
||||
return supportsTimeSetCardFeatureFromState(stateObj);
|
||||
};
|
||||
|
||||
// A datetime is shown in the time zone picked in the user's profile, like the
|
||||
// tile's state, so the time is read and changed in that time zone too.
|
||||
const toZonedDate = (value: string, timeZone?: string): Date => {
|
||||
const date = new Date(value);
|
||||
|
||||
if (!timeZone) {
|
||||
return date;
|
||||
}
|
||||
|
||||
const zoned = new TZDate(date, timeZone);
|
||||
|
||||
// TZDate is invalid where Intl lacks "longOffset" (Chrome < 95, Safari < 15.4)
|
||||
return isNaN(zoned.getHours()) ? date : zoned;
|
||||
};
|
||||
|
||||
const parseTime = (
|
||||
stateObj: HassEntity,
|
||||
timeZone?: string
|
||||
): TimeParts | undefined => {
|
||||
if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (computeDomain(stateObj.entity_id) === "datetime") {
|
||||
const dateObj = toZonedDate(stateObj.state, timeZone);
|
||||
|
||||
if (isNaN(dateObj.getTime())) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
hours: dateObj.getHours(),
|
||||
minutes: dateObj.getMinutes(),
|
||||
seconds: dateObj.getSeconds(),
|
||||
};
|
||||
}
|
||||
|
||||
// input_datetime with a date has a "YYYY-MM-DD HH:MM:SS" state
|
||||
const match = TIME_REGEX.exec(stateObj.state.split(" ").pop() ?? "");
|
||||
|
||||
if (!match) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
hours: Number(match[1]),
|
||||
minutes: Number(match[2]),
|
||||
seconds: match[3] ? Number(match[3]) : 0,
|
||||
};
|
||||
};
|
||||
|
||||
const pad = (value: number) => value.toString().padStart(2, "0");
|
||||
|
||||
// Seconds are kept as they are, so a time is matched on hours and minutes
|
||||
const timeKey = (time: TimeParts) => `${time.hours}:${time.minutes}`;
|
||||
|
||||
// Each write has its own id, as the same time can be sent more than once
|
||||
interface Write {
|
||||
id: number;
|
||||
key: string;
|
||||
}
|
||||
|
||||
const MINUTE_OPTIONS: SelectOption[] = Array.from({ length: 60 }, (_, i) => ({
|
||||
value: i.toString(),
|
||||
label: pad(i),
|
||||
}));
|
||||
|
||||
const HOUR_OPTIONS_24: SelectOption[] = Array.from({ length: 24 }, (_, i) => ({
|
||||
value: i.toString(),
|
||||
label: pad(i),
|
||||
}));
|
||||
|
||||
const HOUR_OPTIONS_12: SelectOption[] = [
|
||||
12,
|
||||
...Array.from({ length: 11 }, (_, i) => i + 1),
|
||||
].map((hour) => ({ value: hour.toString(), label: hour.toString() }));
|
||||
|
||||
@customElement("hui-time-set-card-feature")
|
||||
class HuiTimeSetCardFeature extends LitElement implements LovelaceCardFeature {
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
|
||||
private _stateObj?: HassEntity;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
@transform<HomeAssistantInternationalization, FrontendLocaleData>({
|
||||
transformer: ({ locale }) => locale,
|
||||
})
|
||||
private _locale?: FrontendLocaleData;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, string>({
|
||||
transformer: ({ config }) => config.time_zone,
|
||||
})
|
||||
private _serverTimeZone?: string;
|
||||
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: HomeAssistantApi;
|
||||
|
||||
@state() private _config?: TimeSetCardFeatureConfig;
|
||||
|
||||
// The newest selection and the write that sent it, shown instead of the
|
||||
// entity's time until every write is confirmed, so reports from earlier
|
||||
// writes don't overwrite it
|
||||
@state() private _selection?: {
|
||||
entityId: string;
|
||||
time: TimeParts;
|
||||
writeId: number;
|
||||
};
|
||||
|
||||
// Writes the entity hasn't reported back yet, oldest first
|
||||
private _unconfirmed: Write[] = [];
|
||||
|
||||
private _nextWriteId = 0;
|
||||
|
||||
// The entity and time last reported, to skip updates that don't change it
|
||||
private _reported?: string;
|
||||
|
||||
private get _timeZone(): string | undefined {
|
||||
return this._locale && this._serverTimeZone
|
||||
? resolveTimeZone(this._locale.time_zone, this._serverTimeZone)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
static getStubConfig(): TimeSetCardFeatureConfig {
|
||||
return {
|
||||
type: "time-set",
|
||||
};
|
||||
}
|
||||
|
||||
public static async getConfigElement(): Promise<LovelaceCardFeatureEditor> {
|
||||
await import("../editor/config-elements/hui-time-set-card-feature-editor");
|
||||
|
||||
return document.createElement("hui-time-set-card-feature-editor");
|
||||
}
|
||||
|
||||
public setConfig(config: TimeSetCardFeatureConfig): void {
|
||||
if (!config) {
|
||||
throw new Error("Invalid configuration");
|
||||
}
|
||||
|
||||
this._config = config;
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues): void {
|
||||
super.willUpdate(changedProps);
|
||||
|
||||
if (!changedProps.has("_stateObj") || !this._stateObj) {
|
||||
return;
|
||||
}
|
||||
|
||||
const current = parseTime(this._stateObj, this._timeZone);
|
||||
const key = current ? timeKey(current) : undefined;
|
||||
const reported = `${this._stateObj.entity_id} ${key}`;
|
||||
|
||||
if (reported === this._reported) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._reported = reported;
|
||||
|
||||
if (!this._selection) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Home Assistant applies writes in order, so a report confirms the oldest
|
||||
// unconfirmed write with that time, and any written before it
|
||||
const index = key
|
||||
? this._unconfirmed.findIndex((write) => write.key === key)
|
||||
: -1;
|
||||
|
||||
this._unconfirmed = index === -1 ? [] : this._unconfirmed.slice(index + 1);
|
||||
|
||||
// Once every write is confirmed, or the time changed elsewhere, show the
|
||||
// entity's time
|
||||
if (this._unconfirmed.length === 0) {
|
||||
this._selection = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Worked out from the current entity on each use, as the entity can change
|
||||
// after willUpdate when the card switches to another one
|
||||
private get _time(): TimeParts | undefined {
|
||||
if (!this._stateObj) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return this._selection?.entityId === this._stateObj.entity_id
|
||||
? this._selection.time
|
||||
: parseTime(this._stateObj, this._timeZone);
|
||||
}
|
||||
|
||||
private _useAmPm = memoizeOne(
|
||||
(locale: FrontendLocaleData, timeFormat?: TimeFormat) =>
|
||||
useAmPm(timeFormat ? { ...locale, time_format: timeFormat } : locale)
|
||||
);
|
||||
|
||||
private _periodOptions = memoizeOne((language: string): SelectOption[] => {
|
||||
const formatter = new Intl.DateTimeFormat(language, {
|
||||
hour: "numeric",
|
||||
hourCycle: "h12",
|
||||
});
|
||||
|
||||
const periodLabel = (hours: number, fallback: Period) =>
|
||||
formatter
|
||||
.formatToParts(new Date(2000, 0, 1, hours))
|
||||
.find((part) => part.type === "dayPeriod")?.value ?? fallback;
|
||||
|
||||
return [
|
||||
{ value: "AM", label: periodLabel(0, "AM") },
|
||||
{ value: "PM", label: periodLabel(12, "PM") },
|
||||
];
|
||||
});
|
||||
|
||||
private _hourSelected(ev: HaDropdownSelectEvent): void {
|
||||
const hour = Number(ev.detail.item.value);
|
||||
|
||||
if (
|
||||
!this._locale ||
|
||||
!this._useAmPm(this._locale, this._config?.time_format)
|
||||
) {
|
||||
this._setTime({ hours: hour });
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const isPm = (this._time?.hours ?? 0) >= 12;
|
||||
|
||||
this._setTime({ hours: (hour % 12) + (isPm ? 12 : 0) });
|
||||
}
|
||||
|
||||
private _minuteSelected(ev: HaDropdownSelectEvent): void {
|
||||
this._setTime({ minutes: Number(ev.detail.item.value) });
|
||||
}
|
||||
|
||||
private _periodSelected(ev: HaDropdownSelectEvent<Period>): void {
|
||||
const hours = (this._time?.hours ?? 0) % 12;
|
||||
|
||||
this._setTime({
|
||||
hours: ev.detail.item.value === "PM" ? hours + 12 : hours,
|
||||
});
|
||||
}
|
||||
|
||||
private async _setTime(change: Partial<TimeParts>) {
|
||||
if (!this._stateObj) return;
|
||||
|
||||
const stateObj = this._stateObj;
|
||||
const oldTime = this._time;
|
||||
|
||||
const time: TimeParts = {
|
||||
hours: 0,
|
||||
minutes: 0,
|
||||
seconds: 0,
|
||||
...oldTime,
|
||||
...change,
|
||||
};
|
||||
|
||||
if (
|
||||
oldTime &&
|
||||
time.hours === oldTime.hours &&
|
||||
time.minutes === oldTime.minutes
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const writeId = this._nextWriteId++;
|
||||
|
||||
this._selection = { entityId: stateObj.entity_id, time, writeId };
|
||||
this._unconfirmed = [
|
||||
...this._unconfirmed,
|
||||
{ id: writeId, key: timeKey(time) },
|
||||
];
|
||||
|
||||
const domain = computeDomain(stateObj.entity_id);
|
||||
const value = `${pad(time.hours)}:${pad(time.minutes)}:${pad(time.seconds)}`;
|
||||
|
||||
try {
|
||||
if (domain === "datetime") {
|
||||
const dateObj = toZonedDate(stateObj.state, this._timeZone);
|
||||
|
||||
dateObj.setHours(time.hours, time.minutes, time.seconds);
|
||||
|
||||
await setDateTimeValue(
|
||||
this._api.callService,
|
||||
stateObj.entity_id,
|
||||
new Date(dateObj.getTime())
|
||||
);
|
||||
} else if (domain === "input_datetime") {
|
||||
await setInputDateTimeValue(
|
||||
this._api.callService,
|
||||
stateObj.entity_id,
|
||||
value,
|
||||
stateObj.attributes.has_date
|
||||
? stateObj.state.split(" ")[0]
|
||||
: undefined
|
||||
);
|
||||
} else {
|
||||
await setTimeValue(this._api.callService, stateObj.entity_id, value);
|
||||
}
|
||||
} catch {
|
||||
this._unconfirmed = this._unconfirmed.filter(
|
||||
(write) => write.id !== writeId
|
||||
);
|
||||
|
||||
// When the write behind the shown selection fails, show the entity's
|
||||
// time again
|
||||
if (this._selection?.writeId === writeId) {
|
||||
this._selection = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (
|
||||
!this._config ||
|
||||
!this.context ||
|
||||
!this._stateObj ||
|
||||
!this._locale ||
|
||||
!supportsTimeSetCardFeatureFromState(this._stateObj)
|
||||
) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const disabled = [UNAVAILABLE, UNKNOWN].includes(this._stateObj.state);
|
||||
const useAMPM = this._useAmPm(this._locale, this._config.time_format);
|
||||
const time = this._time;
|
||||
|
||||
const hour = time
|
||||
? (useAMPM ? time.hours % 12 || 12 : time.hours).toString()
|
||||
: undefined;
|
||||
|
||||
return html`
|
||||
<ha-control-select-menu
|
||||
?hide-label=${hour !== undefined}
|
||||
.label=${this._localize("ui.card.time.hour")}
|
||||
.value=${hour}
|
||||
.options=${useAMPM ? HOUR_OPTIONS_12 : HOUR_OPTIONS_24}
|
||||
.disabled=${disabled}
|
||||
@wa-select=${this._hourSelected}
|
||||
></ha-control-select-menu>
|
||||
<span class="separator" aria-hidden="true">:</span>
|
||||
<ha-control-select-menu
|
||||
?hide-label=${time !== undefined}
|
||||
.label=${this._localize("ui.card.time.minute")}
|
||||
.value=${time?.minutes.toString()}
|
||||
.options=${MINUTE_OPTIONS}
|
||||
.disabled=${disabled}
|
||||
@wa-select=${this._minuteSelected}
|
||||
></ha-control-select-menu>
|
||||
${
|
||||
useAMPM
|
||||
? html`
|
||||
<ha-control-select-menu
|
||||
?hide-label=${time !== undefined}
|
||||
.label=${this._localize("ui.card.time.period")}
|
||||
.value=${time ? (time.hours >= 12 ? "PM" : "AM") : undefined}
|
||||
.options=${this._periodOptions(this._locale.language)}
|
||||
.disabled=${disabled}
|
||||
@wa-select=${this._periodSelected}
|
||||
></ha-control-select-menu>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = [
|
||||
cardFeatureStyles,
|
||||
css`
|
||||
:host {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-1);
|
||||
/* Times read hour first in every language, like ha-base-time-input */
|
||||
direction: ltr;
|
||||
}
|
||||
ha-control-select-menu {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
/* Leave room for "12" or "PM" when the card is narrow */
|
||||
--control-select-menu-padding: 6px var(--ha-space-1);
|
||||
}
|
||||
.separator {
|
||||
color: var(--secondary-text-color);
|
||||
font-size: var(--ha-font-size-l);
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"hui-time-set-card-feature": HuiTimeSetCardFeature;
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,6 @@ import { supportsSelectOptionsCardFeature } from "./hui-select-options-card-feat
|
||||
import { supportsTemperatureForecastCardFeature } from "./hui-temperature-forecast-card-feature";
|
||||
import { supportsTargetHumidityCardFeature } from "./hui-target-humidity-card-feature";
|
||||
import { supportsTargetTemperatureCardFeature } from "./hui-target-temperature-card-feature";
|
||||
import { supportsTimeSetCardFeature } from "./hui-time-set-card-feature";
|
||||
import { supportsTimerActionsCardFeature } from "./hui-timer-actions-card-feature";
|
||||
import { supportsTimerPresetsCardFeature } from "./hui-timer-presets-card-feature";
|
||||
import { supportsTimerProgressCardFeature } from "./hui-timer-progress-card-feature";
|
||||
@@ -110,7 +109,6 @@ export const UI_FEATURE_TYPES = [
|
||||
"trend-graph",
|
||||
"target-humidity",
|
||||
"target-temperature",
|
||||
"time-set",
|
||||
"timer-actions",
|
||||
"timer-presets",
|
||||
"timer-progress",
|
||||
@@ -171,7 +169,6 @@ export const SUPPORTS_FEATURE_TYPES: Record<UiFeatureType, SupportsFeature> = {
|
||||
"target-humidity": supportsTargetHumidityCardFeature,
|
||||
"target-temperature": supportsTargetTemperatureCardFeature,
|
||||
"temperature-forecast": supportsTemperatureForecastCardFeature,
|
||||
"time-set": supportsTimeSetCardFeature,
|
||||
"timer-actions": supportsTimerActionsCardFeature,
|
||||
"timer-presets": supportsTimerPresetsCardFeature,
|
||||
"timer-progress": supportsTimerProgressCardFeature,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { AlarmMode } from "../../../data/alarm_control_panel";
|
||||
import type { HvacMode } from "../../../data/climate";
|
||||
import type { FanSpeedStyle } from "../../../data/fan";
|
||||
import type { TimeFormat } from "../../../data/translation";
|
||||
import type { OperationMode } from "../../../data/water_heater";
|
||||
import type { ForecastPrecipitationType } from "../../../data/weather";
|
||||
|
||||
@@ -214,11 +213,6 @@ export interface TargetTemperatureCardFeatureConfig {
|
||||
style?: "buttons" | "slider";
|
||||
}
|
||||
|
||||
export interface TimeSetCardFeatureConfig {
|
||||
type: "time-set";
|
||||
time_format?: TimeFormat;
|
||||
}
|
||||
|
||||
export interface ToggleCardFeatureConfig {
|
||||
type: "toggle";
|
||||
}
|
||||
@@ -414,7 +408,6 @@ export type LovelaceCardFeatureConfig =
|
||||
| TrendGraphCardFeatureConfig
|
||||
| TargetHumidityCardFeatureConfig
|
||||
| TargetTemperatureCardFeatureConfig
|
||||
| TimeSetCardFeatureConfig
|
||||
| TimerActionsCardFeatureConfig
|
||||
| TimerPresetsCardFeatureConfig
|
||||
| TimerProgressCardFeatureConfig
|
||||
|
||||
@@ -19,14 +19,6 @@ const NUMERIC_INPUT_VARIANTS: TileVariant[] = [TILE_VARIANT, ["numeric-input"]];
|
||||
|
||||
const DATE_VARIANTS: TileVariant[] = [TILE_VARIANT, ["date-set"]];
|
||||
|
||||
const TIME_VARIANTS: TileVariant[] = [TILE_VARIANT, ["time-set"]];
|
||||
|
||||
const DATETIME_VARIANTS: TileVariant[] = [
|
||||
TILE_VARIANT,
|
||||
["date-set"],
|
||||
["time-set"],
|
||||
];
|
||||
|
||||
const BUTTON_VARIANTS: TileVariant[] = [TILE_VARIANT, ["button"]];
|
||||
|
||||
const DOMAIN_VARIANTS: Record<string, TileVariant[]> = {
|
||||
@@ -97,16 +89,15 @@ const DOMAIN_VARIANTS: Record<string, TileVariant[]> = {
|
||||
select: SELECT_VARIANTS,
|
||||
input_number: NUMERIC_INPUT_VARIANTS,
|
||||
number: NUMERIC_INPUT_VARIANTS,
|
||||
input_datetime: DATETIME_VARIANTS,
|
||||
input_datetime: DATE_VARIANTS,
|
||||
date: DATE_VARIANTS,
|
||||
time: TIME_VARIANTS,
|
||||
update: [TILE_VARIANT, ["update-actions"]],
|
||||
water_heater: [
|
||||
TILE_VARIANT,
|
||||
["water-heater-operation-modes"],
|
||||
["target-temperature"],
|
||||
],
|
||||
datetime: DATETIME_VARIANTS,
|
||||
datetime: DATE_VARIANTS,
|
||||
button: BUTTON_VARIANTS,
|
||||
input_button: BUTTON_VARIANTS,
|
||||
scene: BUTTON_VARIANTS,
|
||||
|
||||
@@ -14,7 +14,6 @@ import { consume } from "../../../../common/decorators/consume";
|
||||
import { formatNumberWithUnit } from "../../../../common/number/format_number";
|
||||
import "../../../../components/chart/ha-chart-base";
|
||||
import "../../../../components/chart/ha-chart-tooltip-marker";
|
||||
import { wrapLitTooltipFormatter } from "../../../../components/chart/lit-tooltip-formatter";
|
||||
import {
|
||||
formattersContext,
|
||||
internationalizationContext,
|
||||
@@ -50,7 +49,6 @@ import type { HaECOption } from "../../../../resources/echarts/echarts";
|
||||
import "../../../../components/ha-card";
|
||||
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import { measureTextWidth } from "../../../../util/text";
|
||||
import "../../../../components/ha-icon-button";
|
||||
import { storage } from "../../../../common/decorators/storage";
|
||||
import { getEnergyColor } from "./common/color";
|
||||
@@ -198,9 +196,9 @@ export class HuiEnergyDevicesGraphCard
|
||||
<ha-chart-base
|
||||
.data=${this._chartData}
|
||||
.options=${this._createOptions(
|
||||
this._chartData,
|
||||
this._chartType,
|
||||
this._legendData
|
||||
this._legendData,
|
||||
this._hiddenStats
|
||||
)}
|
||||
.height=${`${Math.max(modes.includes("pie") ? 300 : 100, (this._legendData?.length || 0) * 28 + 50)}px`}
|
||||
.sonificationLabelFormatter=${this._sonificationLabel}
|
||||
@@ -252,97 +250,61 @@ export class HuiEnergyDevicesGraphCard
|
||||
<div style="direction:ltr; display: inline;">${value}</div>`;
|
||||
};
|
||||
|
||||
private _renderLabelTooltip = wrapLitTooltipFormatter(
|
||||
(params: { value: string }) => {
|
||||
const series = this._chartData[0];
|
||||
const item = (series?.data as any[] | undefined)?.find(
|
||||
(d) => d.id === params.value
|
||||
);
|
||||
return item
|
||||
? this._renderTooltip({
|
||||
name: item.name,
|
||||
value: item.value,
|
||||
color: item.itemStyle.color,
|
||||
seriesName: series.name,
|
||||
})
|
||||
: nothing;
|
||||
}
|
||||
);
|
||||
|
||||
private _createOptions = memoizeOne(
|
||||
(
|
||||
data: (BarSeriesOption | PieSeriesOption)[],
|
||||
chartType: "bar" | "pie",
|
||||
legendData: typeof this._legendData
|
||||
legendData: typeof this._legendData,
|
||||
hiddenStats: string[]
|
||||
): HaECOption => {
|
||||
const options: HaECOption = {
|
||||
grid: {
|
||||
top: 5,
|
||||
left: 5,
|
||||
right: 40,
|
||||
bottom: 0,
|
||||
containLabel: true,
|
||||
},
|
||||
const selected = Object.fromEntries(hiddenStats.map((id) => [id, false]));
|
||||
if (chartType === "bar") {
|
||||
const legend: CustomLegendOption = {
|
||||
type: "custom",
|
||||
show: true,
|
||||
position: "y-axis",
|
||||
data: [
|
||||
...legendData.filter((d) => !hiddenStats.includes(d.id!)),
|
||||
...legendData.filter((d) => hiddenStats.includes(d.id!)),
|
||||
].map(({ value: _value, ...item }) => item),
|
||||
selected,
|
||||
};
|
||||
return {
|
||||
grid: {
|
||||
top: 0,
|
||||
bottom: 24,
|
||||
left: 8,
|
||||
right: 40,
|
||||
},
|
||||
tooltip: {
|
||||
show: true,
|
||||
formatter: this._renderTooltip,
|
||||
},
|
||||
xAxis: {
|
||||
show: true,
|
||||
type: "value",
|
||||
name: "kWh",
|
||||
axisPointer: {
|
||||
show: false,
|
||||
},
|
||||
},
|
||||
yAxis: { show: true, type: "category" },
|
||||
legend,
|
||||
};
|
||||
}
|
||||
return {
|
||||
tooltip: {
|
||||
show: true,
|
||||
formatter: this._renderTooltip,
|
||||
},
|
||||
xAxis: { show: false },
|
||||
yAxis: { show: false },
|
||||
legend: { type: "custom", show: false },
|
||||
};
|
||||
if (chartType === "bar") {
|
||||
options.xAxis = {
|
||||
show: true,
|
||||
type: "value",
|
||||
name: "kWh",
|
||||
axisPointer: {
|
||||
show: false,
|
||||
},
|
||||
};
|
||||
options.yAxis = {
|
||||
show: true,
|
||||
type: "category",
|
||||
inverse: true,
|
||||
triggerEvent: true,
|
||||
// ECharts types only list `show`, but the label tooltip takes the
|
||||
// formatter too
|
||||
tooltip: {
|
||||
show: true,
|
||||
formatter: this._renderLabelTooltip,
|
||||
} as { show: boolean },
|
||||
// take order from data
|
||||
data: data[0]?.data?.map((d: any) => d.name),
|
||||
axisLabel: {
|
||||
formatter: this._getDeviceName.bind(this),
|
||||
overflow: "truncate",
|
||||
fontSize: 12,
|
||||
margin: 5,
|
||||
width: Math.min(
|
||||
this._isMobileSize ? 100 : 200,
|
||||
Math.max(
|
||||
...(data[0]?.data?.map(
|
||||
(d: any) =>
|
||||
measureTextWidth(this._getDeviceName(d.name), 12) + 5
|
||||
) || [])
|
||||
)
|
||||
),
|
||||
},
|
||||
};
|
||||
} else {
|
||||
options.legend = {
|
||||
legend: {
|
||||
type: "custom",
|
||||
show: true,
|
||||
data: legendData,
|
||||
selected: legendData
|
||||
.filter((d) => d.id && this._hiddenStats.includes(d.id))
|
||||
.reduce((acc, d) => {
|
||||
acc[d.id!] = false;
|
||||
return acc;
|
||||
}, {}),
|
||||
};
|
||||
}
|
||||
return options;
|
||||
selected,
|
||||
},
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
@@ -657,14 +619,6 @@ export class HuiEnergyDevicesGraphCard
|
||||
|
||||
private _handleChartClick(e: CustomEvent<ECElementEvent>): void {
|
||||
if (
|
||||
e.detail.targetType === "axisLabel" &&
|
||||
e.detail.value &&
|
||||
!isExternalStatistic(e.detail.value as string)
|
||||
) {
|
||||
fireEvent(this, "hass-more-info", {
|
||||
entityId: e.detail.value as string,
|
||||
});
|
||||
} else if (
|
||||
e.detail.seriesType === "pie" &&
|
||||
e.detail.event?.target?.type === "tspan" // label
|
||||
) {
|
||||
|
||||
@@ -21,10 +21,15 @@ import {
|
||||
statesContext,
|
||||
uiContext,
|
||||
} from "../../../../data/context";
|
||||
import type { EnergyData, EnergySourceByType } from "../../../../data/energy";
|
||||
import type {
|
||||
EnergyData,
|
||||
EnergySourceByType,
|
||||
FixedCostType,
|
||||
} from "../../../../data/energy";
|
||||
import {
|
||||
calculateGridNetCost,
|
||||
energySourcesByType,
|
||||
fixedCostsByType,
|
||||
getBatteryEnergyStatIds,
|
||||
getBatteryName,
|
||||
validateEnergyCollectionKey,
|
||||
@@ -178,8 +183,8 @@ export class HuiEnergySourcesTableCard
|
||||
type: string,
|
||||
statId: string,
|
||||
idx: number,
|
||||
energy: number,
|
||||
compareEnergy: number,
|
||||
energy: number | null,
|
||||
compareEnergy: number | null,
|
||||
energyUnit: string,
|
||||
cost: number | null,
|
||||
compareCost: number | null,
|
||||
@@ -201,18 +206,24 @@ export class HuiEnergySourcesTableCard
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const formattedEnergy = formatNumberWithUnit(
|
||||
energy,
|
||||
energyUnit,
|
||||
this._i18n.locale,
|
||||
formatOptions
|
||||
);
|
||||
const formattedCompareEnergy = formatNumberWithUnit(
|
||||
compareEnergy,
|
||||
energyUnit,
|
||||
this._i18n.locale,
|
||||
formatOptions
|
||||
);
|
||||
const formattedEnergy =
|
||||
energy === null
|
||||
? ""
|
||||
: formatNumberWithUnit(
|
||||
energy,
|
||||
energyUnit,
|
||||
this._i18n.locale,
|
||||
formatOptions
|
||||
);
|
||||
const formattedCompareEnergy =
|
||||
compareEnergy === null
|
||||
? ""
|
||||
: formatNumberWithUnit(
|
||||
compareEnergy,
|
||||
energyUnit,
|
||||
this._i18n.locale,
|
||||
formatOptions
|
||||
);
|
||||
|
||||
const label =
|
||||
name ||
|
||||
@@ -444,7 +455,8 @@ export class HuiEnergySourcesTableCard
|
||||
types.water?.some(
|
||||
(flow) =>
|
||||
flow.stat_cost || flow.entity_energy_price || flow.number_energy_price
|
||||
)
|
||||
) ||
|
||||
this._data.prefs.fixed_costs.some((fixedCost) => types[fixedCost.type])
|
||||
);
|
||||
|
||||
const units = {
|
||||
@@ -485,9 +497,13 @@ export class HuiEnergySourcesTableCard
|
||||
this._data.statsCompare
|
||||
)
|
||||
: undefined;
|
||||
const hasGridCost = gridCost !== undefined || gridCostCompare !== undefined;
|
||||
const totalGridCost = gridCost ?? 0;
|
||||
const totalGridCostCompare = gridCostCompare ?? 0;
|
||||
const gridHasEnergy = !!types.grid?.some(
|
||||
(source) => !!source.stat_energy_from || !!source.stat_energy_to
|
||||
);
|
||||
// Fixed costs are added to these while their rows render
|
||||
let hasGridCost = gridCost !== undefined || gridCostCompare !== undefined;
|
||||
let totalGridCost = gridCost ?? 0;
|
||||
let totalGridCostCompare = gridCostCompare ?? 0;
|
||||
|
||||
const _extractStatData = (
|
||||
statId: string,
|
||||
@@ -617,6 +633,60 @@ export class HuiEnergySourcesTableCard
|
||||
"ui.panel.lovelace.cards.energy.energy_distribution.grid"
|
||||
);
|
||||
|
||||
const fixedCosts = fixedCostsByType(this._data.prefs);
|
||||
|
||||
const _renderFixedCosts = (type: FixedCostType) => {
|
||||
const sourceCount = types[type]?.length;
|
||||
if (!sourceCount) {
|
||||
return nothing;
|
||||
}
|
||||
return fixedCosts[type]?.map((fixedCost, idx) => {
|
||||
const statId = this._data!.info.fixed_cost_sensors[fixedCost.id];
|
||||
if (!statId) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const cost = calculateStatisticSumGrowth(this._data!.stats[statId]);
|
||||
const costCompare = compare
|
||||
? calculateStatisticSumGrowth(this._data!.statsCompare[statId])
|
||||
: null;
|
||||
|
||||
if (cost === null && costCompare === null) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
if (type === "grid") {
|
||||
hasGridCost = true;
|
||||
totalGridCost += cost ?? 0;
|
||||
totalGridCostCompare += costCompare ?? 0;
|
||||
} else {
|
||||
hasCosts[type] = true;
|
||||
totalCosts[type] += cost ?? 0;
|
||||
totalCostsCompare[type] += costCompare ?? 0;
|
||||
}
|
||||
|
||||
if (showOnlyTotals) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
// Shades after the source rows keep the bullets distinct from them
|
||||
return this._renderRow(
|
||||
computedStyles,
|
||||
type === "grid" ? "grid_consumption" : type,
|
||||
statId,
|
||||
sourceCount + idx,
|
||||
null,
|
||||
null,
|
||||
"",
|
||||
cost,
|
||||
costCompare,
|
||||
showCosts,
|
||||
compare,
|
||||
fixedCost.name
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const _renderSimpleCategory = (type: "solar" | "gas" | "water") =>
|
||||
html` ${types[type]?.map((source, idx) => {
|
||||
const cost_stat =
|
||||
@@ -658,6 +728,7 @@ export class HuiEnergySourcesTableCard
|
||||
source.name
|
||||
);
|
||||
})}
|
||||
${type === "solar" ? nothing : _renderFixedCosts(type)}
|
||||
${
|
||||
types[type]
|
||||
? this._renderTotalRow(
|
||||
@@ -1017,17 +1088,15 @@ export class HuiEnergySourcesTableCard
|
||||
)
|
||||
: gridName
|
||||
)}
|
||||
${_renderFixedCosts("grid")}
|
||||
${
|
||||
types.grid &&
|
||||
types.grid.some(
|
||||
(s) => !!s.stat_energy_from || !!s.stat_energy_to
|
||||
)
|
||||
types.grid && (gridHasEnergy || hasGridCost)
|
||||
? this._renderTotalRow(
|
||||
this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.energy_sources_table.grid_total"
|
||||
),
|
||||
totalGrid,
|
||||
totalGridCompare,
|
||||
gridHasEnergy ? totalGrid : null,
|
||||
gridHasEnergy ? totalGridCompare : null,
|
||||
"kWh",
|
||||
hasGridCost ? totalGridCost : null,
|
||||
hasGridCost ? totalGridCostCompare : null,
|
||||
|
||||
@@ -30,9 +30,11 @@ import type {
|
||||
GridSourceTypeEnergyPreference,
|
||||
} from "../../../../data/energy";
|
||||
import {
|
||||
calculateFixedCostTotal,
|
||||
calculateGridNetCost,
|
||||
computeConsumptionData,
|
||||
energySourcesByType,
|
||||
fixedCostsByType,
|
||||
getBatteryEnergyStatIds,
|
||||
getBatteryFlowStatIds,
|
||||
getBatteryName,
|
||||
@@ -630,11 +632,24 @@ export class HuiEnergyUsageGraphCard
|
||||
this._chartData = datasets;
|
||||
this._legendData = this._getLegendData(datasets);
|
||||
this._total = this._processTotal(consumption);
|
||||
this._totalCost = calculateGridNetCost(
|
||||
energySourcesByType(energyData.prefs).grid ?? [],
|
||||
const gridSources = energySourcesByType(energyData.prefs).grid ?? [];
|
||||
const gridCost = calculateGridNetCost(
|
||||
gridSources,
|
||||
energyData.info,
|
||||
energyData.stats
|
||||
);
|
||||
// Like the sources table, fixed costs only count next to a grid source
|
||||
const fixedCost = gridSources.length
|
||||
? calculateFixedCostTotal(
|
||||
fixedCostsByType(energyData.prefs).grid ?? [],
|
||||
energyData.info,
|
||||
energyData.stats
|
||||
)
|
||||
: undefined;
|
||||
this._totalCost =
|
||||
gridCost === undefined && fixedCost === undefined
|
||||
? undefined
|
||||
: (gridCost ?? 0) + (fixedCost ?? 0);
|
||||
}
|
||||
|
||||
private _getLegendData(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { PropertyValues, TemplateResult } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, query, queryAll, state } from "lit/decorators";
|
||||
import { customElement, queryAll, state } from "lit/decorators";
|
||||
import { DOMAINS_TOGGLE } from "../../../common/const";
|
||||
import { applyThemesOnElement } from "../../../common/dom/apply_themes_on_element";
|
||||
import { computeDomain } from "../../../common/entity/compute_domain";
|
||||
@@ -81,8 +81,6 @@ class HuiEntitiesCard extends LitElement implements LovelaceCard {
|
||||
|
||||
@queryAll("#states > div > *") private _rowElements!: NodeListOf<HTMLElement>;
|
||||
|
||||
@query("hui-entities-toggle") private _entitiesToggle?: HTMLElement;
|
||||
|
||||
private _hass?: HomeAssistant;
|
||||
|
||||
private _configEntities?: LovelaceRowConfig[];
|
||||
@@ -119,9 +117,6 @@ class HuiEntitiesCard extends LitElement implements LovelaceCard {
|
||||
if (this._footerElement) {
|
||||
this._footerElement.hass = hass;
|
||||
}
|
||||
if (this._entitiesToggle) {
|
||||
(this._entitiesToggle as any).hass = hass;
|
||||
}
|
||||
}
|
||||
|
||||
public async getCardSize(): Promise<number> {
|
||||
@@ -242,7 +237,6 @@ class HuiEntitiesCard extends LitElement implements LovelaceCard {
|
||||
? nothing
|
||||
: html`
|
||||
<hui-entities-toggle
|
||||
.hass=${this._hass}
|
||||
.entities=${(
|
||||
this._configEntities!.filter(
|
||||
(conf) => "entity" in conf
|
||||
|
||||
@@ -12,8 +12,8 @@ import { transform } from "../../../common/decorators/transform";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import { computeDomain } from "../../../common/entity/compute_domain";
|
||||
import {
|
||||
findEntities,
|
||||
generateEntityFilter,
|
||||
createEntityFinder,
|
||||
type EntityFinder,
|
||||
} from "../../../common/entity/entity_filter";
|
||||
import { formatNumber } from "../../../common/number/format_number";
|
||||
import "../../../components/ha-card";
|
||||
@@ -52,17 +52,26 @@ import {
|
||||
filterLowBatteryEntities,
|
||||
filterProblemEntities,
|
||||
filterUnavailableBatteryEntities,
|
||||
findMaintenanceEntities,
|
||||
} from "../../maintenance/strategies/maintenance-view-strategy";
|
||||
import {
|
||||
isSecurityAlertActive,
|
||||
resolveSecurityAlertSeverity,
|
||||
} from "../../security/strategies/security-alerts";
|
||||
import { findSecurityEntities } from "../../security/strategies/security-view-strategy";
|
||||
import type { LovelaceCard, LovelaceGridOptions } from "../types";
|
||||
import { tileCardStyle } from "./tile/tile-card-style";
|
||||
import type { HomeSummaryCard } from "./types";
|
||||
|
||||
const summaryEntityFinders = new Map<HomeSummary, EntityFinder>();
|
||||
|
||||
const getSummaryEntityFinder = (summary: HomeSummary): EntityFinder => {
|
||||
let finder = summaryEntityFinders.get(summary);
|
||||
if (!finder) {
|
||||
finder = createEntityFinder(HOME_SUMMARIES_FILTERS[summary]);
|
||||
summaryEntityFinders.set(summary, finder);
|
||||
}
|
||||
return finder;
|
||||
};
|
||||
|
||||
@customElement("hui-home-summary-card")
|
||||
export class HuiHomeSummaryCard extends LitElement implements LovelaceCard {
|
||||
@state() private _config?: HomeSummaryCard;
|
||||
@@ -168,17 +177,14 @@ export class HuiHomeSummaryCard extends LitElement implements LovelaceCard {
|
||||
return "";
|
||||
}
|
||||
const { localize, locale } = this._i18n;
|
||||
const allEntities = Object.keys(states);
|
||||
const findSummaryEntities = (summary: HomeSummary) =>
|
||||
getSummaryEntityFinder(summary)(states, entities, devices, areas, floors);
|
||||
|
||||
switch (this._config.summary) {
|
||||
case "light": {
|
||||
// Number of lights on
|
||||
const lightsFilters = HOME_SUMMARIES_FILTERS.light.map((filter) =>
|
||||
generateEntityFilter(states, entities, devices, areas, floors, filter)
|
||||
);
|
||||
|
||||
const lightEntities = filterGroupsWithListedMembers(
|
||||
findEntities(allEntities, lightsFilters),
|
||||
findSummaryEntities("light"),
|
||||
states
|
||||
);
|
||||
|
||||
@@ -237,13 +243,7 @@ export class HuiHomeSummaryCard extends LitElement implements LovelaceCard {
|
||||
}
|
||||
case "security": {
|
||||
// Alarm and lock status
|
||||
const securityEntities = findSecurityEntities({
|
||||
states,
|
||||
entities,
|
||||
devices,
|
||||
areas,
|
||||
floors,
|
||||
});
|
||||
const securityEntities = findSummaryEntities("security");
|
||||
|
||||
const locks = securityEntities.filter((entityId) => {
|
||||
const domain = computeDomain(entityId);
|
||||
@@ -297,22 +297,7 @@ export class HuiHomeSummaryCard extends LitElement implements LovelaceCard {
|
||||
}
|
||||
case "media_players": {
|
||||
// Playing media
|
||||
const mediaPlayerFilters = HOME_SUMMARIES_FILTERS.media_players.map(
|
||||
(filter) =>
|
||||
generateEntityFilter(
|
||||
states,
|
||||
entities,
|
||||
devices,
|
||||
areas,
|
||||
floors,
|
||||
filter
|
||||
)
|
||||
);
|
||||
|
||||
const mediaPlayerEntities = findEntities(
|
||||
allEntities,
|
||||
mediaPlayerFilters
|
||||
);
|
||||
const mediaPlayerEntities = findSummaryEntities("media_players");
|
||||
|
||||
const playingMedia = mediaPlayerEntities.filter((entityId) => {
|
||||
const s = states[entityId]?.state;
|
||||
@@ -326,13 +311,7 @@ export class HuiHomeSummaryCard extends LitElement implements LovelaceCard {
|
||||
: localize("ui.card.home-summary.no_media_playing");
|
||||
}
|
||||
case "maintenance": {
|
||||
const maintenanceEntities = findMaintenanceEntities({
|
||||
states,
|
||||
entities,
|
||||
devices,
|
||||
areas,
|
||||
floors,
|
||||
});
|
||||
const maintenanceEntities = findSummaryEntities("maintenance");
|
||||
|
||||
const lowBatteryEntities = filterLowBatteryEntities(
|
||||
states,
|
||||
@@ -400,10 +379,7 @@ export class HuiHomeSummaryCard extends LitElement implements LovelaceCard {
|
||||
return formatConsumptionShort(locale, totalConsumption, "kWh");
|
||||
}
|
||||
case "persons": {
|
||||
const personsFilters = HOME_SUMMARIES_FILTERS.persons.map((filter) =>
|
||||
generateEntityFilter(states, entities, devices, areas, floors, filter)
|
||||
);
|
||||
const personEntities = findEntities(allEntities, personsFilters);
|
||||
const personEntities = findSummaryEntities("persons");
|
||||
const personsHome = personEntities.filter((entityId) => {
|
||||
const s = states[entityId]?.state;
|
||||
return s === "home";
|
||||
|
||||
@@ -141,8 +141,8 @@ class HuiPictureEntityCard extends LitElement implements LovelaceCard {
|
||||
if (this._config.show_name && this._config.show_state) {
|
||||
footer = html`
|
||||
<div class="footer both">
|
||||
<div>${name}</div>
|
||||
<div>${entityState}</div>
|
||||
<div class="name">${name}</div>
|
||||
<div class="state">${entityState}</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (this._config.show_name) {
|
||||
@@ -271,6 +271,17 @@ class HuiPictureEntityCard extends LitElement implements LovelaceCard {
|
||||
.both {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: var(--ha-space-2);
|
||||
}
|
||||
|
||||
.both .name {
|
||||
min-width: 0;
|
||||
overflow-x: clip;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.both .state {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.single {
|
||||
|
||||
@@ -13,16 +13,14 @@ import "../../../components/tile/ha-tile-icon";
|
||||
import "../../../components/tile/ha-tile-info";
|
||||
import {
|
||||
configContext,
|
||||
formattersContext,
|
||||
internationalizationContext,
|
||||
statesContext,
|
||||
} from "../../../data/context";
|
||||
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
|
||||
import { filterUpdateEntities, updateCanInstall } from "../../../data/update";
|
||||
import { countInstallableUpdates } from "../../../data/update";
|
||||
import type {
|
||||
CurrentUser,
|
||||
HomeAssistantConfig,
|
||||
HomeAssistantFormatters,
|
||||
HomeAssistantInternationalization,
|
||||
} from "../../../types";
|
||||
import { hasAction } from "../common/has-action";
|
||||
@@ -40,10 +38,6 @@ export class HuiUpdatesCard extends LitElement implements LovelaceCard {
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: HomeAssistantInternationalization;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
private _formatters!: HomeAssistantFormatters;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, CurrentUser | undefined>({
|
||||
@@ -53,19 +47,7 @@ export class HuiUpdatesCard extends LitElement implements LovelaceCard {
|
||||
|
||||
@state()
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
@transform<HassEntities, number>({
|
||||
transformer: function (this: HuiUpdatesCard, states) {
|
||||
if (!this._formatters) {
|
||||
return undefined;
|
||||
}
|
||||
return filterUpdateEntities(
|
||||
states,
|
||||
this._formatters.formatEntityName,
|
||||
this._i18n?.locale.language
|
||||
).filter((entity) => updateCanInstall(entity, false)).length;
|
||||
},
|
||||
watch: ["_i18n", "_formatters"],
|
||||
})
|
||||
@transform<HassEntities, number>({ transformer: countInstallableUpdates })
|
||||
private _updateCount?: number;
|
||||
|
||||
public setConfig(config: UpdatesCardConfig): void {
|
||||
@@ -113,8 +95,6 @@ export class HuiUpdatesCard extends LitElement implements LovelaceCard {
|
||||
);
|
||||
}
|
||||
|
||||
// Runs after @transform has refreshed _updateCount, which happens after
|
||||
// willUpdate.
|
||||
protected update(changedProps: PropertyValues): void {
|
||||
if (this._config) {
|
||||
this._updateVisibility();
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { STATES_OFF } from "../../../../common/const";
|
||||
import { computeDomain } from "../../../../common/entity/compute_domain";
|
||||
import { computeStateDomain } from "../../../../common/entity/compute_state_domain";
|
||||
import { getToggleAction } from "../../../../common/entity/get_toggle_action";
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type { HomeAssistantApi } from "../../../../types";
|
||||
|
||||
export const turnOnOffEntities = (
|
||||
hass: HomeAssistant,
|
||||
entityIds: string[],
|
||||
callService: HomeAssistantApi["callService"],
|
||||
stateObjs: HassEntity[],
|
||||
turnOn = true
|
||||
): void => {
|
||||
const domainsToCall = {};
|
||||
entityIds.forEach((entityId) => {
|
||||
if (STATES_OFF.includes(hass.states[entityId].state) === turnOn) {
|
||||
const stateDomain = computeDomain(entityId);
|
||||
stateObjs.forEach((stateObj) => {
|
||||
if (STATES_OFF.includes(stateObj.state) === turnOn) {
|
||||
const stateDomain = computeStateDomain(stateObj);
|
||||
// Entities with non-standard toggle action need separate calls
|
||||
const serviceDomain =
|
||||
getToggleAction(stateDomain, true) !== "turn_on"
|
||||
@@ -21,7 +22,7 @@ export const turnOnOffEntities = (
|
||||
if (!(serviceDomain in domainsToCall)) {
|
||||
domainsToCall[serviceDomain] = [];
|
||||
}
|
||||
domainsToCall[serviceDomain].push(entityId);
|
||||
domainsToCall[serviceDomain].push(stateObj.entity_id);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -29,6 +30,6 @@ export const turnOnOffEntities = (
|
||||
const service = getToggleAction(domain, turnOn);
|
||||
|
||||
const entities = domainsToCall[domain];
|
||||
hass.callService(domain, service, { entity_id: entities });
|
||||
callService(domain, service, { entity_id: entities });
|
||||
});
|
||||
};
|
||||
@@ -1,46 +1,59 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { DOMAINS_TOGGLE } from "../../../common/const";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import {
|
||||
consumeEntityStates,
|
||||
consumeLocalize,
|
||||
} from "../../../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-switch";
|
||||
import type { HaSwitch } from "../../../components/ha-switch";
|
||||
import { apiContext } from "../../../data/context";
|
||||
import { forwardHaptic } from "../../../data/haptics";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
import { turnOnOffEntities } from "../common/entity/turn-on-off-entities";
|
||||
|
||||
@customElement("hui-entities-toggle")
|
||||
class HuiEntitiesToggle extends LitElement {
|
||||
@property({ type: Array }) public entities?: string[];
|
||||
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
@state() _toggleEntities?: string[];
|
||||
|
||||
@state() private _toggleEntities?: string[];
|
||||
@state()
|
||||
@consumeEntityStates({ entityIdPath: ["_toggleEntities"] })
|
||||
private _stateObjs?: Record<string, HassEntity>;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize?: LocalizeFunc;
|
||||
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api?: ContextType<typeof apiContext>;
|
||||
|
||||
public willUpdate(changedProperties: PropertyValues<this>): void {
|
||||
super.willUpdate(changedProperties);
|
||||
if (changedProperties.has("entities")) {
|
||||
this._toggleEntities = this.entities!.filter(
|
||||
(entityId) =>
|
||||
entityId in this.hass!.states &&
|
||||
DOMAINS_TOGGLE.has(entityId.split(".", 1)[0])
|
||||
this._toggleEntities = this.entities!.filter((entityId) =>
|
||||
DOMAINS_TOGGLE.has(entityId.split(".", 1)[0])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this._toggleEntities?.length) {
|
||||
const stateObjs = Object.values(this._stateObjs ?? {});
|
||||
if (!stateObjs.length || !this._localize) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-switch
|
||||
.accessibleLabel=${this.hass!.localize(
|
||||
.accessibleLabel=${this._localize(
|
||||
"ui.panel.lovelace.card.entities.toggle"
|
||||
)}
|
||||
.checked=${this._toggleEntities!.some((entityId) => {
|
||||
const stateObj = this.hass!.states[entityId];
|
||||
return stateObj && stateObj.state === "on";
|
||||
})}
|
||||
.checked=${stateObjs.some((stateObj) => stateObj.state === "on")}
|
||||
@change=${this._callService}
|
||||
></ha-switch>
|
||||
`;
|
||||
@@ -59,9 +72,16 @@ class HuiEntitiesToggle extends LitElement {
|
||||
`;
|
||||
|
||||
private _callService(ev: MouseEvent): void {
|
||||
if (!this._api) {
|
||||
return;
|
||||
}
|
||||
forwardHaptic(this, "light");
|
||||
const turnOn = (ev.target as HaSwitch).checked;
|
||||
turnOnOffEntities(this.hass!, this._toggleEntities!, turnOn!);
|
||||
turnOnOffEntities(
|
||||
this._api.callService,
|
||||
Object.values(this._stateObjs ?? {}),
|
||||
turnOn
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,27 +1,46 @@
|
||||
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, eventOptions, property, query } from "lit/decorators";
|
||||
import {
|
||||
customElement,
|
||||
eventOptions,
|
||||
property,
|
||||
query,
|
||||
state,
|
||||
} from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { DOMAINS_INPUT_ROW } from "../../../common/const";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../common/decorators/transform";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import { stopPropagation } from "../../../common/dom/stop_propagation";
|
||||
import { computeDomain } from "../../../common/entity/compute_domain";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/entity/state-badge";
|
||||
import "../../../components/ha-relative-time";
|
||||
import "../../../components/ha-tooltip";
|
||||
import { configContext, formattersContext } from "../../../data/context";
|
||||
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
import type {
|
||||
HomeAssistant,
|
||||
HomeAssistantConfig,
|
||||
HomeAssistantFormatters,
|
||||
} from "../../../types";
|
||||
import type { EntitiesCardEntityConfig } from "../cards/types";
|
||||
import { actionHandler } from "../common/directives/action-handler-directive";
|
||||
import { handleAction } from "../common/handle-action";
|
||||
import { hasAction, hasAnyAction } from "../common/has-action";
|
||||
import { createEntityNotFoundWarning } from "./hui-warning";
|
||||
import "../../../state-display/state-display";
|
||||
|
||||
@customElement("hui-generic-entity-row")
|
||||
export class HuiGenericEntityRow extends LitElement {
|
||||
// Fallback for custom rows that pass `hass` instead of `stateObj`
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public stateObj?: HassEntity;
|
||||
|
||||
@property({ attribute: false }) public config?: EntitiesCardEntityConfig;
|
||||
|
||||
@property({ attribute: "secondary-text" }) public secondaryText?: string;
|
||||
@@ -36,22 +55,42 @@ export class HuiGenericEntityRow extends LitElement {
|
||||
@property({ attribute: "catch-interaction", type: Boolean })
|
||||
public catchInteraction?;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize?: LocalizeFunc;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, HassConfig>({
|
||||
transformer: ({ config }) => config,
|
||||
})
|
||||
private _hassConfig?: HassConfig;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
private _formatters?: HomeAssistantFormatters;
|
||||
|
||||
@query(".row > slot") private _controlSlot?: HTMLSlotElement;
|
||||
|
||||
private _pressedControl = false;
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this.config) {
|
||||
if (
|
||||
!this.config ||
|
||||
!this._localize ||
|
||||
!this._hassConfig ||
|
||||
!this._formatters
|
||||
) {
|
||||
return nothing;
|
||||
}
|
||||
const stateObj = this.config.entity
|
||||
? this.hass.states[this.config.entity]
|
||||
: undefined;
|
||||
const stateObj =
|
||||
this.stateObj ??
|
||||
(this.config.entity ? this.hass?.states[this.config.entity] : undefined);
|
||||
|
||||
if (!stateObj) {
|
||||
return html`
|
||||
<hui-warning>
|
||||
${createEntityNotFoundWarning(this.hass.localize, this.hass.config)}
|
||||
${createEntityNotFoundWarning(this._localize, this._hassConfig)}
|
||||
</hui-warning>
|
||||
`;
|
||||
}
|
||||
@@ -63,7 +102,7 @@ export class HuiGenericEntityRow extends LitElement {
|
||||
const pointer = hasAnyAction(this.config);
|
||||
|
||||
const hasSecondary = this.secondaryText || this.config.secondary_info;
|
||||
const name = this.hass.formatEntityName(stateObj, this.config.name);
|
||||
const name = this._formatters.formatEntityName(stateObj, this.config.name);
|
||||
|
||||
return html`
|
||||
<div
|
||||
@@ -161,7 +200,10 @@ export class HuiGenericEntityRow extends LitElement {
|
||||
}
|
||||
|
||||
private _handleAction(ev: ActionHandlerEvent) {
|
||||
handleAction(this, this.hass!, this.config!, ev.detail.action!);
|
||||
fireEvent(this, "hass-action", {
|
||||
config: this.config!,
|
||||
action: ev.detail.action!,
|
||||
});
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
|
||||
@@ -36,7 +36,6 @@ import "../card-features/hui-numeric-input-card-feature";
|
||||
import "../card-features/hui-select-options-card-feature";
|
||||
import "../card-features/hui-target-humidity-card-feature";
|
||||
import "../card-features/hui-target-temperature-card-feature";
|
||||
import "../card-features/hui-time-set-card-feature";
|
||||
import "../card-features/hui-timer-actions-card-feature";
|
||||
import "../card-features/hui-timer-presets-card-feature";
|
||||
import "../card-features/hui-timer-progress-card-feature";
|
||||
@@ -104,7 +103,6 @@ const TYPES = new Set<LovelaceCardFeatureConfig["type"]>([
|
||||
"target-humidity",
|
||||
"target-temperature",
|
||||
"temperature-forecast",
|
||||
"time-set",
|
||||
"timer-actions",
|
||||
"timer-presets",
|
||||
"timer-progress",
|
||||
|
||||
@@ -151,7 +151,11 @@ export const addEntitiesToLovelaceView = async (
|
||||
}
|
||||
const dashboardPath = viewUrlPath ?? LOVELACE_PANEL;
|
||||
const viewPath = newConfig.views[viewIndex].path || viewIndex;
|
||||
const dashboardTitle = getPanelTitleFromUrlPath(hass, dashboardPath);
|
||||
const dashboardTitle = getPanelTitleFromUrlPath(
|
||||
hass.localize,
|
||||
hass.panels,
|
||||
dashboardPath
|
||||
);
|
||||
showToast(element, {
|
||||
message: dashboardTitle
|
||||
? {
|
||||
|
||||
@@ -65,7 +65,6 @@ import { supportsNumericInputCardFeature } from "../../card-features/hui-numeric
|
||||
import { supportsSelectOptionsCardFeature } from "../../card-features/hui-select-options-card-feature";
|
||||
import { supportsTargetHumidityCardFeature } from "../../card-features/hui-target-humidity-card-feature";
|
||||
import { supportsTargetTemperatureCardFeature } from "../../card-features/hui-target-temperature-card-feature";
|
||||
import { supportsTimeSetCardFeature } from "../../card-features/hui-time-set-card-feature";
|
||||
import { supportsTimerActionsCardFeature } from "../../card-features/hui-timer-actions-card-feature";
|
||||
import { supportsTimerPresetsCardFeature } from "../../card-features/hui-timer-presets-card-feature";
|
||||
import { supportsTimerProgressCardFeature } from "../../card-features/hui-timer-progress-card-feature";
|
||||
@@ -136,7 +135,6 @@ const UI_FEATURE_TYPES = [
|
||||
"target-humidity",
|
||||
"target-temperature",
|
||||
"temperature-forecast",
|
||||
"time-set",
|
||||
"timer-actions",
|
||||
"timer-presets",
|
||||
"timer-progress",
|
||||
@@ -183,7 +181,6 @@ const EDITABLES_FEATURE_TYPES = new Set<UiFeatureTypes>([
|
||||
"select-options",
|
||||
"target-humidity",
|
||||
"target-temperature",
|
||||
"time-set",
|
||||
"timer-actions",
|
||||
"timer-presets",
|
||||
"trend-graph",
|
||||
@@ -242,7 +239,6 @@ const SUPPORTS_FEATURE_TYPES: Record<
|
||||
"target-humidity": supportsTargetHumidityCardFeature,
|
||||
"target-temperature": supportsTargetTemperatureCardFeature,
|
||||
"temperature-forecast": supportsTemperatureForecastCardFeature,
|
||||
"time-set": supportsTimeSetCardFeature,
|
||||
"timer-actions": supportsTimerActionsCardFeature,
|
||||
"timer-presets": supportsTimerPresetsCardFeature,
|
||||
"timer-progress": supportsTimerProgressCardFeature,
|
||||
|
||||
@@ -63,6 +63,10 @@ const cardConfigStruct = assign(
|
||||
})
|
||||
);
|
||||
|
||||
type ClockCardFormData = Omit<ClockCardConfig, "time_format"> & {
|
||||
time_format?: ClockCardConfig["time_format"] | "auto";
|
||||
};
|
||||
|
||||
@customElement("hui-clock-card-editor")
|
||||
export class HuiClockCardEditor
|
||||
extends LitElement
|
||||
@@ -121,7 +125,15 @@ export class HuiClockCardEditor
|
||||
value: "digital",
|
||||
},
|
||||
selector: {
|
||||
ui_clock_time_format: {},
|
||||
select: {
|
||||
mode: "dropdown",
|
||||
options: ["auto", ...Object.values(TimeFormat)].map((value) => ({
|
||||
value,
|
||||
label: localize(
|
||||
`ui.panel.lovelace.editor.card.clock.time_formats.${value}`
|
||||
),
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -219,13 +231,14 @@ export class HuiClockCardEditor
|
||||
] as const satisfies readonly HaFormSchema[]
|
||||
);
|
||||
|
||||
private _data = memoizeOne((config: ClockCardConfig): ClockCardConfig => {
|
||||
private _data = memoizeOne((config: ClockCardConfig): ClockCardFormData => {
|
||||
const dateConfig = getClockCardDateConfig(config);
|
||||
|
||||
const data: ClockCardConfig = {
|
||||
const data: ClockCardFormData = {
|
||||
...config,
|
||||
clock_style: config.clock_style ?? "digital",
|
||||
clock_size: config.clock_size ?? "small",
|
||||
time_format: config.time_format ?? "auto",
|
||||
show_seconds: config.show_seconds ?? false,
|
||||
no_background: config.no_background ?? false,
|
||||
// Analog clock options
|
||||
@@ -262,14 +275,14 @@ export class HuiClockCardEditor
|
||||
`;
|
||||
}
|
||||
|
||||
private _valueChanged(ev: ValueChangedEvent<ClockCardConfig>): void {
|
||||
private _valueChanged(ev: ValueChangedEvent<ClockCardFormData>): void {
|
||||
const config = ev.detail.value;
|
||||
|
||||
if (!config.date_format || config.date_format.length === 0) {
|
||||
delete config.date_format;
|
||||
}
|
||||
|
||||
if (!config.time_format) {
|
||||
if (config.time_format === "auto") {
|
||||
delete config.time_format;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type {
|
||||
HaFormSchema,
|
||||
SchemaUnion,
|
||||
} from "../../../../components/ha-form/types";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
|
||||
import type {
|
||||
LovelaceCardFeatureContext,
|
||||
TimeSetCardFeatureConfig,
|
||||
} from "../../card-features/types";
|
||||
import type { LovelaceCardFeatureEditor } from "../../types";
|
||||
|
||||
const SCHEMA = [
|
||||
{
|
||||
name: "time_format",
|
||||
selector: {
|
||||
ui_clock_time_format: {},
|
||||
},
|
||||
},
|
||||
] as const satisfies readonly HaFormSchema[];
|
||||
|
||||
@customElement("hui-time-set-card-feature-editor")
|
||||
export class HuiTimeSetCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state() private _config?: TimeSetCardFeatureConfig;
|
||||
|
||||
public setConfig(config: TimeSetCardFeatureConfig): void {
|
||||
this._config = config;
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${this._config}
|
||||
.schema=${SCHEMA}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@value-changed=${this._valueChanged}
|
||||
></ha-form>
|
||||
`;
|
||||
}
|
||||
|
||||
private _valueChanged(ev: ValueChangedEvent<TimeSetCardFeatureConfig>) {
|
||||
const { time_format, ...rest } = ev.detail.value;
|
||||
|
||||
const config: TimeSetCardFeatureConfig = time_format
|
||||
? { ...rest, time_format }
|
||||
: rest;
|
||||
|
||||
fireEvent(this, "config-changed", { config });
|
||||
}
|
||||
|
||||
private _computeLabelCallback = (schema: SchemaUnion<typeof SCHEMA>) =>
|
||||
this.hass!.localize(
|
||||
`ui.panel.lovelace.editor.features.types.time-set.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"hui-time-set-card-feature-editor": HuiTimeSetCardFeatureEditor;
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,7 @@ class HuiButtonEntityRow extends LitElement implements LovelaceRow {
|
||||
}
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
|
||||
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
|
||||
<ha-button
|
||||
appearance="plain"
|
||||
size="s"
|
||||
|
||||
@@ -42,7 +42,7 @@ class HuiClimateEntityRow extends LitElement implements LovelaceRow {
|
||||
}
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
|
||||
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
|
||||
<ha-climate-state .stateObj=${stateObj}> </ha-climate-state>
|
||||
</hui-generic-entity-row>
|
||||
`;
|
||||
|
||||
@@ -44,7 +44,7 @@ class HuiCoverEntityRow extends LitElement implements LovelaceRow {
|
||||
}
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
|
||||
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
|
||||
${
|
||||
isTiltOnly(stateObj)
|
||||
? html`
|
||||
|
||||
@@ -47,7 +47,7 @@ class HuiDateEntityRow extends LitElement implements LovelaceRow {
|
||||
const name = this.hass.formatEntityName(stateObj, this._config.name);
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
|
||||
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
|
||||
<ha-date-input
|
||||
.locale=${this.hass.locale}
|
||||
.disabled=${unavailable}
|
||||
|
||||
@@ -57,7 +57,7 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row
|
||||
.hass=${this.hass}
|
||||
.stateObj=${stateObj}
|
||||
.config=${this._config}
|
||||
hide-name
|
||||
>
|
||||
|
||||
@@ -56,7 +56,7 @@ class HuiEventEntityRow extends LitElement implements LovelaceRow {
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row
|
||||
.hass=${this.hass}
|
||||
.stateObj=${stateObj}
|
||||
.config=${this._config}
|
||||
.catchInteraction=${false}
|
||||
>
|
||||
|
||||
@@ -95,7 +95,7 @@ class HuiFanEntityRow extends LitElement implements LovelaceRow {
|
||||
stateObj.state === UNKNOWN);
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
|
||||
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
|
||||
${
|
||||
supportSpeedPercentage && !supportsOnOff
|
||||
? html`
|
||||
|
||||
@@ -60,7 +60,7 @@ class HuiGroupEntityRow extends LitElement implements LovelaceRow {
|
||||
}
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
|
||||
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
|
||||
${
|
||||
this._computeCanToggle(this.hass, stateObj.attributes.entity_id)
|
||||
? html`
|
||||
|
||||
@@ -43,7 +43,7 @@ class HuiHumidifierEntityRow extends LitElement implements LovelaceRow {
|
||||
}
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
|
||||
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
|
||||
<ha-humidifier-state .stateObj=${stateObj}> </ha-humidifier-state>
|
||||
</hui-generic-entity-row>
|
||||
`;
|
||||
|
||||
@@ -43,7 +43,7 @@ class HuiInputButtonEntityRow extends LitElement implements LovelaceRow {
|
||||
}
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
|
||||
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
|
||||
<ha-button
|
||||
appearance="plain"
|
||||
size="s"
|
||||
|
||||
@@ -50,7 +50,7 @@ class HuiInputDatetimeEntityRow extends LitElement implements LovelaceRow {
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row
|
||||
.hass=${this.hass}
|
||||
.stateObj=${stateObj}
|
||||
.config=${this._config}
|
||||
.hideName=${
|
||||
stateObj.attributes.has_date && stateObj.attributes.has_time
|
||||
|
||||
@@ -74,7 +74,7 @@ class HuiInputNumberEntityRow extends LitElement implements LovelaceRow {
|
||||
const name = this.hass.formatEntityName(stateObj, this._config.name);
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
|
||||
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
|
||||
${
|
||||
stateObj.attributes.mode === "slider"
|
||||
? html`
|
||||
|
||||
@@ -52,7 +52,7 @@ class HuiInputSelectEntityRow extends LitElement implements LovelaceRow {
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row
|
||||
.hass=${this.hass}
|
||||
.stateObj=${stateObj}
|
||||
.config=${this._config}
|
||||
hide-name
|
||||
>
|
||||
|
||||
@@ -47,7 +47,7 @@ class HuiInputTextEntityRow extends LitElement implements LovelaceRow {
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row
|
||||
.hass=${this.hass}
|
||||
.stateObj=${stateObj}
|
||||
.config=${this._config}
|
||||
hide-name
|
||||
>
|
||||
|
||||
@@ -44,7 +44,7 @@ class HuiLockEntityRow extends LitElement implements LovelaceRow {
|
||||
}
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row .hass=${this.hass} .config=${this._config}>
|
||||
<hui-generic-entity-row .stateObj=${stateObj} .config=${this._config}>
|
||||
<ha-button
|
||||
appearance="plain"
|
||||
size="s"
|
||||
|
||||
@@ -199,7 +199,7 @@ class HuiMediaPlayerEntityRow extends LitElement implements LovelaceRow {
|
||||
|
||||
return html`
|
||||
<hui-generic-entity-row
|
||||
.hass=${this.hass}
|
||||
.stateObj=${stateObj}
|
||||
.config=${this._config}
|
||||
.secondaryText=${
|
||||
mediaDescription || this.hass.formatEntityState(stateObj)
|
||||
|
||||
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user