Compare commits

...
Author SHA1 Message Date
Maarten Lakerveld da3977e061 Let users hide entities from the lights page
Move the lights panel onto HaHomeSummaryPanelBase, which brings a light hidden list in system data, config loading and the edit mode the climate and maintenance pages have. In edit mode the strategy sets `hideable` metadata on its tiles; the toggle groups and heading buttons have none, so they stay inert. It also drops the panel's leftover min-height: 100vh, which overflowed the top app bar's scroll area.

Hidden lights leave the page's tiles, the desktop toggle group and the mobile area on/off buttons. Those buttons now target the visible lights instead of the whole area, so they match the toggle group. A visible light group still switches all its members, hidden or not.

The Home overview's light badge and on count skip hidden lights too, and so does the Lights section of area pages, whose on/off buttons get the same visible-lights target.
2026-11-30 15:36:21 +01:00
Maarten Lakerveld 99edd37944 Let users hide entities from the climate page
Give the climate page a hidden list in system data by moving it onto the summary panel base, so it gets the same edit mode as maintenance. In edit mode the strategy sets `hideable` metadata on every tile it generates. The climate resolver also covers the area temperature and humidity sensors, which the page adds outside the entity filters, so they can be hidden too and the Home climate badge skips them.

The visible area sensor map is built once with the hidden list applied, so the page and the Home badge share one rule. Temperature and humidity tiles are labelled from the area slot they fill instead of reading device_class back off the state, which produced an empty name for sensors set through the API without a device class.
2026-11-30 15:36:20 +01:00
Maarten Lakerveld 4171b95acb Hide maintenance entities through Lovelace edit mode
Admins can hide entities from the maintenance page and the Home maintenance summary. The hidden ids are stored as the strategy's `hidden` option in frontend system data. The maintenance panel becomes a subclass of a new HaHomeSummaryPanelBase that holds loading, saving and edit mode, so the climate and lights pages can reuse them.

The pencil turns on real Lovelace edit mode, and the panel hands hui-view the strategy view instead of a generated one. Lovelace already knows which content a strategy generated: sections view, header, footer, sidebar and badges now skip their layout tools for a strategy view, its sections count as strategy content, and its cards aren't previewed.

In edit mode a strategy can set `metadata` on the cards it generates, only for the controls that apply. The maintenance tiles get `{ id, hideable: true }`, and grid sections wrap such cards in a show/hide toggle that fires `item-visibility-changed`. Other generated cards are inert while editing. While editing, the panel leaves `hidden` out so hidden tiles show, dimmed from `lovelace.hiddenIds`.

The panel sets `strategyEditSupport` on Lovelace to say it applies these controls. Only then does hui-view pass `editMode` to the view strategy and regenerate it when edit mode changes, and only then do grid sections show the toggles and make the other generated cards inert. A strategy view on a regular dashboard gets no controls that nothing would save.

A toggle saves and hands the view a new Lovelace object with the same config, so nothing rebuilds and focus stays on the toggle.

The view container now uses min-height: 100%, the value the climate and lights panels get once they move onto the base.

This replaces #55610, reverted in #55979, which faked edit mode with an entity-visibility wrapper card that any YAML dashboard could use.
2026-11-30 15:36:20 +01:00
34 changed files with 1320 additions and 812 deletions

No files matched your search

