diff --git a/src/panels/lovelace/sections/hui-section.ts b/src/panels/lovelace/sections/hui-section.ts index fa722fc29a..bff0d3eb44 100644 --- a/src/panels/lovelace/sections/hui-section.ts +++ b/src/panels/lovelace/sections/hui-section.ts @@ -26,6 +26,13 @@ import { parseLovelaceCardPath } from "../editor/lovelace-path"; import { generateLovelaceSectionStrategy } from "../strategies/get-strategy"; import type { Lovelace } from "../types"; import { DEFAULT_SECTION_LAYOUT } from "./const"; +import { fireEvent } from "../../../common/dom/fire_event"; + +declare global { + interface HASSDomEvents { + "section-visibility-changed": { value: boolean }; + } +} @customElement("hui-section") export class HuiSection extends ReactiveElement { @@ -219,8 +226,12 @@ export class HuiSection extends ReactiveElement { !this.config.visibility || checkConditionsMet(this.config.visibility, this.hass); - this.style.setProperty("display", visible ? "" : "none"); - this.toggleAttribute("hidden", !visible); + if (this.hidden !== !visible) { + this.style.setProperty("display", visible ? "" : "none"); + this.toggleAttribute("hidden", !visible); + fireEvent(this, "section-visibility-changed", { value: visible }); + } + if (!visible && this._layoutElement.parentElement) { this.removeChild(this._layoutElement); } else if (visible && !this._layoutElement.parentElement) { diff --git a/src/panels/lovelace/views/hui-sections-view.ts b/src/panels/lovelace/views/hui-sections-view.ts index df963000c5..d50e1af18f 100644 --- a/src/panels/lovelace/views/hui-sections-view.ts +++ b/src/panels/lovelace/views/hui-sections-view.ts @@ -54,29 +54,22 @@ export class SectionsView extends LitElement implements LovelaceViewElement { return this._sectionConfigKeys.get(sectionConfig)!; } - private _sectionObserver?: MutationObserver; - private _computeSectionsCount() { this._sectionCount = this.sections.filter( (section) => !section.hidden ).length; } + connectedCallback(): void { + super.connectedCallback(); + this.addEventListener("section-visibility-changed", () => { + this._computeSectionsCount(); + }); + } + willUpdate(changedProperties: PropertyValues): void { - if (!this._sectionObserver) { - this._sectionObserver = new MutationObserver(() => { - this._computeSectionsCount(); - }); - } if (changedProperties.has("sections")) { this._computeSectionsCount(); - this._sectionObserver.disconnect(); - this.sections.forEach((section) => { - this._sectionObserver!.observe(section, { - attributes: true, - attributeFilter: ["hidden"], - }); - }); } }