Use event for section visibility instead of mutation observer (#20967)

This commit is contained in:
Paul Bottein 2024-06-03 15:54:40 +02:00 committed by GitHub
parent c08d9a9166
commit 0add65feff
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 20 additions and 16 deletions

View File

@ -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) {

View File

@ -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<typeof this>): 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"],
});
});
}
}