+17 -2
View File
@@ -163,9 +163,21 @@ export const findEntities = (
return results;
};
export const excludeEntities = (
entityIds: string[],
excludedEntityIds?: string[]
): string[] => {
if (!excludedEntityIds?.length) {
return entityIds;
}
const excluded = new Set(excludedEntityIds);
return entityIds.filter((entityId) => !excluded.has(entityId));
};
export const findFilteredEntities = (
sources: EntityFilterSources,
filters: EntityFilter[]
filters: EntityFilter[],
excludedEntityIds?: string[]
): string[] => {
const filterFuncs = filters.map((filter) =>
generateEntityFilter(
@@ -177,5 +189,8 @@ export const findFilteredEntities = (
filter
)
);
return findEntities(Object.keys(sources.states), filterFuncs);
return excludeEntities(
findEntities(Object.keys(sources.states), filterFuncs),
excludedEntityIds
);
};
+43
View File
@@ -56,6 +56,20 @@ export interface SecurityFrontendSystemData {
favorite_entities?: string[];
}
export interface MaintenanceFrontendSystemData {
hidden?: string[];
}
export interface ClimateFrontendSystemData {
hidden?: string[];
}
export interface LightFrontendSystemData {
hidden?: string[];
}
export type HomeSummaryPanelSystemDataKey = "maintenance" | "climate" | "light";
export interface EnergyFrontendSystemData {
// Stable "<view>.<card-type>" keys of energy dashboard cards the user has
// hidden. An absent key or array means nothing is hidden (all cards visible),
@@ -75,6 +89,9 @@ declare global {
home: HomeFrontendSystemData;
energy: EnergyFrontendSystemData;
security: SecurityFrontendSystemData;
maintenance: MaintenanceFrontendSystemData;
climate: ClimateFrontendSystemData;
light: LightFrontendSystemData;
}
}
@@ -151,6 +168,32 @@ export const saveFrontendSystemData = async <
value,
});
const pendingSystemDataSaves = new Map<ValidSystemDataKey, Promise<void>>();
export const queueFrontendSystemDataSave = <
SystemDataKey extends ValidSystemDataKey,
>(
conn: Connection,
key: SystemDataKey,
value: FrontendSystemData[SystemDataKey]
): Promise<void> => {
const save = (pendingSystemDataSaves.get(key) ?? Promise.resolve())
.catch(() => undefined)
.then(() => saveFrontendSystemData(conn, key, value));
pendingSystemDataSaves.set(key, save);
return save;
};
export const fetchFrontendSystemDataAfterSaves = async <
SystemDataKey extends ValidSystemDataKey,
>(
conn: Connection,
key: SystemDataKey
): Promise<FrontendSystemData[SystemDataKey] | null> => {
await pendingSystemDataSaves.get(key)?.catch(() => undefined);
return fetchFrontendSystemData(conn, key);
};
export const subscribeFrontendSystemData = <
SystemDataKey extends ValidSystemDataKey,
>(
+11
View File
@@ -4,6 +4,16 @@ import type {
LovelaceLayoutOptions,
} from "../../../panels/lovelace/types";
/**
* Set by a strategy on the cards it generates in edit mode, for the controls
* the panel showing them applies: `hideable` adds a show/hide toggle that
* fires `item-visibility-changed` with `id`.
*/
export interface LovelaceItemMetadata {
id: string;
hideable?: boolean;
}
export interface LovelaceCardConfig {
index?: number;
view_index?: number;
@@ -15,4 +25,5 @@ export interface LovelaceCardConfig {
[key: string]: any;
visibility?: VisibilityCondition[];
disabled?: boolean;
metadata?: LovelaceItemMetadata;
}
+4 -166
View File
@@ -1,171 +1,9 @@
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { debounce } from "../../common/util/debounce";
import { deepEqual } from "../../common/util/deep-equal";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { generateLovelaceViewStrategy } from "../lovelace/strategies/get-strategy";
import type { Lovelace } from "../lovelace/types";
import "../lovelace/views/hui-view";
import "../lovelace/views/hui-view-background";
import "../lovelace/views/hui-view-container";
import "../../components/ha-top-app-bar-fixed";
const CLIMATE_LOVELACE_VIEW_CONFIG: LovelaceStrategyViewConfig = {
strategy: {
type: "climate",
},
};
import { customElement } from "lit/decorators";
import { HaHomeSummaryPanelBase } from "../home/ha-home-summary-panel-base";
@customElement("ha-panel-climate")
class PanelClimate extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean, reflect: true }) public narrow = false;
@state() private _viewIndex = 0;
@state() private _lovelace?: Lovelace;
@state() private _searchParams = new URLSearchParams(window.location.search);
private _childPanelReady?: ChildPanelReady;
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
// Initial setup
if (!this.hasUpdated) {
this._setup();
return;
}
if (!changedProps.has("hass")) {
return;
}
const oldHass = changedProps.get("hass") as this["hass"];
if (oldHass && oldHass.localize !== this.hass.localize) {
this._setLovelace();
return;
}
if (oldHass && this.hass) {
// If the entity registry changed, ask the user if they want to refresh the config
if (
oldHass.entities !== this.hass.entities ||
oldHass.devices !== this.hass.devices ||
oldHass.areas !== this.hass.areas ||
oldHass.floors !== this.hass.floors ||
oldHass.panels !== this.hass.panels
) {
if (this.hass.config.state === "RUNNING") {
this._debounceRegistriesChanged();
return;
}
}
// If ha started, refresh the config
if (
this.hass.config.state === "RUNNING" &&
oldHass.config.state !== "RUNNING"
) {
this._setLovelace();
}
}
}
private async _setup() {
await this.hass.loadFragmentTranslation("lovelace");
this._setLovelace();
}
private _debounceRegistriesChanged = debounce(
() => this._registriesChanged(),
200
);
private _registriesChanged = async () => {
this._setLovelace();
};
protected render() {
return html`
<ha-top-app-bar-fixed
.narrow=${this.narrow}
.backButton=${this._searchParams.has("historyBack")}
>
<div slot="title">${this.hass.localize("panel.climate")}</div>
${
this._lovelace
? html`
<hui-view-container .hass=${this.hass}>
<hui-view-background .hass=${this.hass}>
</hui-view-background>
<hui-view
.hass=${this.hass}
.narrow=${this.narrow}
.lovelace=${this._lovelace}
.index=${this._viewIndex}
></hui-view
></hui-view-container>
`
: nothing
}
</ha-top-app-bar-fixed>
`;
}
private async _setLovelace() {
const viewConfig = await generateLovelaceViewStrategy(
CLIMATE_LOVELACE_VIEW_CONFIG,
this.hass
);
const config = { views: [viewConfig] };
const rawConfig = { views: [CLIMATE_LOVELACE_VIEW_CONFIG] };
if (deepEqual(config, this._lovelace?.config)) {
return;
}
this._childPanelReady ??= new ChildPanelReady(this);
this._lovelace = {
config: config,
rawConfig: rawConfig,
editMode: false,
urlPath: "climate",
mode: "generated",
locale: this.hass.locale,
enableFullEditMode: () => undefined,
saveConfig: async () => undefined,
deleteConfig: async () => undefined,
setEditMode: () => undefined,
showToast: () => undefined,
};
}
static get styles(): CSSResultGroup {
return [
haStyle,
css`
:host {
user-select: none;
}
hui-view-container {
position: relative;
display: flex;
min-height: 100vh;
box-sizing: border-box;
}
hui-view {
flex: 1 1 100%;
max-width: 100%;
}
`,
];
}
class PanelClimate extends HaHomeSummaryPanelBase<"climate"> {
protected readonly _systemDataKey = "climate";
}
declare global {
@@ -2,9 +2,10 @@ import { ReactiveElement } from "lit";
import { customElement } from "lit/decorators";
import { getAreasFloorHierarchy } from "../../../common/areas/areas-floor-hierarchy";
import {
findEntities,
findFilteredEntities,
generateEntityFilter,
type EntityFilter,
type EntityFilterSources,
} from "../../../common/entity/entity_filter";
import { floorDefaultIcon } from "../../../components/ha-floor-icon";
import type { LovelaceCardConfig } from "../../../data/lovelace/config/card";
@@ -12,9 +13,14 @@ import type { LovelaceSectionRawConfig } from "../../../data/lovelace/config/sec
import type { LovelaceViewConfig } from "../../../data/lovelace/config/view";
import type { HomeAssistant } from "../../../types";
import { computeAreaTileCardConfig } from "../../lovelace/strategies/areas/helpers/areas-strategy-helper";
import type {
LovelaceStrategyDependency,
LovelaceStrategyGenerateOptions,
} from "../../lovelace/strategies/types";
export interface ClimateViewStrategyConfig {
type: "climate";
hidden?: string[];
}
export const climateEntityFilters: EntityFilter[] = [
@@ -42,40 +48,53 @@ export const climateEntityFilters: EntityFilter[] = [
},
];
export const hasClimateEntities = (hass: HomeAssistant): boolean => {
const hasAreaSensor = Object.values(hass.areas).some(
(area) =>
(area.temperature_entity_id && hass.states[area.temperature_entity_id]) ||
(area.humidity_entity_id && hass.states[area.humidity_entity_id])
);
export const findClimateEntities = (
sources: EntityFilterSources,
hiddenEntities?: string[]
): string[] =>
findFilteredEntities(sources, climateEntityFilters, hiddenEntities);
if (hasAreaSensor) {
return true;
type ClimateAreaSensorKind = "temperature" | "humidity";
export const findClimateAreaSensors = (
sources: EntityFilterSources,
hiddenEntities?: string[]
): Map<string, ClimateAreaSensorKind> => {
const hidden = new Set(hiddenEntities);
const sensors = new Map<string, ClimateAreaSensorKind>();
for (const area of Object.values(sources.areas)) {
const slots = [
[area.temperature_entity_id, "temperature"],
[area.humidity_entity_id, "humidity"],
] as const;
for (const [entityId, kind] of slots) {
if (entityId && entityId in sources.states && !hidden.has(entityId)) {
sensors.set(entityId, kind);
}
}
}
const entityIds = Object.keys(hass.states);
return climateEntityFilters.some((filter) =>
entityIds.some(
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
filter
)
)
);
return sensors;
};
export const hasClimateEntities = (
hass: HomeAssistant,
hiddenEntities?: string[]
): boolean =>
findClimateAreaSensors(hass, hiddenEntities).size > 0 ||
findClimateEntities(hass, hiddenEntities).length > 0;
interface ClimateCardOptions {
entities: string[];
areaSensors: Map<string, ClimateAreaSensorKind>;
computeCard: (entityId: string) => LovelaceCardConfig;
}
const processAreasForClimate = (
areaIds: string[],
hass: HomeAssistant,
entities: string[]
{ entities, areaSensors, computeCard }: ClimateCardOptions
): LovelaceCardConfig[] => {
const cards: LovelaceCardConfig[] = [];
const computeTileCard = computeAreaTileCardConfig(hass, true);
for (const areaId of areaIds) {
const area = hass.areas[areaId];
@@ -96,25 +115,13 @@ const processAreasForClimate = (
// Add temperature and humidity sensors with trend graphs for areas
const temperatureEntityId = area.temperature_entity_id;
if (temperatureEntityId && hass.states[temperatureEntityId]) {
areaCards.push({
...computeTileCard(temperatureEntityId),
name:
hass.localize("component.sensor.entity_component.temperature.name") ||
"Temperature",
features: [{ type: "trend-graph" }],
});
if (temperatureEntityId && areaSensors.has(temperatureEntityId)) {
areaCards.push(computeCard(temperatureEntityId));
}
const humidityEntityId = area.humidity_entity_id;
if (humidityEntityId && hass.states[humidityEntityId]) {
areaCards.push({
...computeTileCard(humidityEntityId),
name:
hass.localize("component.sensor.entity_component.humidity.name") ||
"Humidity",
features: [{ type: "trend-graph" }],
});
if (humidityEntityId && areaSensors.has(humidityEntityId)) {
areaCards.push(computeCard(humidityEntityId));
}
// Add other climate entities
@@ -124,18 +131,7 @@ const processAreasForClimate = (
continue;
}
const state = hass.states[entityId];
if (
state?.attributes.device_class === "temperature" ||
state?.attributes.device_class === "humidity"
) {
areaCards.push({
...computeTileCard(entityId),
features: [{ type: "trend-graph" }],
});
} else {
areaCards.push(computeTileCard(entityId));
}
areaCards.push(computeCard(entityId));
}
if (areaCards.length > 0) {
@@ -159,7 +155,7 @@ const processAreasForClimate = (
const processUnassignedEntities = (
hass: HomeAssistant,
entities: string[]
{ entities, computeCard }: ClimateCardOptions
): LovelaceCardConfig[] => {
const unassignedFilter = generateEntityFilter(
hass.states,
@@ -173,10 +169,9 @@ const processUnassignedEntities = (
);
const unassignedEntities = entities.filter(unassignedFilter);
const areaCards: LovelaceCardConfig[] = [];
const computeTileCard = computeAreaTileCardConfig(hass, true);
for (const entityId of unassignedEntities) {
areaCards.push(computeTileCard(entityId));
areaCards.push(computeCard(entityId));
}
return areaCards;
@@ -184,9 +179,18 @@ const processUnassignedEntities = (
@customElement("climate-view-strategy")
export class ClimateViewStrategy extends ReactiveElement {
static registryDependencies: readonly LovelaceStrategyDependency[] = [
"entities",
"devices",
"areas",
"floors",
"panels",
];
static async generate(
_config: ClimateViewStrategyConfig,
hass: HomeAssistant
config: ClimateViewStrategyConfig,
hass: HomeAssistant,
options?: LovelaceStrategyGenerateOptions
): Promise<LovelaceViewConfig> {
const areas = Object.values(hass.areas);
const floors = Object.values(hass.floors);
@@ -194,20 +198,35 @@ export class ClimateViewStrategy extends ReactiveElement {
const sections: LovelaceSectionRawConfig[] = [];
const allEntities = Object.keys(hass.states);
const entities = findClimateEntities(hass, config.hidden);
const climateFilters = climateEntityFilters.map((filter) =>
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
filter
)
);
const entities = findEntities(allEntities, climateFilters);
const areaSensors = findClimateAreaSensors(hass, config.hidden);
const computeTileCard = computeAreaTileCardConfig(hass, true);
const computeClimateCard = (entityId: string): LovelaceCardConfig => {
const tileCard = computeTileCard(entityId);
const areaSensor = areaSensors.get(entityId);
if (!areaSensor) {
return tileCard;
}
return {
...tileCard,
name:
hass.localize(
`component.sensor.entity_component.${areaSensor}.name`
) || undefined,
features: [{ type: "trend-graph" }],
};
};
const cardOptions: ClimateCardOptions = {
entities,
areaSensors,
computeCard: options?.editMode
? (entityId) => ({
...computeClimateCard(entityId),
metadata: { id: entityId, hideable: true },
})
: computeClimateCard,
};
const floorCount =
hierarchy.floors.length + (hierarchy.areas.length ? 1 : 0);
@@ -233,7 +252,7 @@ export class ClimateViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForClimate(areaIds, hass, entities);
const areaCards = processAreasForClimate(areaIds, hass, cardOptions);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -257,7 +276,11 @@ export class ClimateViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForClimate(hierarchy.areas, hass, entities);
const areaCards = processAreasForClimate(
hierarchy.areas,
hass,
cardOptions
);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -266,7 +289,7 @@ export class ClimateViewStrategy extends ReactiveElement {
}
// Process unassigned entities
const unassignedCards = processUnassignedEntities(hass, entities);
const unassignedCards = processUnassignedEntities(hass, cardOptions);
if (unassignedCards.length > 0) {
const section: LovelaceSectionRawConfig = {
@@ -0,0 +1,269 @@
import { mdiPencil } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { property, state } from "lit/decorators";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { deepEqual } from "../../common/util/deep-equal";
import "../../components/ha-button";
import "../../components/ha-icon-button";
import "../../components/ha-top-app-bar-fixed";
import {
fetchFrontendSystemDataAfterSaves,
queueFrontendSystemDataSave,
type HomeSummaryPanelSystemDataKey,
} from "../../data/frontend";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { showToast } from "../../util/toast";
import type { Lovelace } from "../lovelace/types";
import "../lovelace/views/hui-view";
import "../lovelace/views/hui-view-background";
import "../lovelace/views/hui-view-container";
export abstract class HaHomeSummaryPanelBase<
K extends HomeSummaryPanelSystemDataKey,
> extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean, reflect: true }) public narrow = false;
@state() private _lovelace?: Lovelace;
@state() private _config?: FrontendSystemData[K];
@state() private _editMode = false;
@state() private _searchParams = new URLSearchParams(window.location.search);
protected abstract readonly _systemDataKey: K;
private _childPanelReady?: ChildPanelReady;
private _loadConfigPromise?: Promise<void>;
private _loadConfigRevision = 0;
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
if (!this.hasUpdated) {
this._setup();
return;
}
if (!changedProps.has("hass")) {
return;
}
const oldHass = changedProps.get("hass") as this["hass"];
if (
oldHass &&
this.hass.config.state === "RUNNING" &&
oldHass.config.state !== "RUNNING"
) {
this._setup();
}
}
private async _setup() {
this._loadConfigPromise = this._loadConfig();
await Promise.all([
this.hass.loadFragmentTranslation("lovelace"),
this._loadConfigPromise,
]);
this._setLovelace();
}
private async _loadConfig() {
const revision = ++this._loadConfigRevision;
this._config = undefined;
try {
const data = await fetchFrontendSystemDataAfterSaves(
this.hass.connection,
this._systemDataKey
);
if (revision !== this._loadConfigRevision) {
return;
}
this._config = data || ({} as FrontendSystemData[K]);
} catch (err) {
if (revision !== this._loadConfigRevision) {
return;
}
this._editMode = false;
const key: HomeSummaryPanelSystemDataKey = this._systemDataKey;
// eslint-disable-next-line no-console
console.error(`Failed to load ${key} configuration:`, err);
showToast(this, {
message: this.hass.localize(`ui.panel.${key}.editor.load_failed`),
duration: 0,
dismissable: true,
});
}
}
protected render() {
const key: HomeSummaryPanelSystemDataKey = this._systemDataKey;
return html`
<ha-top-app-bar-fixed
.narrow=${this.narrow}
.backButton=${this._searchParams.has("historyBack")}
>
<div slot="title">${this.hass.localize(`panel.${key}`)}</div>
${
!this.hass.user?.is_admin
? nothing
: this._editMode
? html`<ha-button
slot="actionItems"
appearance="filled"
size="s"
@click=${this._exitEditMode}
>
${this.hass.localize("ui.panel.lovelace.menu.exit_edit_mode")}
</ha-button>`
: this._config
? html`<ha-icon-button
slot="actionItems"
.path=${mdiPencil}
.label=${this.hass.localize(`ui.panel.${key}.editor.title`)}
@click=${this._enterEditMode}
></ha-icon-button>`
: nothing
}
${
this._lovelace
? html`
<hui-view-container .hass=${this.hass}>
<hui-view-background .hass=${this.hass}>
</hui-view-background>
<hui-view
.hass=${this.hass}
.narrow=${this.narrow}
.lovelace=${this._lovelace}
.index=${0}
@item-visibility-changed=${this._visibilityChanged}
></hui-view>
</hui-view-container>
`
: nothing
}
</ha-top-app-bar-fixed>
`;
}
private async _setLovelace() {
if (this._loadConfigPromise) {
await this._loadConfigPromise;
}
const view: LovelaceStrategyViewConfig = {
strategy: {
type: this._systemDataKey,
hidden: this._editMode ? undefined : this._config?.hidden,
},
};
const config =
this._lovelace && deepEqual(view, this._lovelace.config.views[0])
? this._lovelace.config
: { views: [view] };
this._childPanelReady ??= new ChildPanelReady(this);
this._lovelace = {
config,
rawConfig: config,
editMode: this._editMode,
hiddenIds: this._config?.hidden,
strategyEditSupport: true,
urlPath: this._systemDataKey,
mode: "generated",
locale: this.hass.locale,
enableFullEditMode: () => undefined,
saveConfig: async () => undefined,
deleteConfig: async () => undefined,
setEditMode: this._setEditMode,
showToast: () => undefined,
};
}
private _setEditMode = (editMode: boolean) => {
this._editMode = editMode;
if (!editMode && !this._config) {
this._loadConfigPromise = this._loadConfig();
}
this._setLovelace();
};
private _enterEditMode = () => {
this._setEditMode(true);
};
private _exitEditMode = () => {
this._setEditMode(false);
};
private _visibilityChanged = (
ev: HASSDomEvent<HASSDomEvents["item-visibility-changed"]>
) => {
if (!this._config) {
return;
}
const { id, hidden } = ev.detail;
const hiddenIds = (this._config.hidden ?? []).filter(
(hiddenId) => hiddenId !== id
);
if (hidden) {
hiddenIds.push(id);
}
this._saveConfig({
...this._config,
hidden: hiddenIds.length ? hiddenIds : undefined,
});
this._setLovelace();
};
private _saveConfig(config: FrontendSystemData[K]): Promise<void> {
this._config = config;
const key: HomeSummaryPanelSystemDataKey = this._systemDataKey;
return queueFrontendSystemDataSave(
this.hass.connection,
this._systemDataKey,
config
).catch(async (err) => {
// eslint-disable-next-line no-console
console.error(`Failed to save ${key} configuration:`, err);
showToast(this, {
message: this.hass.localize(`ui.panel.${key}.editor.save_failed`),
duration: 0,
dismissable: true,
});
if (config !== this._config) {
return;
}
await this._loadConfig();
await this._setLovelace();
});
}
static get styles(): CSSResultGroup {
return [
haStyle,
css`
:host {
user-select: none;
}
hui-view-container {
position: relative;
display: flex;
min-height: 100%;
box-sizing: border-box;
}
hui-view {
flex: 1 1 100%;
max-width: 100%;
}
`,
];
}
}
+117 -6
View File
@@ -16,7 +16,10 @@ import {
fetchFrontendSystemData,
saveFrontendSystemData,
subscribeFrontendSystemData,
type ClimateFrontendSystemData,
type HomeFrontendSystemData,
type LightFrontendSystemData,
type MaintenanceFrontendSystemData,
type SecurityFrontendSystemData,
} from "../../data/frontend";
import type { LovelaceDashboardStrategyConfig } from "../../data/lovelace/config/types";
@@ -54,6 +57,12 @@ class PanelHome extends SubscribeMixin(LitElement) {
@state() private _securityConfig: SecurityFrontendSystemData = {};
@state() private _maintenanceConfig: MaintenanceFrontendSystemData = {};
@state() private _climateConfig: ClimateFrontendSystemData = {};
@state() private _lightConfig: LightFrontendSystemData = {};
@state() private _extraActionItems?: ExtraActionItem[];
@query(".banner") private _banner?: HTMLElement;
@@ -62,6 +71,12 @@ class PanelHome extends SubscribeMixin(LitElement) {
private _securityConfigRevision = 0;
private _maintenanceConfigRevision = 0;
private _climateConfigRevision = 0;
private _lightConfigRevision = 0;
public hassSubscribe() {
return [
subscribeFrontendSystemData(
@@ -79,6 +94,51 @@ class PanelHome extends SubscribeMixin(LitElement) {
}
}
),
subscribeFrontendSystemData(
this.hass.connection,
"maintenance",
({ value }) => {
this._maintenanceConfigRevision++;
const config = value || {};
if (deepEqual(config, this._maintenanceConfig)) {
return;
}
this._maintenanceConfig = config;
if (this.hasUpdated) {
this._setLovelace();
}
}
),
subscribeFrontendSystemData(
this.hass.connection,
"climate",
({ value }) => {
this._climateConfigRevision++;
const config = value || {};
if (deepEqual(config, this._climateConfig)) {
return;
}
this._climateConfig = config;
if (this.hasUpdated) {
this._setLovelace();
}
}
),
subscribeFrontendSystemData(
this.hass.connection,
"light",
({ value }) => {
this._lightConfigRevision++;
const config = value || {};
if (deepEqual(config, this._lightConfig)) {
return;
}
this._lightConfig = config;
if (this.hasUpdated) {
this._setLovelace();
}
}
),
];
}
@@ -179,12 +239,24 @@ class PanelHome extends SubscribeMixin(LitElement) {
private async _loadConfig() {
const securityConfigRevision = this._securityConfigRevision;
const [translationsResult, homeResult, securityResult] =
await Promise.allSettled([
this.hass.loadFragmentTranslation("lovelace"),
fetchFrontendSystemData(this.hass.connection, "home"),
fetchFrontendSystemData(this.hass.connection, "security"),
]);
const maintenanceConfigRevision = this._maintenanceConfigRevision;
const climateConfigRevision = this._climateConfigRevision;
const lightConfigRevision = this._lightConfigRevision;
const [
translationsResult,
homeResult,
securityResult,
maintenanceResult,
climateResult,
lightResult,
] = await Promise.allSettled([
this.hass.loadFragmentTranslation("lovelace"),
fetchFrontendSystemData(this.hass.connection, "home"),
fetchFrontendSystemData(this.hass.connection, "security"),
fetchFrontendSystemData(this.hass.connection, "maintenance"),
fetchFrontendSystemData(this.hass.connection, "climate"),
fetchFrontendSystemData(this.hass.connection, "light"),
]);
if (translationsResult.status === "rejected") {
// eslint-disable-next-line no-console
@@ -214,6 +286,42 @@ class PanelHome extends SubscribeMixin(LitElement) {
} else if (securityConfigRevision === this._securityConfigRevision) {
this._securityConfig = securityResult.value || {};
}
if (maintenanceResult.status === "rejected") {
// eslint-disable-next-line no-console
console.error(
"Failed to load maintenance configuration:",
maintenanceResult.reason
);
if (maintenanceConfigRevision === this._maintenanceConfigRevision) {
this._maintenanceConfig = {};
}
} else if (maintenanceConfigRevision === this._maintenanceConfigRevision) {
this._maintenanceConfig = maintenanceResult.value || {};
}
if (climateResult.status === "rejected") {
// eslint-disable-next-line no-console
console.error(
"Failed to load climate configuration:",
climateResult.reason
);
if (climateConfigRevision === this._climateConfigRevision) {
this._climateConfig = {};
}
} else if (climateConfigRevision === this._climateConfigRevision) {
this._climateConfig = climateResult.value || {};
}
if (lightResult.status === "rejected") {
// eslint-disable-next-line no-console
console.error("Failed to load light configuration:", lightResult.reason);
if (lightConfigRevision === this._lightConfigRevision) {
this._lightConfig = {};
}
} else if (lightConfigRevision === this._lightConfigRevision) {
this._lightConfig = lightResult.value || {};
}
}
private _debounceRegenerateStrategy = debounce(
@@ -400,6 +508,9 @@ class PanelHome extends SubscribeMixin(LitElement) {
strategy: {
type: "home",
alert_entities: this._securityConfig.alert_entities,
maintenance_hidden_entities: this._maintenanceConfig.hidden,
climate_hidden_entities: this._climateConfig.hidden,
light_hidden_entities: this._lightConfig.hidden,
favorite_entities: this._config?.favorite_entities,
home_panel: true,
hide_welcome_message: this._config?.hide_welcome_message,
+4 -166
View File
@@ -1,171 +1,9 @@
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { debounce } from "../../common/util/debounce";
import { deepEqual } from "../../common/util/deep-equal";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { generateLovelaceViewStrategy } from "../lovelace/strategies/get-strategy";
import type { Lovelace } from "../lovelace/types";
import "../lovelace/views/hui-view";
import "../lovelace/views/hui-view-container";
import "../lovelace/views/hui-view-background";
import "../../components/ha-top-app-bar-fixed";
const LIGHT_LOVELACE_VIEW_CONFIG: LovelaceStrategyViewConfig = {
strategy: {
type: "light",
},
};
import { customElement } from "lit/decorators";
import { HaHomeSummaryPanelBase } from "../home/ha-home-summary-panel-base";
@customElement("ha-panel-light")
class PanelLight extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean, reflect: true }) public narrow = false;
@state() private _viewIndex = 0;
@state() private _lovelace?: Lovelace;
@state() private _searchParms = new URLSearchParams(window.location.search);
private _childPanelReady?: ChildPanelReady;
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
// Initial setup
if (!this.hasUpdated) {
this._setup();
return;
}
if (!changedProps.has("hass")) {
return;
}
const oldHass = changedProps.get("hass") as this["hass"];
if (oldHass && oldHass.localize !== this.hass.localize) {
this._setLovelace();
return;
}
if (oldHass && this.hass) {
// If the entity registry changed, ask the user if they want to refresh the config
if (
oldHass.entities !== this.hass.entities ||
oldHass.devices !== this.hass.devices ||
oldHass.areas !== this.hass.areas ||
oldHass.floors !== this.hass.floors ||
oldHass.panels !== this.hass.panels
) {
if (this.hass.config.state === "RUNNING") {
this._debounceRegistriesChanged();
return;
}
}
// If ha started, refresh the config
if (
this.hass.config.state === "RUNNING" &&
oldHass.config.state !== "RUNNING"
) {
this._setLovelace();
}
}
}
private async _setup() {
await this.hass.loadFragmentTranslation("lovelace");
this._setLovelace();
}
private _debounceRegistriesChanged = debounce(
() => this._registriesChanged(),
200
);
private _registriesChanged = async () => {
this._setLovelace();
};
protected render() {
return html`
<ha-top-app-bar-fixed
.narrow=${this.narrow}
.backButton=${this._searchParms.has("historyBack")}
>
<div slot="title">${this.hass.localize("panel.light")}</div>
${
this._lovelace
? html`
<hui-view-container .hass=${this.hass}>
<hui-view-background .hass=${this.hass}>
</hui-view-background>
<hui-view
.hass=${this.hass}
.narrow=${this.narrow}
.lovelace=${this._lovelace}
.index=${this._viewIndex}
></hui-view
></hui-view-container>
`
: nothing
}
</ha-top-app-bar-fixed>
`;
}
private async _setLovelace() {
const viewConfig = await generateLovelaceViewStrategy(
LIGHT_LOVELACE_VIEW_CONFIG,
this.hass
);
const config = { views: [viewConfig] };
const rawConfig = { views: [LIGHT_LOVELACE_VIEW_CONFIG] };
if (deepEqual(config, this._lovelace?.config)) {
return;
}
this._childPanelReady ??= new ChildPanelReady(this);
this._lovelace = {
config: config,
rawConfig: rawConfig,
editMode: false,
urlPath: "light",
mode: "generated",
locale: this.hass.locale,
enableFullEditMode: () => undefined,
saveConfig: async () => undefined,
deleteConfig: async () => undefined,
setEditMode: () => undefined,
showToast: () => undefined,
};
}
static get styles(): CSSResultGroup {
return [
haStyle,
css`
:host {
user-select: none;
}
hui-view-container {
position: relative;
display: flex;
min-height: 100vh;
box-sizing: border-box;
}
hui-view {
flex: 1 1 100%;
max-width: 100%;
}
`,
];
}
class PanelLight extends HaHomeSummaryPanelBase<"light"> {
protected readonly _systemDataKey = "light";
}
declare global {
+144 -131
View File
@@ -2,9 +2,10 @@ import { ReactiveElement } from "lit";
import { customElement } from "lit/decorators";
import { getAreasFloorHierarchy } from "../../../common/areas/areas-floor-hierarchy";
import {
findEntities,
findFilteredEntities,
generateEntityFilter,
type EntityFilter,
type EntityFilterSources,
} from "../../../common/entity/entity_filter";
import { floorDefaultIcon } from "../../../components/ha-floor-icon";
import type { LovelaceCardConfig } from "../../../data/lovelace/config/card";
@@ -17,20 +18,36 @@ import {
SMALL_SCREEN_CONDITION,
} from "../../lovelace/strategies/helpers/view-columns-conditions";
import type { ToggleGroupCardConfig } from "../../lovelace/cards/types";
import type {
LovelaceStrategyDependency,
LovelaceStrategyGenerateOptions,
} from "../../lovelace/strategies/types";
import type { ButtonHeadingBadgeConfig } from "../../lovelace/heading-badges/types";
export interface LightViewStrategyConfig {
type: "light";
hidden?: string[];
}
export const lightEntityFilters: EntityFilter[] = [
{ domain: "light", entity_category: "none" },
];
export const findLightEntities = (
sources: EntityFilterSources,
hiddenEntities?: string[]
): string[] =>
findFilteredEntities(sources, lightEntityFilters, hiddenEntities);
interface LightCardOptions {
entities: string[];
computeCard: (entityId: string) => LovelaceCardConfig;
}
const processAreasForLight = (
areaIds: string[],
hass: HomeAssistant,
entities: string[]
{ entities, computeCard }: LightCardOptions
): LovelaceCardConfig[] => {
const cards: LovelaceCardConfig[] = [];
@@ -49,114 +66,109 @@ const processAreasForLight = (
}
);
const areaLights = entities.filter(areaFilter);
const areaCards: LovelaceCardConfig[] = [];
const areaCards = areaLights.map(computeCard);
const computeTileCard = computeAreaTileCardConfig(hass, false);
for (const entityId of areaLights) {
areaCards.push(computeTileCard(entityId));
if (areaCards.length === 0) {
continue;
}
if (areaCards.length > 0) {
// Visibility condition: any light is on
const anyOnCondition = {
condition: "or" as const,
conditions: areaLights.map((entityId) => ({
condition: "state" as const,
entity: entityId,
state: "on",
})),
};
const heading: LovelaceCardConfig = {
heading_style: "subtitle",
type: "heading",
heading: area.name,
tap_action: hass.panels.home
? {
action: "navigate",
navigation_path: `/home/areas-${area.area_id}`,
}
: undefined,
};
cards.push({
heading_style: "subtitle",
type: "heading",
heading: area.name,
tap_action: hass.panels.home
? {
action: "navigate",
navigation_path: `/home/areas-${area.area_id}`,
}
: undefined,
badges: [
// Toggle buttons for mobile
{
type: "button",
icon: "mdi:power",
text: hass.localize("ui.panel.lovelace.strategy.light.off"),
label: hass.localize(
"ui.panel.lovelace.strategy.light.turn_on_area",
{ area: area.name }
),
tap_action: {
action: "perform-action",
perform_action: "light.turn_on",
target: {
area_id: area.area_id,
},
// Visibility condition: any light is on
const anyOnCondition = {
condition: "or" as const,
conditions: areaLights.map((entityId) => ({
condition: "state" as const,
entity: entityId,
state: "on",
})),
};
const target = { entity_id: areaLights };
cards.push({
...heading,
badges: [
// Toggle buttons for mobile
{
type: "button",
icon: "mdi:power",
text: hass.localize("ui.panel.lovelace.strategy.light.off"),
label: hass.localize(
"ui.panel.lovelace.strategy.light.turn_on_area",
{ area: area.name }
),
tap_action: {
action: "perform-action",
perform_action: "light.turn_on",
target,
},
visibility: [
SMALL_SCREEN_CONDITION,
{
condition: "not",
conditions: [anyOnCondition],
},
visibility: [
SMALL_SCREEN_CONDITION,
{
condition: "not",
conditions: [anyOnCondition],
},
],
} satisfies ButtonHeadingBadgeConfig,
{
type: "button",
icon: "mdi:power",
color: "orange",
text: hass.localize("ui.panel.lovelace.strategy.light.on"),
label: hass.localize(
"ui.panel.lovelace.strategy.light.turn_off_area",
{ area: area.name }
),
tap_action: {
action: "perform-action",
perform_action: "light.turn_off",
target: {
area_id: area.area_id,
},
},
visibility: [SMALL_SCREEN_CONDITION, anyOnCondition],
} satisfies ButtonHeadingBadgeConfig,
] satisfies LovelaceCardConfig[],
});
],
} satisfies ButtonHeadingBadgeConfig,
{
type: "button",
icon: "mdi:power",
color: "orange",
text: hass.localize("ui.panel.lovelace.strategy.light.on"),
label: hass.localize(
"ui.panel.lovelace.strategy.light.turn_off_area",
{ area: area.name }
),
tap_action: {
action: "perform-action",
perform_action: "light.turn_off",
target,
},
visibility: [SMALL_SCREEN_CONDITION, anyOnCondition],
} satisfies ButtonHeadingBadgeConfig,
] satisfies LovelaceCardConfig[],
});
// Toggle group card for desktop
cards.push({
type: "toggle-group",
color: "amber",
entities: areaLights,
visibility: [LARGE_SCREEN_CONDITION],
grid_options: {
columns: 6,
rows: 1,
},
} as ToggleGroupCardConfig);
// Toggle group card for desktop
cards.push({
type: "toggle-group",
color: "amber",
entities: areaLights,
visibility: [LARGE_SCREEN_CONDITION],
grid_options: {
columns: 6,
rows: 1,
},
} as ToggleGroupCardConfig);
areaCards.forEach((card) => {
// Insert a blank card before every 3rd card to align the individual
// cards with the toggle group card on desktop
if (
areaCards.indexOf(card) % 3 === 0 &&
areaCards.indexOf(card) !== 0
) {
cards.push({
type: "vertical-stack",
cards: [],
visibility: [LARGE_SCREEN_CONDITION],
grid_options: {
columns: 6,
rows: 1,
},
});
}
areaCards.forEach((card) => {
// Insert a blank card before every 3rd card to align the individual
// cards with the toggle group card on desktop
if (areaCards.indexOf(card) % 3 === 0 && areaCards.indexOf(card) !== 0) {
cards.push({
type: "vertical-stack",
cards: [],
visibility: [LARGE_SCREEN_CONDITION],
grid_options: {
columns: 6,
rows: 1,
},
});
}
cards.push(card);
});
}
cards.push(card);
});
}
return cards;
@@ -164,7 +176,7 @@ const processAreasForLight = (
const processUnassignedLights = (
hass: HomeAssistant,
entities: string[]
{ entities, computeCard }: LightCardOptions
): LovelaceCardConfig[] => {
const unassignedFilter = generateEntityFilter(
hass.states,
@@ -176,22 +188,23 @@ const processUnassignedLights = (
area: null,
}
);
const unassignedLights = entities.filter(unassignedFilter);
const areaCards: LovelaceCardConfig[] = [];
const computeTileCard = computeAreaTileCardConfig(hass, false);
for (const entityId of unassignedLights) {
areaCards.push(computeTileCard(entityId));
}
return areaCards;
return entities.filter(unassignedFilter).map(computeCard);
};
@customElement("light-view-strategy")
export class LightViewStrategy extends ReactiveElement {
static registryDependencies: readonly LovelaceStrategyDependency[] = [
"entities",
"devices",
"areas",
"floors",
"panels",
];
static async generate(
_config: LightViewStrategyConfig,
hass: HomeAssistant
config: LightViewStrategyConfig,
hass: HomeAssistant,
options?: LovelaceStrategyGenerateOptions
): Promise<LovelaceViewConfig> {
const areas = Object.values(hass.areas);
const floors = Object.values(hass.floors);
@@ -199,20 +212,16 @@ export class LightViewStrategy extends ReactiveElement {
const sections: LovelaceSectionRawConfig[] = [];
const allEntities = Object.keys(hass.states);
const lightFilters = lightEntityFilters.map((filter) =>
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
filter
)
);
const entities = findEntities(allEntities, lightFilters);
const computeTileCard = computeAreaTileCardConfig(hass, false);
const cardOptions: LightCardOptions = {
entities: findLightEntities(hass, config.hidden),
computeCard: options?.editMode
? (entityId) => ({
...computeTileCard(entityId),
metadata: { id: entityId, hideable: true },
})
: computeTileCard,
};
const floorCount =
hierarchy.floors.length + (hierarchy.areas.length ? 1 : 0);
@@ -238,7 +247,7 @@ export class LightViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForLight(areaIds, hass, entities);
const areaCards = processAreasForLight(areaIds, hass, cardOptions);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -262,7 +271,11 @@ export class LightViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForLight(hierarchy.areas, hass, entities);
const areaCards = processAreasForLight(
hierarchy.areas,
hass,
cardOptions
);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -271,7 +284,7 @@ export class LightViewStrategy extends ReactiveElement {
}
// Process unassigned lights
const unassignedCards = processUnassignedLights(hass, entities);
const unassignedCards = processUnassignedLights(hass, cardOptions);
if (unassignedCards.length > 0) {
const section: LovelaceSectionRawConfig = {
type: "grid",
@@ -29,6 +29,8 @@ const BADGE_SORTABLE_OPTIONS: HaSortableOptions = {
export class HuiViewBadges extends LitElement {
@property({ attribute: false }) public lovelace!: Lovelace;
@property({ attribute: false }) public editMode = false;
@property({ attribute: false }) public badges: HuiBadge[] = [];
@property({ attribute: false }) public path!: ConfigPath;
@@ -46,7 +48,7 @@ export class HuiViewBadges extends LitElement {
private _checkAllHidden() {
const allHidden =
!this.lovelace.editMode && this.badges.every((section) => section.hidden);
!this.editMode && this.badges.every((section) => section.hidden);
this.toggleAttribute("hidden", allHidden);
}
@@ -71,7 +73,7 @@ export class HuiViewBadges extends LitElement {
}
willUpdate(changedProperties: PropertyValues<this>): void {
if (changedProperties.has("badges") || changedProperties.has("lovelace")) {
if (changedProperties.has("badges") || changedProperties.has("editMode")) {
this._checkAllHidden();
}
}
@@ -125,7 +127,7 @@ export class HuiViewBadges extends LitElement {
render() {
if (!this.lovelace) return nothing;
const editMode = this.lovelace.editMode;
const editMode = this.editMode;
const badges = this.badges;
@@ -58,6 +58,7 @@ import {
isSecurityAlertActive,
resolveSecurityAlertSeverity,
} from "../../security/strategies/security-alerts";
import { findLightEntities } from "../../light/strategies/light-view-strategy";
import { findSecurityEntities } from "../../security/strategies/security-view-strategy";
import type { LovelaceCard, LovelaceGridOptions } from "../types";
import { tileCardStyle } from "./tile/tile-card-style";
@@ -173,12 +174,11 @@ export class HuiHomeSummaryCard extends LitElement implements LovelaceCard {
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),
findLightEntities(
{ states, entities, devices, areas, floors },
this._config.hidden_entities
),
states
);
@@ -195,12 +195,16 @@ export class HuiHomeSummaryCard extends LitElement implements LovelaceCard {
}
case "climate": {
// Min/Max temperature of the areas
const hiddenEntities = new Set(this._config.hidden_entities);
const areaSensors = Object.values(areas)
.map((area) => area.temperature_entity_id)
.filter(Boolean);
.filter(
(entityId): entityId is string =>
!!entityId && !hiddenEntities.has(entityId)
);
const sensorsValues = areaSensors
.map((entityId) => parseFloat(states[entityId!]?.state) || NaN)
.map((entityId) => parseFloat(states[entityId]?.state) || NaN)
.filter((value) => !isNaN(value));
if (sensorsValues.length === 0) {
@@ -326,13 +330,10 @@ 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 = findMaintenanceEntities(
{ states, entities, devices, areas, floors },
this._config.hidden_entities
);
const lowBatteryEntities = filterLowBatteryEntities(
states,
+1
View File
@@ -768,6 +768,7 @@ export interface HeadingCardConfig extends LovelaceCardConfig {
export interface HomeSummaryCard extends LovelaceCardConfig {
summary: HomeSummary;
alert_entities?: SecurityAlertEntityConfig[];
hidden_entities?: string[];
vertical?: boolean;
tap_action?: ActionConfig;
hold_action?: ActionConfig;
@@ -0,0 +1,127 @@
import { mdiEye, mdiEyeOff } from "@mdi/js";
import type { HassEntity } from "home-assistant-js-websocket";
import type { CSSResultGroup } from "lit";
import { LitElement, css, html } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-svg-icon";
import { formattersContext } from "../../../data/context";
import type { HomeAssistantFormatters } from "../../../types";
@customElement("hui-card-visibility-edit-mode")
export class HuiCardVisibilityEditMode extends LitElement {
@property({ attribute: false }) public itemId!: string;
@property({ type: Boolean, reflect: true, attribute: "item-hidden" })
public itemHidden = false;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@state()
@consumeEntityState({ entityIdPath: ["itemId"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: HomeAssistantFormatters;
protected render() {
const name = this._stateObj
? this._formatters.formatEntityName(this._stateObj)
: this.itemId;
return html`
<div class="card-wrapper" inert><slot></slot></div>
<button
class="control"
aria-label=${this._localize(
`ui.components.items-display-editor.${this.itemHidden ? "show" : "hide"}`,
{ label: name }
)}
@click=${this._toggle}
>
<ha-svg-icon
.path=${this.itemHidden ? mdiEyeOff : mdiEye}
></ha-svg-icon>
</button>
`;
}
private _toggle(): void {
fireEvent(this, "item-visibility-changed", {
id: this.itemId,
hidden: !this.itemHidden,
});
}
static styles: CSSResultGroup = css`
:host {
display: block;
position: relative;
height: 100%;
border-radius: var(--ha-card-border-radius, var(--ha-border-radius-lg));
}
.card-wrapper {
height: 100%;
}
:host([item-hidden]) .card-wrapper {
opacity: 0.8;
}
:host([item-hidden])::after {
content: "";
position: absolute;
inset: 0;
border: 2px dotted var(--secondary-text-color);
border-radius: inherit;
pointer-events: none;
}
.control {
position: absolute;
inset: 0;
z-index: 1;
display: flex;
align-items: flex-end;
justify-content: flex-end;
margin: 0;
padding: var(--ha-space-2);
border: none;
background: none;
border-radius: inherit;
cursor: pointer;
color: var(--primary-text-color);
}
.control:focus-visible {
outline: 2px solid var(--primary-color);
}
.control ha-svg-icon {
display: flex;
padding: var(--ha-space-1);
border-radius: var(--ha-border-radius-circle);
background: var(--secondary-background-color);
box-shadow: var(--ha-box-shadow-s);
--mdc-icon-size: 20px;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"hui-card-visibility-edit-mode": HuiCardVisibilityEditMode;
}
interface GlobalEventHandlersEventMap {
"item-visibility-changed": HASSDomEvent<
HASSDomEvents["item-visibility-changed"]
>;
}
interface HASSDomEvents {
"item-visibility-changed": { id: string; hidden: boolean };
}
}
@@ -18,8 +18,9 @@ import type { HomeAssistant } from "../../../types";
import type { HuiCard } from "../cards/hui-card";
import { computeCardGridSize } from "../common/compute-card-grid-size";
import "../components/hui-card-edit-mode";
import "../components/hui-card-visibility-edit-mode";
import { moveAtPath } from "../editor/lovelace-path";
import type { Lovelace } from "../types";
import { strategyEditMode, type Lovelace } from "../types";
const CARD_SORTABLE_OPTIONS: HaSortableOptions = {
delay: 100,
@@ -79,6 +80,8 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
const cardsConfig = this._config?.cards ?? [];
const editMode = Boolean(this.lovelace?.editMode && !this.isStrategy);
const generatedEditMode =
strategyEditMode(this.lovelace) && this.isStrategy;
const sortableOptions = this.importOnly
? IMPORT_MODE_CARD_SORTABLE_OPTIONS
@@ -104,7 +107,7 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
${repeat(
cardsConfig,
(cardConfig) => this._getKey(cardConfig),
(_cardConfig, idx) => {
(cardConfig, idx) => {
const card = this.cards![idx];
card.layout = "grid";
const gridOptions = card.getGridOptions();
@@ -126,6 +129,7 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
"full-width": columns === "full",
hidden: !editMode && card.hidden,
})}"
?inert=${generatedEditMode && !cardConfig.metadata?.hideable}
.sortableData=${cardPath}
>
${
@@ -141,7 +145,20 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
${card}
</hui-card-edit-mode>
`
: card
: generatedEditMode && cardConfig.metadata?.hideable
? html`
<hui-card-visibility-edit-mode
.itemId=${cardConfig.metadata.id}
.itemHidden=${Boolean(
this.lovelace?.hiddenIds?.includes(
cardConfig.metadata.id
)
)}
>
${card}
</hui-card-visibility-edit-mode>
`
: card
}
</div>
`;
@@ -25,6 +25,7 @@ import type {
LovelaceSectionStrategy,
LovelaceStrategy,
LovelaceStrategyDependency,
LovelaceStrategyGenerateOptions,
LovelaceViewStrategy,
} from "./types";
@@ -157,7 +158,8 @@ const generateStrategy = async <T extends LovelaceStrategyConfigType>(
configType: T,
renderError: (err: string | Error) => StrategyConfig<T>,
strategyConfig: LovelaceStrategyConfig,
hass: HomeAssistant
hass: HomeAssistant,
options?: LovelaceStrategyGenerateOptions
): Promise<StrategyConfig<T>> => {
const strategyType = strategyConfig.type;
if (!strategyType) {
@@ -187,7 +189,7 @@ const generateStrategy = async <T extends LovelaceStrategyConfigType>(
const config = cleanLegacyStrategyConfig(strategyConfig);
return await strategy.generate(config, hass);
return await strategy.generate(config, hass, options);
} catch (err: any) {
if (err.message !== "timeout") {
// eslint-disable-next-line
@@ -229,7 +231,8 @@ export const generateLovelaceDashboardStrategy = async (
export const generateLovelaceViewStrategy = async (
config: LovelaceStrategyViewConfig,
hass: HomeAssistant
hass: HomeAssistant,
options?: LovelaceStrategyGenerateOptions
): Promise<LovelaceViewConfig> => {
const { strategy, ...base } = config;
const generated = await generateStrategy(
@@ -243,7 +246,8 @@ export const generateLovelaceViewStrategy = async (
],
}),
strategy,
hass
hass,
options
);
return {
...base,
@@ -3,6 +3,7 @@ import { customElement } from "lit/decorators";
import { computeDeviceName } from "../../../../common/entity/compute_device_name";
import { getEntityContext } from "../../../../common/entity/context/get_entity_context";
import {
excludeEntities,
findEntities,
generateEntityFilter,
} from "../../../../common/entity/entity_filter";
@@ -29,6 +30,8 @@ import {
export interface HomeAreaViewStrategyConfig {
type: "home-area";
area?: string;
climate_hidden_entities?: string[];
light_hidden_entities?: string[];
home_panel?: boolean;
}
@@ -91,7 +94,12 @@ export class HomeAreaViewStrategy extends ReactiveElement {
const allEntities = Object.keys(hass.states);
const areaEntities = allEntities.filter(areaFilter);
const entitiesBySummary = HOME_SUMMARIES.reduce(
const hiddenEntities: Partial<Record<HomeSummary, string[]>> = {
climate: config.climate_hidden_entities,
light: config.light_hidden_entities,
};
const summaryEntitiesBySummary = HOME_SUMMARIES.reduce(
(acc, summary) => {
const summariesFilters = HOME_SUMMARIES_FILTERS[summary];
const filterFunctions = summariesFilters.map((filter) =>
@@ -110,6 +118,17 @@ export class HomeAreaViewStrategy extends ReactiveElement {
{} as Record<HomeSummary, string[]>
);
const entitiesBySummary = HOME_SUMMARIES.reduce(
(acc, summary) => {
acc[summary] = excludeEntities(
summaryEntitiesBySummary[summary],
hiddenEntities[summary]
);
return acc;
},
{} as Record<HomeSummary, string[]>
);
const {
light,
climate,
@@ -152,9 +171,7 @@ export class HomeAreaViewStrategy extends ReactiveElement {
tap_action: {
action: "perform-action",
perform_action: "light.turn_on",
target: {
area_id: config.area,
},
target: { entity_id: light },
},
visibility: [
{
@@ -175,9 +192,7 @@ export class HomeAreaViewStrategy extends ReactiveElement {
tap_action: {
action: "perform-action",
perform_action: "light.turn_off",
target: {
area_id: config.area,
},
target: { entity_id: light },
},
visibility: [anyOnCondition],
} satisfies ButtonHeadingBadgeConfig,
@@ -247,7 +262,8 @@ export class HomeAreaViewStrategy extends ReactiveElement {
}
const deviceSections: LovelaceSectionRawConfig[] = [];
const { maintenance, ...partialEntitiesBySummary } = entitiesBySummary;
const { maintenance, ...partialEntitiesBySummary } =
summaryEntitiesBySummary;
const summaryEntities = Object.values(partialEntitiesBySummary).flat();
// Scenes section
@@ -21,6 +21,9 @@ import type { HomeOverviewViewStrategyConfig } from "./home-overview-view-strate
export interface HomeDashboardStrategyConfig {
type: "home";
alert_entities?: SecurityAlertEntityConfig[];
maintenance_hidden_entities?: string[];
climate_hidden_entities?: string[];
light_hidden_entities?: string[];
favorite_entities?: string[];
home_panel?: boolean;
hide_welcome_message?: boolean;
@@ -72,6 +75,8 @@ export class HomeDashboardStrategy extends ReactiveElement {
strategy: {
type: "home-area",
area: area.area_id,
climate_hidden_entities: config.climate_hidden_entities,
light_hidden_entities: config.light_hidden_entities,
home_panel: config.home_panel,
} satisfies HomeAreaViewStrategyConfig,
};
@@ -106,6 +111,9 @@ export class HomeDashboardStrategy extends ReactiveElement {
strategy: {
type: "home-overview",
alert_entities: config.alert_entities,
maintenance_hidden_entities: config.maintenance_hidden_entities,
climate_hidden_entities: config.climate_hidden_entities,
light_hidden_entities: config.light_hidden_entities,
favorite_entities: config.favorite_entities,
home_panel: config.home_panel,
hide_welcome_message: config.hide_welcome_message,
@@ -40,6 +40,7 @@ import {
computeFavoriteCardConfig,
computeFavoriteCardsSize,
} from "../helpers/favorite-cards";
import { findLightEntities } from "../../../light/strategies/light-view-strategy";
import { findMaintenanceEntities } from "../../../maintenance/strategies/maintenance-view-strategy";
import {
computeDefaultSecurityAlertVisibility,
@@ -60,6 +61,9 @@ import { OTHER_DEVICES_FILTERS } from "./helpers/other-devices-filters";
export interface HomeOverviewViewStrategyConfig {
type: "home-overview";
alert_entities?: SecurityAlertEntityConfig[];
maintenance_hidden_entities?: string[];
climate_hidden_entities?: string[];
light_hidden_entities?: string[];
favorite_entities?: string[];
home_panel?: boolean;
hide_welcome_message?: boolean;
@@ -351,26 +355,20 @@ export class HomeOverviewViewStrategy extends ReactiveElement {
)
);
const lightsFilters = HOME_SUMMARIES_FILTERS.light.map((filter) =>
generateEntityFilter(
hass.states,
hass.entities,
hass.devices,
hass.areas,
hass.floors,
filter
)
);
const hasLights =
hass.panels.light && findEntities(allEntities, lightsFilters).length > 0;
hass.panels.light &&
findLightEntities(hass, config.light_hidden_entities).length > 0;
const hasMediaPlayers =
findEntities(allEntities, mediaPlayerFilter).length > 0;
const hasClimate = hass.panels.climate && hasClimateEntities(hass);
const hasClimate =
hass.panels.climate &&
hasClimateEntities(hass, config.climate_hidden_entities);
const hasSecurity =
hass.panels.security && findSecurityEntities(hass).length > 0;
const hasMaintenance =
hass.panels.maintenance && findMaintenanceEntities(hass).length > 0;
hass.panels.maintenance &&
findMaintenanceEntities(hass, config.maintenance_hidden_entities).length >
0;
const alertEntities = config.alert_entities ?? [];
const alertSeverityEntities = filterSecurityAlertEntities(
@@ -418,6 +416,9 @@ export class HomeOverviewViewStrategy extends ReactiveElement {
? ({
type: "home-summary",
summary: "light",
hidden_entities: config.light_hidden_entities?.length
? config.light_hidden_entities
: undefined,
tap_action: {
action: "navigate",
navigation_path: "/light?historyBack=1",
@@ -429,6 +430,9 @@ export class HomeOverviewViewStrategy extends ReactiveElement {
? ({
type: "home-summary",
summary: "climate",
hidden_entities: config.climate_hidden_entities?.length
? config.climate_hidden_entities
: undefined,
tap_action: {
action: "navigate",
navigation_path: "/climate?historyBack=1",
@@ -468,6 +472,9 @@ export class HomeOverviewViewStrategy extends ReactiveElement {
? ({
type: "home-summary",
summary: "maintenance",
hidden_entities: config.maintenance_hidden_entities?.length
? config.maintenance_hidden_entities
: undefined,
tap_action: {
action: "navigate",
navigation_path: config.home_panel
+10 -1
View File
@@ -9,8 +9,17 @@ import type { LovelaceGenericElementEditor } from "../types";
export type LovelaceStrategyDependency =
"entities" | "devices" | "areas" | "floors" | "labels" | "panels";
export interface LovelaceStrategyGenerateOptions {
/** The result is shown in edit mode, so it may carry `metadata`. */
editMode?: boolean;
}
export interface LovelaceStrategy<T = any> {
generate(config: LovelaceStrategyConfig, hass: HomeAssistant): Promise<T>;
generate(
config: LovelaceStrategyConfig,
hass: HomeAssistant,
options?: LovelaceStrategyGenerateOptions
): Promise<T>;
shouldRegenerate?(
config: LovelaceStrategyConfig,
oldHass: HomeAssistant,
+13
View File
@@ -48,8 +48,21 @@ export interface Lovelace {
* window's history and scroll position.
*/
embedded?: boolean;
/**
* Ids of the generated items that are hidden. In edit mode they are still
* shown, with their visibility toggle off.
*/
hiddenIds?: string[];
/**
* The host applies the controls that generated items declare in their
* `metadata`, so strategies add it in edit mode.
*/
strategyEditSupport?: boolean;
}
export const strategyEditMode = (lovelace?: Lovelace): boolean =>
Boolean(lovelace?.editMode && lovelace.strategyEditSupport);
export interface LovelaceBadge extends HTMLElement {
hass?: HomeAssistant;
preview?: boolean;
@@ -88,6 +88,7 @@ export class MasonryView extends LitElement implements LovelaceViewElement {
<hui-view-badges
.badges=${this.badges}
.lovelace=${this.lovelace}
.editMode=${Boolean(this.lovelace?.editMode)}
.path=${[...this.path!, "badges"]}
show-add-label
></hui-view-badges>
@@ -191,7 +191,7 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
if (!this.lovelace) return nothing;
const sections = this.sections;
const editMode = this.lovelace.editMode;
const editMode = this.lovelace.editMode && !this.isStrategy;
const hasSidebar =
this._config?.sidebar && (this._sidebarVisible || editMode);
const singleColumn = this._maxColumns <= 1;
@@ -239,6 +239,7 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
.hass=${this.hass}
.badges=${this.badges}
.lovelace=${this.lovelace}
.editMode=${editMode}
.path=${this.path!}
.config=${this._config?.header}
></hui-view-header>
@@ -370,6 +371,7 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
.hass=${this.hass}
.badges=${this.badges}
.lovelace=${this.lovelace}
.editMode=${editMode}
.path=${this.path!}
.config=${this._config.sidebar}
@sidebar-visibility-changed=${
@@ -383,6 +385,7 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
<hui-view-footer
.hass=${this.hass}
.lovelace=${this.lovelace}
.editMode=${editMode}
.path=${this.path!}
.config=${this._config?.footer}
></hui-view-footer>
@@ -94,6 +94,7 @@ export class SideBarView extends LitElement implements LovelaceViewElement {
<hui-view-badges
.badges=${this.badges}
.lovelace=${this.lovelace}
.editMode=${Boolean(this.lovelace?.editMode)}
.path=${[...this.path!, "badges"]}
show-add-label
></hui-view-badges>
+12 -7
View File
@@ -26,6 +26,8 @@ export class HuiViewFooter extends LitElement {
@property({ attribute: false }) public lovelace!: Lovelace;
@property({ attribute: false }) public editMode = false;
@property({ attribute: false }) public card?: HuiCard;
@property({ attribute: false }) public config?: LovelaceViewFooterConfig;
@@ -52,12 +54,16 @@ export class HuiViewFooter extends LitElement {
if (changedProperties.has("hass")) {
this.card.hass = this.hass;
}
if (changedProperties.has("lovelace")) {
this.card.preview = this.lovelace.editMode;
if (changedProperties.has("editMode")) {
this.card.preview = this.editMode;
}
}
if (changedProperties.has("lovelace") || changedProperties.has("card")) {
if (
!this.hasUpdated ||
changedProperties.has("editMode") ||
changedProperties.has("card")
) {
this._checkHidden();
}
}
@@ -69,8 +75,7 @@ export class HuiViewFooter extends LitElement {
private _checkHidden() {
const hidden =
!this.lovelace?.editMode &&
(!this.card || this.card.hasAttribute("hidden"));
!this.editMode && (!this.card || this.card.hasAttribute("hidden"));
this.toggleAttribute("hidden", hidden);
this.toggleAttribute("sticky", Boolean(this.card));
}
@@ -78,7 +83,7 @@ export class HuiViewFooter extends LitElement {
private _createCardElement(cardConfig: LovelaceCardConfig) {
const element = document.createElement("hui-card");
element.hass = this.hass;
element.preview = this.lovelace.editMode;
element.preview = this.editMode;
element.layout = "grid";
element.config = cardConfig;
element.addEventListener("card-updated", (ev: Event) => {
@@ -150,7 +155,7 @@ export class HuiViewFooter extends LitElement {
render() {
if (!this.lovelace) return nothing;
const editMode = Boolean(this.lovelace?.editMode);
const editMode = this.editMode;
const card = this.card;
if (!editMode && !card) {
+11 -8
View File
@@ -33,6 +33,8 @@ export class HuiViewHeader extends LitElement {
@property({ attribute: false }) public lovelace!: Lovelace;
@property({ attribute: false }) public editMode = false;
@property({ attribute: false }) public card?: HuiCard;
@property({ attribute: false }) public badges: HuiBadge[] = [];
@@ -44,7 +46,7 @@ export class HuiViewHeader extends LitElement {
private _checkHidden() {
const allHidden =
!this.card &&
!this.lovelace.editMode &&
!this.editMode &&
this.badges.every((badges) => badges.hidden);
this.toggleAttribute("hidden", allHidden);
}
@@ -79,15 +81,15 @@ export class HuiViewHeader extends LitElement {
willUpdate(changedProperties: PropertyValues<this>): void {
if (
changedProperties.has("badges") ||
changedProperties.has("lovelace") ||
changedProperties.has("editMode") ||
changedProperties.has("card")
) {
this._checkHidden();
}
if (changedProperties.has("config") || changedProperties.has("lovelace")) {
if (changedProperties.has("config") || changedProperties.has("editMode")) {
this._dragScrollController.enabled =
!this.lovelace.editMode && this.config?.badges_wrap === "scroll";
!this.editMode && this.config?.badges_wrap === "scroll";
}
if (changedProperties.has("config")) {
@@ -104,8 +106,8 @@ export class HuiViewHeader extends LitElement {
if (changedProperties.has("hass")) {
this.card.hass = this.hass;
}
if (changedProperties.has("lovelace")) {
this.card.preview = this.lovelace.editMode;
if (changedProperties.has("editMode")) {
this.card.preview = this.editMode;
}
}
}
@@ -113,7 +115,7 @@ export class HuiViewHeader extends LitElement {
private _createCardElement(cardConfig: LovelaceCardConfig) {
const element = document.createElement("hui-card");
element.hass = this.hass;
element.preview = this.lovelace.editMode;
element.preview = this.editMode;
element.config = cardConfig;
element.load();
return element;
@@ -163,7 +165,7 @@ export class HuiViewHeader extends LitElement {
render() {
if (!this.lovelace) return nothing;
const editMode = Boolean(this.lovelace?.editMode);
const editMode = this.editMode;
const card = this.card;
@@ -254,6 +256,7 @@ export class HuiViewHeader extends LitElement {
<hui-view-badges
.badges=${this.badges}
.lovelace=${this.lovelace!}
.editMode=${this.editMode}
.path=${[...this.path, "badges"]}
.showAddLabel=${this.badges.length === 0}
></hui-view-badges>
@@ -25,6 +25,8 @@ export class HuiViewSidebar extends ConditionalListenerMixin<LovelaceViewSidebar
@property({ attribute: false }) public lovelace!: Lovelace;
@property({ attribute: false }) public editMode = false;
@property({ attribute: false }) public config?: LovelaceViewSidebarConfig;
@property({ attribute: false }) public path!: ConfigPath;
@@ -74,7 +76,7 @@ export class HuiViewSidebar extends ConditionalListenerMixin<LovelaceViewSidebar
<hui-section
.config=${section}
.hass=${this.hass}
.preview=${this.lovelace.editMode}
.preview=${this.editMode}
.path=${sectionPath}
></hui-section>
`;
+31 -9
View File
@@ -65,7 +65,7 @@ import {
checkStrategyShouldRegenerate,
generateLovelaceViewStrategy,
} from "../strategies/get-strategy";
import type { Lovelace } from "../types";
import { strategyEditMode, type Lovelace } from "../types";
import { PANEL_VIEW_LAYOUT, SIDEBAR_VIEW_LAYOUT } from "./const";
import { getViewType } from "./get-view-type";
@@ -119,6 +119,8 @@ export class HUIView extends ReactiveElement {
private _layoutElementType?: string;
private _initializeConfigRevision = 0;
private _layoutElement?: LovelaceViewElement;
private _config?: LovelaceViewConfig;
@@ -368,6 +370,14 @@ export class HUIView extends ReactiveElement {
};
}
private get _isStrategy(): boolean {
return isStrategyView(this.lovelace.config.views[this.index]);
}
private get _preview(): boolean {
return this.lovelace.editMode && !this._isStrategy;
}
private _getCardConfig(path: ConfigPath): LovelaceCardConfig | undefined {
if (isStrategyView(this.lovelace.config.views[this.index])) {
return undefined;
@@ -378,7 +388,7 @@ export class HUIView extends ReactiveElement {
private _createCardElement(cardConfig: LovelaceCardConfig) {
const element = document.createElement("hui-card");
element.hass = this.hass;
element.preview = this.lovelace.editMode;
element.preview = this._preview;
element.config = cardConfig;
element.addEventListener("card-updated", (ev: Event) => {
ev.stopPropagation();
@@ -391,7 +401,7 @@ export class HUIView extends ReactiveElement {
public createBadgeElement(badgeConfig: LovelaceBadgeConfig) {
const element = document.createElement("hui-badge");
element.hass = this.hass;
element.preview = this.lovelace.editMode;
element.preview = this._preview;
element.config = badgeConfig;
element.addEventListener("badge-updated", (ev: Event) => {
ev.stopPropagation();
@@ -406,8 +416,9 @@ export class HUIView extends ReactiveElement {
const element = document.createElement("hui-section");
element.hass = this.hass;
element.lovelace = this.lovelace;
element.insideStrategy = this._isStrategy;
element.config = sectionConfig;
element.preview = this.lovelace.editMode;
element.preview = this._preview;
element.addEventListener(
"ll-rebuild",
(ev: Event) => {
@@ -449,7 +460,9 @@ export class HUIView extends ReactiveElement {
(changedProperties.has("lovelace") &&
(!oldLovelace ||
this.lovelace.config.views[this.index] !==
oldLovelace.config.views[this.index]))
oldLovelace.config.views[this.index] ||
(this._isStrategy &&
strategyEditMode(this.lovelace) !== strategyEditMode(oldLovelace))))
) {
this._initializeConfig();
return;
@@ -465,6 +478,7 @@ export class HUIView extends ReactiveElement {
if (
this.hass.config.state === "RUNNING" &&
(oldHass.config.state !== "RUNNING" ||
oldHass.localize !== this.hass.localize ||
checkStrategyShouldRegenerate(
"view",
viewConfig.strategy,
@@ -516,16 +530,16 @@ export class HUIView extends ReactiveElement {
try {
element.hass = this.hass;
element.lovelace = this.lovelace;
element.preview = this.lovelace.editMode;
element.preview = this._preview;
} catch (e: any) {
this._rebuildSection(element, createErrorSectionConfig(e.message));
}
});
this._cards.forEach((element) => {
element.preview = this.lovelace.editMode;
element.preview = this._preview;
});
this._badges.forEach((element) => {
element.preview = this.lovelace.editMode;
element.preview = this._preview;
});
}
if (changedProperties.has("_cards")) {
@@ -543,7 +557,8 @@ export class HUIView extends ReactiveElement {
if (isStrategyView(config)) {
const strategyConfig = await generateLovelaceViewStrategy(
config,
this.hass!
this.hass!,
{ editMode: strategyEditMode(this.lovelace) }
);
const generatedConfig = normalizeViewConfig(strategyConfig);
return {
@@ -596,11 +611,18 @@ export class HUIView extends ReactiveElement {
}
private async _initializeConfig() {
const revision = ++this._initializeConfigRevision;
const rawConfig = this.lovelace.config.views[this.index];
const isStrategy = isStrategyView(rawConfig);
const viewConfig = await this._generateConfig(rawConfig);
if (this._layoutElement) {
await customElements.whenDefined(this._layoutElement.localName);
}
if (revision !== this._initializeConfigRevision) {
return;
}
this._setConfig(viewConfig, isStrategy);
await customElements.whenDefined(this._layoutElement!.localName);
if (this._layoutElement instanceof ReactiveElement) {
+4 -165
View File
@@ -1,170 +1,9 @@
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { debounce } from "../../common/util/debounce";
import { deepEqual } from "../../common/util/deep-equal";
import "../../components/ha-top-app-bar-fixed";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { generateLovelaceViewStrategy } from "../lovelace/strategies/get-strategy";
import type { Lovelace } from "../lovelace/types";
import "../lovelace/views/hui-view";
import "../lovelace/views/hui-view-background";
import "../lovelace/views/hui-view-container";
const MAINTENANCE_LOVELACE_VIEW_CONFIG: LovelaceStrategyViewConfig = {
strategy: {
type: "maintenance",
},
};
import { customElement } from "lit/decorators";
import { HaHomeSummaryPanelBase } from "../home/ha-home-summary-panel-base";
@customElement("ha-panel-maintenance")
class PanelMaintenance extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean, reflect: true }) public narrow = false;
@state() private _viewIndex = 0;
@state() private _lovelace?: Lovelace;
@state() private _searchParams = new URLSearchParams(window.location.search);
private _childPanelReady?: ChildPanelReady;
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
// Initial setup
if (!this.hasUpdated) {
this._setup();
return;
}
if (!changedProps.has("hass")) {
return;
}
const oldHass = changedProps.get("hass") as this["hass"];
if (oldHass && oldHass.localize !== this.hass.localize) {
this._setLovelace();
return;
}
if (oldHass && this.hass) {
// If the entity registry changed, ask the user if they want to refresh the config
if (
oldHass.entities !== this.hass.entities ||
oldHass.devices !== this.hass.devices ||
oldHass.areas !== this.hass.areas ||
oldHass.floors !== this.hass.floors ||
oldHass.panels !== this.hass.panels
) {
if (this.hass.config.state === "RUNNING") {
this._debounceRegistriesChanged();
return;
}
}
// If ha started, refresh the config
if (
this.hass.config.state === "RUNNING" &&
oldHass.config.state !== "RUNNING"
) {
this._setLovelace();
}
}
}
private async _setup() {
await this.hass.loadFragmentTranslation("lovelace");
this._setLovelace();
}
private _debounceRegistriesChanged = debounce(
() => this._registriesChanged(),
200
);
private _registriesChanged = async () => {
this._setLovelace();
};
protected render() {
return html`
<ha-top-app-bar-fixed
.narrow=${this.narrow}
.backButton=${this._searchParams.has("historyBack")}
>
<div slot="title">${this.hass.localize("panel.maintenance")}</div>
${
this._lovelace
? html`
<hui-view-container .hass=${this.hass}>
<hui-view-background .hass=${this.hass}>
</hui-view-background>
<hui-view
.hass=${this.hass}
.narrow=${this.narrow}
.lovelace=${this._lovelace}
.index=${this._viewIndex}
></hui-view>
</hui-view-container>
`
: nothing
}
</ha-top-app-bar-fixed>
`;
}
private async _setLovelace() {
const viewConfig = await generateLovelaceViewStrategy(
MAINTENANCE_LOVELACE_VIEW_CONFIG,
this.hass
);
const config = { views: [viewConfig] };
const rawConfig = { views: [MAINTENANCE_LOVELACE_VIEW_CONFIG] };
if (deepEqual(config, this._lovelace?.config)) {
return;
}
this._childPanelReady ??= new ChildPanelReady(this);
this._lovelace = {
config: config,
rawConfig: rawConfig,
editMode: false,
urlPath: "maintenance",
mode: "generated",
locale: this.hass.locale,
enableFullEditMode: () => undefined,
saveConfig: async () => undefined,
deleteConfig: async () => undefined,
setEditMode: () => undefined,
showToast: () => undefined,
};
}
static get styles(): CSSResultGroup {
return [
haStyle,
css`
:host {
user-select: none;
}
hui-view-container {
position: relative;
display: flex;
box-sizing: border-box;
}
hui-view {
flex: 1 1 100%;
max-width: 100%;
}
`,
];
}
class PanelMaintenance extends HaHomeSummaryPanelBase<"maintenance"> {
protected readonly _systemDataKey = "maintenance";
}
declare global {
@@ -14,6 +14,10 @@ import type { LovelaceSectionRawConfig } from "../../../data/lovelace/config/sec
import type { LovelaceViewConfig } from "../../../data/lovelace/config/view";
import type { HomeAssistant } from "../../../types";
import type { TileCardConfig } from "../../lovelace/cards/types";
import type {
LovelaceStrategyDependency,
LovelaceStrategyGenerateOptions,
} from "../../lovelace/strategies/types";
import { BINARY_STATE_ON } from "../../../common/const";
import { computeDomain } from "../../../common/entity/compute_domain";
import { getDeviceEntityDisplayLookup } from "../../../data/device/device_registry";
@@ -21,6 +25,7 @@ import { findBatteryChargingEntity } from "../../../data/entity/entity_registry"
export interface MaintenanceViewStrategyConfig {
type: "maintenance";
hidden?: string[];
}
export const maintenanceEntityFilters: EntityFilter[] = [
@@ -35,8 +40,10 @@ export const maintenanceEntityFilters: EntityFilter[] = [
];
export const findMaintenanceEntities = (
sources: EntityFilterSources
): string[] => findFilteredEntities(sources, maintenanceEntityFilters);
sources: EntityFilterSources,
hiddenEntities?: string[]
): string[] =>
findFilteredEntities(sources, maintenanceEntityFilters, hiddenEntities);
const LOW_BATTERY_THRESHOLD = 20;
@@ -100,26 +107,29 @@ export const filterUnavailableBatteryEntities = (
const computeMaintenanceTileCard = (
states: HomeAssistant["states"],
entities: HomeAssistant["entities"],
entityId: string
entityId: string,
editMode: boolean
): TileCardConfig => {
const deviceId = entities[entityId]?.device_id;
if (!deviceId) {
return { type: "tile", entity: entityId, name: { type: "entity" } };
}
const isProblem = states[entityId]?.attributes?.device_class === "problem";
return {
const card: TileCardConfig = {
type: "tile",
entity: entityId,
name: isProblem
? [{ type: "device" }, { type: "entity" }]
: { type: "device" },
name: !entities[entityId]?.device_id
? { type: "entity" }
: isProblem
? [{ type: "device" }, { type: "entity" }]
: { type: "device" },
};
return editMode
? { ...card, metadata: { id: entityId, hideable: true } }
: card;
};
const processAreasForBattery = (
areaIds: string[],
hass: HomeAssistant,
entities: string[]
entities: string[],
editMode: boolean
): LovelaceCardConfig[] => {
const cards: LovelaceCardConfig[] = [];
@@ -142,7 +152,12 @@ const processAreasForBattery = (
for (const entityId of areaBatteryEntities) {
areaCards.push(
computeMaintenanceTileCard(hass.states, hass.entities, entityId)
computeMaintenanceTileCard(
hass.states,
hass.entities,
entityId,
editMode
)
);
}
@@ -167,7 +182,8 @@ const processAreasForBattery = (
const processUnassignedEntities = (
hass: HomeAssistant,
entities: string[]
entities: string[],
editMode: boolean
): LovelaceCardConfig[] => {
const unassignedFilter = generateEntityFilter(
hass.states,
@@ -184,7 +200,7 @@ const processUnassignedEntities = (
for (const entityId of unassignedEntities) {
cards.push(
computeMaintenanceTileCard(hass.states, hass.entities, entityId)
computeMaintenanceTileCard(hass.states, hass.entities, entityId, editMode)
);
}
@@ -193,17 +209,27 @@ const processUnassignedEntities = (
@customElement("maintenance-view-strategy")
export class MaintenanceViewStrategy extends ReactiveElement {
static registryDependencies: readonly LovelaceStrategyDependency[] = [
"entities",
"devices",
"areas",
"floors",
"panels",
];
static async generate(
_config: MaintenanceViewStrategyConfig,
hass: HomeAssistant
config: MaintenanceViewStrategyConfig,
hass: HomeAssistant,
options?: LovelaceStrategyGenerateOptions
): Promise<LovelaceViewConfig> {
const editMode = Boolean(options?.editMode);
const areas = Object.values(hass.areas);
const floors = Object.values(hass.floors);
const hierarchy = getAreasFloorHierarchy(floors, areas);
const sections: LovelaceSectionRawConfig[] = [];
const entities = findMaintenanceEntities(hass);
const entities = findMaintenanceEntities(hass, config.hidden);
const floorCount =
hierarchy.floors.length + (hierarchy.areas.length ? 1 : 0);
@@ -229,7 +255,12 @@ export class MaintenanceViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForBattery(areaIds, hass, entities);
const areaCards = processAreasForBattery(
areaIds,
hass,
entities,
editMode
);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -255,7 +286,12 @@ export class MaintenanceViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForBattery(hierarchy.areas, hass, entities);
const areaCards = processAreasForBattery(
hierarchy.areas,
hass,
entities,
editMode
);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -264,7 +300,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
}
// Process unassigned entities
const unassignedCards = processUnassignedEntities(hass, entities);
const unassignedCards = processUnassignedEntities(hass, entities, editMode);
if (unassignedCards.length > 0) {
const section: LovelaceSectionRawConfig = {
+21
View File
@@ -3098,6 +3098,27 @@
"save_failed": "Failed to save security and safety page configuration"
}
},
"climate": {
"editor": {
"title": "Edit visible entities",
"load_failed": "Failed to load climate page configuration",
"save_failed": "Failed to save climate page configuration"
}
},
"light": {
"editor": {
"title": "Edit visible entities",
"load_failed": "Failed to load lights page configuration",
"save_failed": "Failed to save lights page configuration"
}
},
"maintenance": {
"editor": {
"title": "Edit visible entities",
"load_failed": "Failed to load maintenance page configuration",
"save_failed": "Failed to save maintenance page configuration"
}
},
"my": {
"not_supported": "This redirect is not supported by your Home Assistant instance. Check the {link} for the supported redirects and the version they where introduced.",
"component_not_loaded": "This redirect is not supported by your Home Assistant instance. You need the integration {integration} to use this redirect.",
+15 -7
View File
@@ -710,15 +710,23 @@ describe("generateEntityFilter", () => {
});
describe("findFilteredEntities", () => {
it("should match entities against any of the filters", () => {
const entities = findFilteredEntities(mockHass, [
{ domain: "light" },
{ domain: "switch" },
]);
it("should match any filter and drop excluded entities", () => {
const entities = findFilteredEntities(
mockHass,
[{ domain: "light" }, { domain: "switch" }],
["light.bedroom"]
);
expect(entities).toContain("light.living_room");
expect(entities).toContain("switch.kitchen");
expect(entities).not.toContain("light.bedroom");
expect(entities).not.toContain("sensor.temperature");
});
it("should return every match when nothing is excluded", () => {
const entities = findFilteredEntities(mockHass, [{ domain: "light" }]);
expect(entities).toContain("light.living_room");
expect(entities).toContain("light.bedroom");
expect(entities).toContain("switch.kitchen");
expect(entities).not.toContain("sensor.temperature");
});
});
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import type { LovelaceCardConfig } from "../../../../src/data/lovelace/config/card";
import type { LovelaceSectionConfig } from "../../../../src/data/lovelace/config/section";
import { LightViewStrategy } from "../../../../src/panels/light/strategies/light-view-strategy";
import type { HomeAssistant } from "../../../../src/types";
import {
mockArea,
mockEntity,
} from "../../../common/entity/context/context-mock";
import { createMockEntityState, createMockHass } from "../../../fixtures/hass";
const createLightHass = (): HomeAssistant => ({
...createMockHass(
{
"light.ceiling": createMockEntityState("light.ceiling", "on"),
"light.status_led": createMockEntityState("light.status_led", "off"),
},
{
entities: {
"light.ceiling": mockEntity({
entity_id: "light.ceiling",
area_id: "kitchen",
}),
"light.status_led": mockEntity({
entity_id: "light.status_led",
area_id: "kitchen",
}),
},
areas: {
kitchen: mockArea({ area_id: "kitchen", name: "Kitchen" }),
},
}
),
panels: {},
});
const kitchenCards = async (
config: Parameters<typeof LightViewStrategy.generate>[0]
): Promise<LovelaceCardConfig[]> => {
const view = await LightViewStrategy.generate(config, createLightHass());
const section = view.sections?.[0] as LovelaceSectionConfig;
return section.cards!.slice(1);
};
describe("LightViewStrategy", () => {
it("leaves hidden lights out of the tiles, toggle group and area buttons", async () => {
const cards = await kitchenCards({
type: "light",
hidden: ["light.status_led"],
});
const heading = cards.find((card) => card.type === "heading")!;
expect(
heading.badges.map((badge: LovelaceCardConfig) => badge.tap_action.target)
).toEqual([
{ entity_id: ["light.ceiling"] },
{ entity_id: ["light.ceiling"] },
]);
expect(
cards.find((card) => card.type === "toggle-group")?.entities
).toEqual(["light.ceiling"]);
expect(
cards.filter((card) => card.type === "tile").map((card) => card.entity)
).toEqual(["light.ceiling"]);
});
});
@@ -0,0 +1,79 @@
import { describe, expect, it } from "vitest";
import type { LovelaceCardConfig } from "../../../../../src/data/lovelace/config/card";
import type { LovelaceSectionConfig } from "../../../../../src/data/lovelace/config/section";
import { HomeAreaViewStrategy } from "../../../../../src/panels/lovelace/strategies/home/home-area-view-strategy";
import type { HomeAssistant } from "../../../../../src/types";
import {
mockArea,
mockEntity,
} from "../../../../common/entity/context/context-mock";
import {
createMockEntityState,
createMockHass,
} from "../../../../fixtures/hass";
const createKitchenHass = (): HomeAssistant => ({
...createMockHass(
{
"light.ceiling": createMockEntityState("light.ceiling", "on"),
"light.status_led": createMockEntityState("light.status_led", "off"),
},
{
entities: {
"light.ceiling": mockEntity({
entity_id: "light.ceiling",
area_id: "kitchen",
}),
"light.status_led": mockEntity({
entity_id: "light.status_led",
area_id: "kitchen",
}),
},
areas: {
kitchen: mockArea({ area_id: "kitchen", name: "Kitchen" }),
},
}
),
panels: {},
});
describe("HomeAreaViewStrategy", () => {
it("leaves hidden lights out of the Lights section and its buttons", async () => {
const view = await HomeAreaViewStrategy.generate(
{
type: "home-area",
area: "kitchen",
light_hidden_entities: ["light.status_led"],
},
createKitchenHass()
);
const [heading, ...tiles] = (view.sections?.[0] as LovelaceSectionConfig)
.cards!;
expect(
heading.badges.map((badge: LovelaceCardConfig) => badge.tap_action.target)
).toEqual([
{ entity_id: ["light.ceiling"] },
{ entity_id: ["light.ceiling"] },
]);
expect(tiles.map((card) => card.entity)).toEqual(["light.ceiling"]);
});
it("does not show hidden lights among the other area entities", async () => {
const view = await HomeAreaViewStrategy.generate(
{
type: "home-area",
area: "kitchen",
light_hidden_entities: ["light.status_led"],
},
createKitchenHass()
);
const entities = view
.sections!.flatMap(
(section) => (section as LovelaceSectionConfig).cards ?? []
)
.map((card) => card.entity);
expect(entities).not.toContain("light.status_led");
});
});
@@ -280,4 +280,60 @@ describe("MaintenanceViewStrategy.generate", () => {
},
]);
});
const createBatteryHass = () =>
createMockHass({
"sensor.car_target_charge": createMockEntityState(
"sensor.car_target_charge",
"80",
{ device_class: "battery" }
),
"sensor.remote_battery": createMockEntityState(
"sensor.remote_battery",
"80",
{ device_class: "battery" }
),
});
it("leaves hidden entities out of the view", async () => {
const view = await MaintenanceViewStrategy.generate(
{ type: "maintenance", hidden: ["sensor.car_target_charge"] },
createBatteryHass()
);
const section = view.sections?.[0] as LovelaceSectionConfig;
expect(section.cards?.slice(1)).toEqual([
{
type: "tile",
entity: "sensor.remote_battery",
name: { type: "entity" },
},
]);
});
it("adds visibility metadata to the tiles only in edit mode", async () => {
const hass = createBatteryHass();
const tiles = async (editMode: boolean) =>
(
(
await MaintenanceViewStrategy.generate(
{ type: "maintenance" },
hass,
{
editMode,
}
)
).sections?.[0] as LovelaceSectionConfig
).cards?.slice(1);
expect((await tiles(false))?.map((card) => card.metadata)).toEqual([
undefined,
undefined,
]);
expect((await tiles(true))?.map((card) => card.metadata)).toEqual([
{ id: "sensor.car_target_charge", hideable: true },
{ id: "sensor.remote_battery", hideable: true },
]);
});
});