Teardown and rebuild element editor when switching stack cards (#24065)

This commit is contained in:
karwosts 2025-02-19 22:57:34 -08:00 committed by GitHub
parent 5cddc6e5c6
commit d22a82c4a6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -21,6 +21,7 @@ import {
optional, optional,
string, string,
} from "superstruct"; } from "superstruct";
import { keyed } from "lit/directives/keyed";
import type { import type {
HaFormSchema, HaFormSchema,
SchemaUnion, SchemaUnion,
@ -84,6 +85,8 @@ export class HuiStackCardEditor
@state() protected _guiModeAvailable? = true; @state() protected _guiModeAvailable? = true;
protected _keys = new WeakMap<LovelaceCardConfig, string>();
protected _schema: readonly HaFormSchema[] = SCHEMA; protected _schema: readonly HaFormSchema[] = SCHEMA;
@query("hui-card-element-editor") @query("hui-card-element-editor")
@ -199,14 +202,16 @@ export class HuiStackCardEditor
@click=${this._handleDeleteCard} @click=${this._handleDeleteCard}
></ha-icon-button> ></ha-icon-button>
</div> </div>
${keyed(
<hui-card-element-editor this._getKey(this._config.cards[selected]),
.hass=${this.hass} html`<hui-card-element-editor
.value=${this._config.cards[selected]} .hass=${this.hass}
.lovelace=${this.lovelace} .value=${this._config.cards[selected]}
@config-changed=${this._handleConfigChanged} .lovelace=${this.lovelace}
@GUImode-changed=${this._handleGUIModeChanged} @config-changed=${this._handleConfigChanged}
></hui-card-element-editor> @GUImode-changed=${this._handleGUIModeChanged}
></hui-card-element-editor>`
)}
` `
: html` : html`
<hui-card-picker <hui-card-picker
@ -220,6 +225,14 @@ export class HuiStackCardEditor
`; `;
} }
private _getKey(card: LovelaceCardConfig) {
if (!this._keys.has(card)) {
this._keys.set(card, Math.random().toString());
}
return this._keys.get(card)!;
}
protected _handleSelectedCard(ev) { protected _handleSelectedCard(ev) {
if (ev.target.id === "add-card") { if (ev.target.id === "add-card") {
this._selectedCard = this._config!.cards.length; this._selectedCard = this._config!.cards.length;
@ -236,7 +249,10 @@ export class HuiStackCardEditor
return; return;
} }
const cards = [...this._config.cards]; const cards = [...this._config.cards];
cards[this._selectedCard] = ev.detail.config as LovelaceCardConfig; const key = this._getKey(cards[this._selectedCard]);
const newCard = ev.detail.config as LovelaceCardConfig;
cards[this._selectedCard] = newCard;
this._keys.set(newCard, key);
this._config = { ...this._config, cards }; this._config = { ...this._config, cards };
this._guiModeAvailable = ev.detail.guiModeAvailable; this._guiModeAvailable = ev.detail.guiModeAvailable;
fireEvent(this, "config-changed", { config: this._config }); fireEvent(this, "config-changed", { config: this._config });