Compare commits

...
Author SHA1 Message Date
Maarten Lakerveld f9792a391d Let users hide entities from the lights page
Move the lights panel onto HaHomeSummaryPanelBase, which brings light hidden_entities system data, config loading and the edit mode the climate and maintenance pages have. 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 and no longer switch hidden lights.

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-12 14:08:17 +01:00
Maarten Lakerveld cd17713733 Let users hide entities from the climate page
Give the climate page hidden_entities system data by moving it onto the summary panel base, so it gets the same edit mode as maintenance. 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-12 14:08:17 +01:00
Maarten Lakerveld a0fe036f48 Share one base class across the home summary panels
Maintenance moves its config loading, saving and edit mode into HaHomeSummaryPanelBase, so climate and lights can add hiding by subclassing it instead of copying the panel. Security keeps its own panel and favorites dialog for now.

The view container now uses min-height: 100%, the value the panels get on the base.
2026-11-12 14:08:17 +01:00
Maarten Lakerveld 8823dce36c Hide maintenance entities through Lovelace edit mode
The maintenance pencil faked an edit mode: it regenerated the view with every card wrapped in an entity-visibility card, while the Lovelace object kept editMode off. That card type had to be registered with the card factory, so any YAML dashboard could use it.

The panel now turns on real edit mode and sets entityVisibility on the Lovelace object. With that set, view, header, footer, sidebar and badges skip their layout editing chrome, and grid sections wrap each entity card in a hui-card-visibility-edit-mode overlay that toggles it. Cards without an entity are inert while editing, as in regular edit mode. The strategy only takes hidden_entities; while editing, the panel leaves it out so hidden entities show, dimmed.

A toggle saves and hands the view a new Lovelace object with the same config, so nothing is rebuilt and focus stays on the card. The entity-visibility card, its wrapper helper and the edit_visibility strategy option are removed.
2026-11-12 14:08:17 +01:00
30 changed files with 1043 additions and 1187 deletions

No files matched your search

+12
View File
@@ -55,6 +55,16 @@ export interface MaintenanceFrontendSystemData {
hidden_entities?: string[];
}
export interface ClimateFrontendSystemData {
hidden_entities?: string[];
}
export interface LightFrontendSystemData {
hidden_entities?: 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),
@@ -74,6 +84,8 @@ declare global {
energy: EnergyFrontendSystemData;
security: SecurityFrontendSystemData;
maintenance: MaintenanceFrontendSystemData;
climate: ClimateFrontendSystemData;
light: LightFrontendSystemData;
}
}
+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";
@@ -15,6 +16,7 @@ import { computeAreaTileCardConfig } from "../../lovelace/strategies/areas/helpe
export interface ClimateViewStrategyConfig {
type: "climate";
hidden_entities?: string[];
}
export const climateEntityFilters: EntityFilter[] = [
@@ -42,40 +44,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 +111,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 +127,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 +151,7 @@ const processAreasForClimate = (
const processUnassignedEntities = (
hass: HomeAssistant,
entities: string[]
{ entities, computeCard }: ClimateCardOptions
): LovelaceCardConfig[] => {
const unassignedFilter = generateEntityFilter(
hass.states,
@@ -173,10 +165,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;
@@ -185,7 +176,7 @@ const processUnassignedEntities = (
@customElement("climate-view-strategy")
export class ClimateViewStrategy extends ReactiveElement {
static async generate(
_config: ClimateViewStrategyConfig,
config: ClimateViewStrategyConfig,
hass: HomeAssistant
): Promise<LovelaceViewConfig> {
const areas = Object.values(hass.areas);
@@ -194,20 +185,30 @@ export class ClimateViewStrategy extends ReactiveElement {
const sections: LovelaceSectionRawConfig[] = [];
const allEntities = Object.keys(hass.states);
const entities = findClimateEntities(hass, config.hidden_entities);
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_entities);
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: computeClimateCard,
};
const floorCount =
hierarchy.floors.length + (hierarchy.areas.length ? 1 : 0);
@@ -233,7 +234,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 +258,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 +271,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,324 @@
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 { debounce } from "../../common/util/debounce";
import { deepEqual } from "../../common/util/deep-equal";
import "../../components/ha-button";
import "../../components/ha-icon-button";
import "../../components/ha-top-app-bar-fixed";
import {
fetchFrontendSystemDataAfterSaves,
queueFrontendSystemDataSave,
type HomeSummaryPanelSystemDataKey,
} from "../../data/frontend";
import type { LovelaceConfig } from "../../data/lovelace/config/types";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { showToast } from "../../util/toast";
import { generateLovelaceViewStrategy } from "../lovelace/strategies/get-strategy";
import type { Lovelace } from "../lovelace/types";
import "../lovelace/views/hui-view";
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 _config?: FrontendSystemData[K];
@state() private _lovelace?: Lovelace;
@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;
private _setLovelaceRevision = 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();
return;
}
if (oldHass && oldHass.localize !== this.hass.localize) {
this._setLovelace();
return;
}
if (
oldHass &&
(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) &&
this.hass.config.state === "RUNNING"
) {
this._debounceRegistriesChanged();
}
}
private async _setup() {
this._loadConfigPromise = this._loadConfig();
await Promise.all([
this.hass.loadFragmentTranslation("lovelace"),
this._loadConfigPromise,
]);
await 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,
});
}
}
private _debounceRegistriesChanged = debounce(() => this._setLovelace(), 200);
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}
@entity-visibility-changed=${this._visibilityChanged}
></hui-view>
</hui-view-container>
`
: nothing
}
</ha-top-app-bar-fixed>
`;
}
private async _setLovelace(force = false) {
const revision = ++this._setLovelaceRevision;
if (this._loadConfigPromise) {
await this._loadConfigPromise;
}
const viewConfig = await generateLovelaceViewStrategy(
{
strategy: {
type: this._systemDataKey,
hidden_entities: this._editMode
? undefined
: this._config?.hidden_entities,
},
},
this.hass
);
if (revision !== this._setLovelaceRevision) {
return;
}
const config =
!force &&
this._lovelace &&
deepEqual(viewConfig, this._lovelace.config.views[0])
? this._lovelace.config
: { views: [viewConfig] };
if (
config === this._lovelace?.config &&
this._lovelace.editMode === this._editMode &&
deepEqual(
this._lovelace.entityVisibility?.hiddenEntities,
this._config?.hidden_entities ?? []
)
) {
return;
}
this._childPanelReady ??= new ChildPanelReady(this);
this._lovelace = this._createLovelace(config);
}
private _createLovelace(config: LovelaceConfig): Lovelace {
return {
config: config,
rawConfig: { views: [{ strategy: { type: this._systemDataKey } }] },
editMode: this._editMode,
entityVisibility: {
hiddenEntities: this._config?.hidden_entities ?? [],
},
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["entity-visibility-changed"]>
) => {
if (!this._config) {
return;
}
const { entity, hidden } = ev.detail;
const hiddenEntities = (this._config.hidden_entities ?? []).filter(
(entityId) => entityId !== entity
);
if (hidden) {
hiddenEntities.push(entity);
}
this._saveConfig({
...this._config,
hidden_entities: hiddenEntities.length ? hiddenEntities : undefined,
});
if (this._lovelace) {
this._lovelace = this._createLovelace(this._lovelace.config);
}
};
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(true);
});
}
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%;
}
`,
];
}
}
+82 -7
View File
@@ -16,7 +16,9 @@ import {
fetchFrontendSystemData,
saveFrontendSystemData,
subscribeFrontendSystemData,
type ClimateFrontendSystemData,
type HomeFrontendSystemData,
type LightFrontendSystemData,
type MaintenanceFrontendSystemData,
type SecurityFrontendSystemData,
} from "../../data/frontend";
@@ -57,6 +59,10 @@ class PanelHome extends SubscribeMixin(LitElement) {
@state() private _maintenanceConfig: MaintenanceFrontendSystemData = {};
@state() private _climateConfig: ClimateFrontendSystemData = {};
@state() private _lightConfig: LightFrontendSystemData = {};
@state() private _extraActionItems?: ExtraActionItem[];
@query(".banner") private _banner?: HTMLElement;
@@ -67,6 +73,10 @@ class PanelHome extends SubscribeMixin(LitElement) {
private _maintenanceConfigRevision = 0;
private _climateConfigRevision = 0;
private _lightConfigRevision = 0;
public hassSubscribe() {
return [
subscribeFrontendSystemData(
@@ -99,6 +109,36 @@ class PanelHome extends SubscribeMixin(LitElement) {
}
}
),
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();
}
}
),
];
}
@@ -200,13 +240,23 @@ class PanelHome extends SubscribeMixin(LitElement) {
private async _loadConfig() {
const securityConfigRevision = this._securityConfigRevision;
const maintenanceConfigRevision = this._maintenanceConfigRevision;
const [translationsResult, homeResult, securityResult, maintenanceResult] =
await Promise.allSettled([
this.hass.loadFragmentTranslation("lovelace"),
fetchFrontendSystemData(this.hass.connection, "home"),
fetchFrontendSystemData(this.hass.connection, "security"),
fetchFrontendSystemData(this.hass.connection, "maintenance"),
]);
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
@@ -249,6 +299,29 @@ class PanelHome extends SubscribeMixin(LitElement) {
} 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(
@@ -436,6 +509,8 @@ class PanelHome extends SubscribeMixin(LitElement) {
type: "home",
alert_entities: this._securityConfig.alert_entities,
maintenance_hidden_entities: this._maintenanceConfig.hidden_entities,
climate_hidden_entities: this._climateConfig.hidden_entities,
light_hidden_entities: this._lightConfig.hidden_entities,
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 {
+124 -130
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";
@@ -21,16 +22,28 @@ import type { ButtonHeadingBadgeConfig } from "../../lovelace/heading-badges/typ
export interface LightViewStrategyConfig {
type: "light";
hidden_entities?: 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 +62,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 +172,7 @@ const processAreasForLight = (
const processUnassignedLights = (
hass: HomeAssistant,
entities: string[]
{ entities, computeCard }: LightCardOptions
): LovelaceCardConfig[] => {
const unassignedFilter = generateEntityFilter(
hass.states,
@@ -176,21 +184,13 @@ 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 async generate(
_config: LightViewStrategyConfig,
config: LightViewStrategyConfig,
hass: HomeAssistant
): Promise<LovelaceViewConfig> {
const areas = Object.values(hass.areas);
@@ -199,20 +199,10 @@ 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 cardOptions: LightCardOptions = {
entities: findLightEntities(hass, config.hidden_entities),
computeCard: computeAreaTileCardConfig(hass, false),
};
const floorCount =
hierarchy.floors.length + (hierarchy.areas.length ? 1 : 0);
@@ -238,7 +228,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 +252,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 +265,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",
@@ -16,6 +16,7 @@ import "../../../components/ha-svg-icon";
import "../components/hui-badge-edit-mode";
import { moveAtPath } from "../editor/lovelace-path";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
import type { HuiBadge } from "./hui-badge";
const BADGE_SORTABLE_OPTIONS: HaSortableOptions = {
@@ -46,7 +47,8 @@ export class HuiViewBadges extends LitElement {
private _checkAllHidden() {
const allHidden =
!this.lovelace.editMode && this.badges.every((section) => section.hidden);
!isLayoutEditMode(this.lovelace) &&
this.badges.every((section) => section.hidden);
this.toggleAttribute("hidden", allHidden);
}
@@ -125,7 +127,7 @@ export class HuiViewBadges extends LitElement {
render() {
if (!this.lovelace) return nothing;
const editMode = this.lovelace.editMode;
const editMode = isLayoutEditMode(this.lovelace);
const badges = this.badges;
@@ -1,193 +0,0 @@
import { mdiEye, mdiEyeOff } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import "../../../components/ha-svg-icon";
import type { HomeAssistant } from "../../../types";
import "./hui-card";
import type { HuiCard } from "./hui-card";
import type { LovelaceCard, LovelaceGridOptions } from "../types";
import type { EntityVisibilityCardConfig } from "./types";
@customElement("hui-entity-visibility-card")
export class HuiEntityVisibilityCard
extends LitElement
implements LovelaceCard
{
@property({ attribute: false }) public hass?: HomeAssistant;
@property({ type: Boolean }) public preview = false;
@state() private _config?: EntityVisibilityCardConfig;
private _card?: HuiCard;
public setConfig(config: EntityVisibilityCardConfig): void {
if (!config.entity) {
throw new Error("No entity configured");
}
if (!config.card) {
throw new Error("No card configured");
}
this._config = config;
this._card = document.createElement("hui-card");
this._card.hass = this.hass;
this._card.preview = this.preview;
this._card.config = config.card;
this._card.inert = true;
this._card.load();
}
public getCardSize(): number | Promise<number> {
return this._card?.getCardSize() ?? 1;
}
public getGridOptions(): LovelaceGridOptions {
return this._card?.getGridOptions() ?? {};
}
public connectedCallback(): void {
super.connectedCallback();
window.addEventListener(
"entity-visibility-changed",
this._entityVisibilityChanged
);
}
public disconnectedCallback(): void {
super.disconnectedCallback();
window.removeEventListener(
"entity-visibility-changed",
this._entityVisibilityChanged
);
}
protected willUpdate(changedProps: PropertyValues<this>): void {
super.willUpdate(changedProps);
if (!this._card) {
return;
}
if (changedProps.has("hass")) {
this._card.hass = this.hass;
}
if (changedProps.has("preview")) {
this._card.preview = this.preview;
}
}
protected render() {
if (!this._config || !this.hass || !this._card) {
return nothing;
}
const hidden = Boolean(this._config.hidden);
const stateObj = this.hass.states[this._config.entity];
const name = stateObj
? this.hass.formatEntityName(stateObj)
: this._config.entity;
return html`
<div class="wrapper" ?hidden-entity=${hidden}>
${this._card}
<button
class="control"
aria-label=${this.hass.localize(
`ui.components.items-display-editor.${hidden ? "show" : "hide"}`,
{ label: name }
)}
@click=${this._toggle}
>
<ha-svg-icon .path=${hidden ? mdiEyeOff : mdiEye}></ha-svg-icon>
</button>
</div>
`;
}
private _entityVisibilityChanged = (
ev: HASSDomEvent<HASSDomEvents["entity-visibility-changed"]>
) => {
if (
this._config?.hidden === undefined ||
ev.detail.entity !== this._config.entity ||
ev.detail.hidden === this._config.hidden
) {
return;
}
this._config = { ...this._config, hidden: ev.detail.hidden };
};
private _toggle(): void {
if (!this._config) {
return;
}
const hidden = !this._config.hidden;
this._config = { ...this._config, hidden };
fireEvent(this, "entity-visibility-changed", {
entity: this._config.entity,
hidden,
});
}
static styles: CSSResultGroup = css`
.wrapper {
position: relative;
height: 100%;
border-radius: var(--ha-card-border-radius, var(--ha-border-radius-lg));
}
hui-card {
display: block;
height: 100%;
}
.wrapper[hidden-entity] hui-card {
opacity: 0.8;
}
.wrapper[hidden-entity]::after {
content: "";
position: absolute;
inset: 0;
border: 2px dotted var(--secondary-text-color);
border-radius: inherit;
pointer-events: none;
}
.control {
position: absolute;
inset: 0;
z-index: 1;
display: flex;
align-items: flex-end;
justify-content: flex-end;
margin: 0;
padding: var(--ha-space-2);
border: none;
background: none;
border-radius: inherit;
cursor: pointer;
color: var(--primary-text-color);
}
.control:focus-visible {
outline: 2px solid var(--primary-color);
}
.control ha-svg-icon {
display: flex;
padding: var(--ha-space-1);
border-radius: var(--ha-border-radius-circle);
background: var(--secondary-background-color);
box-shadow: var(--ha-box-shadow-s);
--mdc-icon-size: 20px;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"hui-entity-visibility-card": HuiEntityVisibilityCard;
}
interface GlobalEventHandlersEventMap {
"entity-visibility-changed": HASSDomEvent<
HASSDomEvents["entity-visibility-changed"]
>;
}
interface HASSDomEvents {
"entity-visibility-changed": { entity: string; hidden: boolean };
}
}
@@ -57,6 +57,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";
@@ -172,12 +173,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 = findLightEntities(
{ states, entities, devices, areas, floors },
this._config.hidden_entities
);
const lightEntities = findEntities(allEntities, lightsFilters);
const onLights = lightEntities.filter((entityId) => {
const s = states[entityId]?.state;
return s === "on";
@@ -191,12 +191,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) {
-6
View File
@@ -71,12 +71,6 @@ export interface ConditionalCardConfig extends LovelaceCardConfig {
conditions: VisibilityCondition[];
}
export interface EntityVisibilityCardConfig extends LovelaceCardConfig {
entity: string;
hidden?: boolean;
card: LovelaceCardConfig;
}
export interface EmptyStateButtonConfig {
text: string;
icon?: string;
@@ -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() public entity!: string;
@property({ type: Boolean, reflect: true, attribute: "entity-hidden" })
public entityHidden = false;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@state()
@consumeEntityState({ entityIdPath: ["entity"] })
private _stateObj?: HassEntity;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: HomeAssistantFormatters;
protected render() {
const name = this._stateObj
? this._formatters.formatEntityName(this._stateObj)
: this.entity;
return html`
<div class="card-wrapper" inert><slot></slot></div>
<button
class="control"
aria-label=${this._localize(
`ui.components.items-display-editor.${this.entityHidden ? "show" : "hide"}`,
{ label: name }
)}
@click=${this._toggle}
>
<ha-svg-icon
.path=${this.entityHidden ? mdiEyeOff : mdiEye}
></ha-svg-icon>
</button>
`;
}
private _toggle(): void {
fireEvent(this, "entity-visibility-changed", {
entity: this.entity,
hidden: !this.entityHidden,
});
}
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([entity-hidden]) .card-wrapper {
opacity: 0.8;
}
:host([entity-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 {
"entity-visibility-changed": HASSDomEvent<
HASSDomEvents["entity-visibility-changed"]
>;
}
interface HASSDomEvents {
"entity-visibility-changed": { entity: string; hidden: boolean };
}
}
@@ -38,7 +38,6 @@ const LAZY_LOAD_TYPES = {
area: () => import("../cards/hui-area-card"),
calendar: () => import("../cards/hui-calendar-card"),
conditional: () => import("../cards/hui-conditional-card"),
"entity-visibility": () => import("../cards/hui-entity-visibility-card"),
"empty-state": () => import("../cards/hui-empty-state-card"),
"energy-compare": () => import("../cards/energy/hui-energy-compare-card"),
"energy-carbon-consumed-gauge": () =>
@@ -18,8 +18,10 @@ 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 { isLayoutEditMode } from "../types";
const CARD_SORTABLE_OPTIONS: HaSortableOptions = {
delay: 100,
@@ -78,7 +80,10 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
const cardsConfig = this._config?.cards ?? [];
const editMode = Boolean(this.lovelace?.editMode && !this.isStrategy);
const editMode = isLayoutEditMode(this.lovelace) && !this.isStrategy;
const visibility = this.lovelace?.editMode
? this.lovelace.entityVisibility
: undefined;
const sortableOptions = this.importOnly
? IMPORT_MODE_CARD_SORTABLE_OPTIONS
@@ -104,7 +109,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 +131,10 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
"full-width": columns === "full",
hidden: !editMode && card.hidden,
})}"
?inert=${
visibility !== undefined &&
typeof cardConfig.entity !== "string"
}
.sortableData=${cardPath}
>
${
@@ -141,7 +150,18 @@ export class GridSection extends LitElement implements LovelaceSectionElement {
${card}
</hui-card-edit-mode>
`
: card
: visibility && typeof cardConfig.entity === "string"
? html`
<hui-card-visibility-edit-mode
.entity=${cardConfig.entity}
.entityHidden=${visibility.hiddenEntities.includes(
cardConfig.entity
)}
>
${card}
</hui-card-visibility-edit-mode>
`
: card
}
</div>
`;
@@ -1,13 +0,0 @@
import type { LovelaceCardConfig } from "../../../../data/lovelace/config/card";
import type { EntityVisibilityCardConfig } from "../../cards/types";
export type ComputeEntityCard = (entityId: string) => LovelaceCardConfig;
export const wrapEntityVisibility =
(hiddenEntities: Set<string>, computeCard: ComputeEntityCard) =>
(entityId: string): EntityVisibilityCardConfig => ({
type: "entity-visibility",
entity: entityId,
hidden: hiddenEntities.has(entityId),
card: computeCard(entityId),
});
@@ -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
@@ -22,6 +22,8 @@ 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;
@@ -73,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,
};
@@ -108,6 +112,8 @@ export class HomeDashboardStrategy extends ReactiveElement {
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,
@@ -37,6 +37,7 @@ import type {
UpdatesCardConfig,
} from "../../cards/types";
import { computeFavoriteCardConfig } from "../helpers/favorite-cards";
import { findLightEntities } from "../../../light/strategies/light-view-strategy";
import { findMaintenanceEntities } from "../../../maintenance/strategies/maintenance-view-strategy";
import {
computeDefaultSecurityAlertVisibility,
@@ -58,6 +59,8 @@ 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;
@@ -346,22 +349,14 @@ 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 =
@@ -415,6 +410,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",
@@ -426,6 +424,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",
+8
View File
@@ -48,8 +48,16 @@ export interface Lovelace {
* window's history and scroll position.
*/
embedded?: boolean;
/**
* Limits edit mode to showing and hiding the entity cards of a generated
* view, instead of editing its layout.
*/
entityVisibility?: { hiddenEntities: string[] };
}
export const isLayoutEditMode = (lovelace?: Lovelace): boolean =>
Boolean(lovelace?.editMode && !lovelace.entityVisibility);
export interface LovelaceBadge extends HTMLElement {
hass?: HomeAssistant;
preview?: boolean;
@@ -37,6 +37,7 @@ import {
sectionContainerStyles,
} from "../sections/section-container";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
import { generateDefaultSection } from "./default-section";
import "./hui-view-footer";
import "./hui-view-header";
@@ -191,7 +192,7 @@ export class SectionsView extends LitElement implements LovelaceViewElement {
if (!this.lovelace) return nothing;
const sections = this.sections;
const editMode = this.lovelace.editMode;
const editMode = isLayoutEditMode(this.lovelace);
const hasSidebar =
this._config?.sidebar && (this._sidebarVisible || editMode);
const singleColumn = this._maxColumns <= 1;
+5 -4
View File
@@ -19,6 +19,7 @@ import { showCreateCardDialog } from "../editor/card-editor/show-create-card-dia
import { setAtPath } from "../editor/lovelace-path";
import { showEditViewFooterDialog } from "../editor/view-footer/show-edit-view-footer-dialog";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
@customElement("hui-view-footer")
export class HuiViewFooter extends LitElement {
@@ -53,7 +54,7 @@ export class HuiViewFooter extends LitElement {
this.card.hass = this.hass;
}
if (changedProperties.has("lovelace")) {
this.card.preview = this.lovelace.editMode;
this.card.preview = isLayoutEditMode(this.lovelace);
}
}
@@ -69,7 +70,7 @@ export class HuiViewFooter extends LitElement {
private _checkHidden() {
const hidden =
!this.lovelace?.editMode &&
!isLayoutEditMode(this.lovelace) &&
(!this.card || this.card.hasAttribute("hidden"));
this.toggleAttribute("hidden", hidden);
this.toggleAttribute("sticky", Boolean(this.card));
@@ -78,7 +79,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 = isLayoutEditMode(this.lovelace);
element.layout = "grid";
element.config = cardConfig;
element.addEventListener("card-updated", (ev: Event) => {
@@ -150,7 +151,7 @@ export class HuiViewFooter extends LitElement {
render() {
if (!this.lovelace) return nothing;
const editMode = Boolean(this.lovelace?.editMode);
const editMode = isLayoutEditMode(this.lovelace);
const card = this.card;
if (!editMode && !card) {
+7 -5
View File
@@ -22,6 +22,7 @@ import { showEditCardDialog } from "../editor/card-editor/show-edit-card-dialog"
import { setAtPath } from "../editor/lovelace-path";
import { showEditViewHeaderDialog } from "../editor/view-header/show-edit-view-header-dialog";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
export const DEFAULT_VIEW_HEADER_LAYOUT = "center";
export const DEFAULT_VIEW_HEADER_BADGES_POSITION = "bottom";
@@ -44,7 +45,7 @@ export class HuiViewHeader extends LitElement {
private _checkHidden() {
const allHidden =
!this.card &&
!this.lovelace.editMode &&
!isLayoutEditMode(this.lovelace) &&
this.badges.every((badges) => badges.hidden);
this.toggleAttribute("hidden", allHidden);
}
@@ -87,7 +88,8 @@ export class HuiViewHeader extends LitElement {
if (changedProperties.has("config") || changedProperties.has("lovelace")) {
this._dragScrollController.enabled =
!this.lovelace.editMode && this.config?.badges_wrap === "scroll";
!isLayoutEditMode(this.lovelace) &&
this.config?.badges_wrap === "scroll";
}
if (changedProperties.has("config")) {
@@ -105,7 +107,7 @@ export class HuiViewHeader extends LitElement {
this.card.hass = this.hass;
}
if (changedProperties.has("lovelace")) {
this.card.preview = this.lovelace.editMode;
this.card.preview = isLayoutEditMode(this.lovelace);
}
}
}
@@ -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 = isLayoutEditMode(this.lovelace);
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 = isLayoutEditMode(this.lovelace);
const card = this.card;
@@ -13,6 +13,7 @@ import {
sectionContainerStyles,
} from "../sections/section-container";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
import type { LovelaceSectionConfig } from "../../../data/lovelace/config/section";
export const DEFAULT_VIEW_SIDEBAR_LAYOUT = "start";
@@ -74,7 +75,7 @@ export class HuiViewSidebar extends ConditionalListenerMixin<LovelaceViewSidebar
<hui-section
.config=${section}
.hass=${this.hass}
.preview=${this.lovelace.editMode}
.preview=${isLayoutEditMode(this.lovelace)}
.path=${sectionPath}
></hui-section>
`;
+7 -6
View File
@@ -66,6 +66,7 @@ import {
generateLovelaceViewStrategy,
} from "../strategies/get-strategy";
import type { Lovelace } from "../types";
import { isLayoutEditMode } from "../types";
import { PANEL_VIEW_LAYOUT, SIDEBAR_VIEW_LAYOUT } from "./const";
import { getViewType } from "./get-view-type";
@@ -378,7 +379,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 = isLayoutEditMode(this.lovelace);
element.config = cardConfig;
element.addEventListener("card-updated", (ev: Event) => {
ev.stopPropagation();
@@ -391,7 +392,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 = isLayoutEditMode(this.lovelace);
element.config = badgeConfig;
element.addEventListener("badge-updated", (ev: Event) => {
ev.stopPropagation();
@@ -407,7 +408,7 @@ export class HUIView extends ReactiveElement {
element.hass = this.hass;
element.lovelace = this.lovelace;
element.config = sectionConfig;
element.preview = this.lovelace.editMode;
element.preview = isLayoutEditMode(this.lovelace);
element.addEventListener(
"ll-rebuild",
(ev: Event) => {
@@ -516,16 +517,16 @@ export class HUIView extends ReactiveElement {
try {
element.hass = this.hass;
element.lovelace = this.lovelace;
element.preview = this.lovelace.editMode;
element.preview = isLayoutEditMode(this.lovelace);
} catch (e: any) {
this._rebuildSection(element, createErrorSectionConfig(e.message));
}
});
this._cards.forEach((element) => {
element.preview = this.lovelace.editMode;
element.preview = isLayoutEditMode(this.lovelace);
});
this._badges.forEach((element) => {
element.preview = this.lovelace.editMode;
element.preview = isLayoutEditMode(this.lovelace);
});
}
if (changedProperties.has("_cards")) {
+4 -308
View File
@@ -1,313 +1,9 @@
import { mdiPencil } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { debounce } from "../../common/util/debounce";
import { deepEqual } from "../../common/util/deep-equal";
import "../../components/ha-button";
import "../../components/ha-icon-button";
import "../../components/ha-top-app-bar-fixed";
import {
fetchFrontendSystemDataAfterSaves,
queueFrontendSystemDataSave,
type MaintenanceFrontendSystemData,
} from "../../data/frontend";
import type { LovelaceStrategyViewConfig } from "../../data/lovelace/config/view";
import { ChildPanelReady } from "../../layouts/panel-ready";
import { haStyle } from "../../resources/styles";
import type { HomeAssistant } from "../../types";
import { showToast } from "../../util/toast";
import { generateLovelaceViewStrategy } from "../lovelace/strategies/get-strategy";
import type { Lovelace } from "../lovelace/types";
import "../lovelace/views/hui-view";
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 _config?: MaintenanceFrontendSystemData;
@state() private _editVisibility = false;
@state() private _searchParams = new URLSearchParams(window.location.search);
private _childPanelReady?: ChildPanelReady;
private _loadConfigPromise?: Promise<void>;
private _loadConfigRevision = 0;
private _setLovelaceRevision = 0;
public willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
// Initial setup
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();
return;
}
if (oldHass && oldHass.localize !== this.hass.localize) {
this._setLovelace();
return;
}
if (oldHass && this.hass) {
// Refresh the generated view when registries or panels change.
if (
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();
}
}
}
}
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,
"maintenance"
);
if (revision !== this._loadConfigRevision) {
return;
}
this._config = data || {};
} catch (err) {
if (revision !== this._loadConfigRevision) {
return;
}
this._editVisibility = false;
// eslint-disable-next-line no-console
console.error("Failed to load maintenance configuration:", err);
showToast(this, {
message: this.hass.localize("ui.panel.maintenance.editor.load_failed"),
duration: 0,
dismissable: true,
});
}
}
private _debounceRegistriesChanged = debounce(
() => this._registriesChanged(),
200
);
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.hass.user?.is_admin
? nothing
: this._editVisibility
? html`<ha-button
slot="actionItems"
appearance="filled"
size="s"
@click=${this._stopEditVisibility}
>
${this.hass.localize("ui.panel.lovelace.menu.exit_edit_mode")}
</ha-button>`
: this._config
? html`<ha-icon-button
slot="actionItems"
.path=${mdiPencil}
.label=${this.hass.localize("ui.panel.maintenance.editor.title")}
@click=${this._startEditVisibility}
></ha-icon-button>`
: nothing
}
${
this._lovelace
? html`
<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}
@entity-visibility-changed=${this._visibilityChanged}
></hui-view>
</hui-view-container>
`
: nothing
}
</ha-top-app-bar-fixed>
`;
}
private async _setLovelace(force = false) {
const revision = ++this._setLovelaceRevision;
if (this._loadConfigPromise) {
await this._loadConfigPromise;
}
const viewConfig = await generateLovelaceViewStrategy(
{
strategy: {
...MAINTENANCE_LOVELACE_VIEW_CONFIG.strategy,
hidden_entities: this._config?.hidden_entities,
edit_visibility: this._editVisibility || undefined,
},
},
this.hass
);
if (revision !== this._setLovelaceRevision) {
return;
}
const config = { views: [viewConfig] };
const rawConfig = { views: [MAINTENANCE_LOVELACE_VIEW_CONFIG] };
if (!force && deepEqual(config, this._lovelace?.config)) {
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,
};
}
private _startEditVisibility = () => {
this._editVisibility = true;
this._setLovelace();
};
private _stopEditVisibility = () => {
this._editVisibility = false;
if (!this._config) {
this._loadConfigPromise = this._loadConfig();
}
this._setLovelace();
};
private _visibilityChanged = (
ev: HASSDomEvent<HASSDomEvents["entity-visibility-changed"]>
) => {
if (!this._config) {
return;
}
const { entity, hidden } = ev.detail;
const hiddenEntities = (this._config.hidden_entities ?? []).filter(
(entityId) => entityId !== entity
);
if (hidden) {
hiddenEntities.push(entity);
}
this._saveConfig({
...this._config,
hidden_entities: hiddenEntities.length ? hiddenEntities : undefined,
});
};
private _saveConfig(config: MaintenanceFrontendSystemData): Promise<void> {
this._config = config;
return queueFrontendSystemDataSave(
this.hass.connection,
"maintenance",
config
).catch(async (err) => {
// eslint-disable-next-line no-console
console.error("Failed to save maintenance configuration:", err);
showToast(this, {
message: this.hass.localize("ui.panel.maintenance.editor.save_failed"),
duration: 0,
dismissable: true,
});
if (config !== this._config) {
return;
}
await this._loadConfig();
await this._setLovelace(true);
});
}
static get styles(): CSSResultGroup {
return [
haStyle,
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,10 +14,6 @@ import type { LovelaceSectionRawConfig } from "../../../data/lovelace/config/sec
import type { LovelaceViewConfig } from "../../../data/lovelace/config/view";
import type { HomeAssistant } from "../../../types";
import type { TileCardConfig } from "../../lovelace/cards/types";
import {
wrapEntityVisibility,
type ComputeEntityCard,
} from "../../lovelace/strategies/helpers/entity-visibility";
import { BINARY_STATE_ON } from "../../../common/const";
import { computeDomain } from "../../../common/entity/compute_domain";
import { getDeviceEntityDisplayLookup } from "../../../data/device/device_registry";
@@ -26,7 +22,6 @@ import { findBatteryChargingEntity } from "../../../data/entity/entity_registry"
export interface MaintenanceViewStrategyConfig {
type: "maintenance";
hidden_entities?: string[];
edit_visibility?: boolean;
}
export const maintenanceEntityFilters: EntityFilter[] = [
@@ -127,8 +122,7 @@ const computeMaintenanceTileCard = (
const processAreasForBattery = (
areaIds: string[],
hass: HomeAssistant,
entities: string[],
computeCard: ComputeEntityCard
entities: string[]
): LovelaceCardConfig[] => {
const cards: LovelaceCardConfig[] = [];
@@ -150,7 +144,9 @@ const processAreasForBattery = (
const areaCards: LovelaceCardConfig[] = [];
for (const entityId of areaBatteryEntities) {
areaCards.push(computeCard(entityId));
areaCards.push(
computeMaintenanceTileCard(hass.states, hass.entities, entityId)
);
}
if (areaCards.length > 0) {
@@ -174,8 +170,7 @@ const processAreasForBattery = (
const processUnassignedEntities = (
hass: HomeAssistant,
entities: string[],
computeCard: ComputeEntityCard
entities: string[]
): LovelaceCardConfig[] => {
const unassignedFilter = generateEntityFilter(
hass.states,
@@ -191,7 +186,9 @@ const processUnassignedEntities = (
const cards: LovelaceCardConfig[] = [];
for (const entityId of unassignedEntities) {
cards.push(computeCard(entityId));
cards.push(
computeMaintenanceTileCard(hass.states, hass.entities, entityId)
);
}
return cards;
@@ -209,16 +206,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
const sections: LovelaceSectionRawConfig[] = [];
const entities = findMaintenanceEntities(
hass,
config.edit_visibility ? undefined : config.hidden_entities
);
const computeTileCard = (entityId: string) =>
computeMaintenanceTileCard(hass.states, hass.entities, entityId);
const computeCard: ComputeEntityCard = config.edit_visibility
? wrapEntityVisibility(new Set(config.hidden_entities), computeTileCard)
: computeTileCard;
const entities = findMaintenanceEntities(hass, config.hidden_entities);
const floorCount =
hierarchy.floors.length + (hierarchy.areas.length ? 1 : 0);
@@ -244,12 +232,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForBattery(
areaIds,
hass,
entities,
computeCard
);
const areaCards = processAreasForBattery(areaIds, hass, entities);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -275,12 +258,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
],
};
const areaCards = processAreasForBattery(
hierarchy.areas,
hass,
entities,
computeCard
);
const areaCards = processAreasForBattery(hierarchy.areas, hass, entities);
if (areaCards.length > 0) {
section.cards!.push(...areaCards);
@@ -289,11 +267,7 @@ export class MaintenanceViewStrategy extends ReactiveElement {
}
// Process unassigned entities
const unassignedCards = processUnassignedEntities(
hass,
entities,
computeCard
);
const unassignedCards = processUnassignedEntities(hass, entities);
if (unassignedCards.length > 0) {
const section: LovelaceSectionRawConfig = {
+14
View File
@@ -2960,6 +2960,20 @@
"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",
@@ -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_entities: ["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");
});
});
@@ -311,40 +311,4 @@ describe("MaintenanceViewStrategy.generate", () => {
},
]);
});
it("keeps hidden entities as hidden visibility wrappers while editing", async () => {
const view = await MaintenanceViewStrategy.generate(
{
type: "maintenance",
hidden_entities: ["sensor.car_target_charge"],
edit_visibility: true,
},
createBatteryHass()
);
const section = view.sections?.[0] as LovelaceSectionConfig;
expect(section.cards?.slice(1)).toEqual([
{
type: "entity-visibility",
entity: "sensor.car_target_charge",
hidden: true,
card: {
type: "tile",
entity: "sensor.car_target_charge",
name: { type: "entity" },
},
},
{
type: "entity-visibility",
entity: "sensor.remote_battery",
hidden: false,
card: {
type: "tile",
entity: "sensor.remote_battery",
name: { type: "entity" },
},
},
]);
});
});