fix: Expand templates in stock elements (#2199)

- Related: #2193
This commit is contained in:
Dermot Duffy
2025-10-06 21:14:29 -07:00
committed by GitHub
parent af53c66cd5
commit 9f479f8b4f
5 changed files with 89 additions and 44 deletions
+11 -4
View File
@@ -91,7 +91,7 @@ export class ActionsManager implements ActionsExecutor {
/** /**
* This method is called when an ll-custom event is fired. This is used by * This method is called when an ll-custom event is fired. This is used by
* cards to fire custom actions. This card itself should not call this, but * cards to fire custom actions. This card itself should not call this, but
* embedded elements may. * embedded picture elements may.
*/ */
public handleCustomActionEvent = async ( public handleCustomActionEvent = async (
ev: Event | CustomEvent<ActionConfig>, ev: Event | CustomEvent<ActionConfig>,
@@ -111,7 +111,11 @@ export class ActionsManager implements ActionsExecutor {
return; return;
} }
await this.executeActions({ actions: action }); await this.executeActions(
{ actions: action },
// Elements rendered by this card will already have rendered templates.
true,
);
}; };
/** /**
@@ -129,10 +133,13 @@ export class ActionsManager implements ActionsExecutor {
await allPromises(this._actionsInFlight, (actionSet) => actionSet.stop()); await allPromises(this._actionsInFlight, (actionSet) => actionSet.stop());
} }
public async executeActions(request: ActionsExecutionRequest): Promise<void> { public async executeActions(
request: ActionsExecutionRequest,
renderTemplates = true,
): Promise<void> {
const hass = this._api.getHASSManager().getHASS(); const hass = this._api.getHASSManager().getHASS();
const renderedAction: ActionConfig | ActionConfig[] = const renderedAction: ActionConfig | ActionConfig[] =
hass && this._templateRenderer renderTemplates && hass && this._templateRenderer
? (this._templateRenderer.renderRecursively(hass, request.actions, { ? (this._templateRenderer.renderRecursively(hass, request.actions, {
conditionState: this._api.getConditionStateManager().getState(), conditionState: this._api.getConditionStateManager().getState(),
triggerData: request?.triggerData, triggerData: request?.triggerData,
+10 -10
View File
@@ -20,15 +20,17 @@ interface TemplateContext {
acc: TemplateContextInternal; acc: TemplateContextInternal;
} }
interface TemplateRenderOptions {
conditionState?: ConditionState;
triggerData?: ConditionsTriggerData;
mediaData?: TemplateMediaData;
}
export class TemplateRenderer { export class TemplateRenderer {
public renderRecursively = ( public renderRecursively = (
hass: HomeAssistant, hass: HomeAssistant,
data: unknown, data: unknown,
options?: { options?: TemplateRenderOptions,
conditionState?: ConditionState;
triggerData?: ConditionsTriggerData;
mediaData?: TemplateMediaData;
},
): unknown => { ): unknown => {
return this._renderTemplateRecursively( return this._renderTemplateRecursively(
hass, hass,
@@ -37,11 +39,9 @@ export class TemplateRenderer {
); );
}; };
protected _generateTemplateContext(options?: { protected _generateTemplateContext(
conditionState?: ConditionState; options?: TemplateRenderOptions,
triggerData?: ConditionsTriggerData; ): TemplateContext | undefined {
mediaData?: TemplateMediaData;
}): TemplateContext | undefined {
if ( if (
!options?.conditionState?.camera && !options?.conditionState?.camera &&
!options?.conditionState?.view && !options?.conditionState?.view &&
+1
View File
@@ -409,6 +409,7 @@ class AdvancedCameraCard extends LitElement {
${ref(this._refElements)} ${ref(this._refElements)}
.hass=${this._hass} .hass=${this._hass}
.elements=${this._config?.elements} .elements=${this._config?.elements}
.conditionStateManager=${this._controller.getConditionStateManager()}
@advanced-camera-card:menu:add=${(ev: CustomEvent<MenuItem>) => { @advanced-camera-card:menu:add=${(ev: CustomEvent<MenuItem>) => {
this._menuButtonController.addDynamicMenuButton(ev.detail); this._menuButtonController.addDynamicMenuButton(ev.detail);
this.requestUpdate(); this.requestUpdate();
+66 -29
View File
@@ -7,9 +7,12 @@ import {
unsafeCSS, unsafeCSS,
} from 'lit'; } from 'lit';
import { customElement, property, state } from 'lit/decorators.js'; import { customElement, property, state } from 'lit/decorators.js';
import { isEqual } from 'lodash-es';
import { TemplateRenderer } from '../card-controller/templates/index.js';
import { dispatchAdvancedCameraCardErrorEvent } from '../components-lib/message/dispatch.js'; import { dispatchAdvancedCameraCardErrorEvent } from '../components-lib/message/dispatch.js';
import { ConditionsManager } from '../conditions/conditions-manager.js'; import { ConditionsManager } from '../conditions/conditions-manager.js';
import { getConditionStateManagerViaEvent } from '../conditions/state-manager-via-event.js'; import { getConditionStateManagerViaEvent } from '../conditions/state-manager-via-event.js';
import { ConditionStateManager } from '../conditions/state-manager.js';
import { import {
StatusBarIcon, StatusBarIcon,
StatusBarImage, StatusBarImage,
@@ -75,12 +78,19 @@ interface HuiConditionalElement extends HTMLElement {
@customElement('advanced-camera-card-elements-core') @customElement('advanced-camera-card-elements-core')
export class AdvancedCameraCardElementsCore extends LitElement { export class AdvancedCameraCardElementsCore extends LitElement {
@property({ attribute: false }) @property({ attribute: false })
public elements?: PictureElements; public hass?: HomeAssistant;
protected _root: HuiConditionalElement | null = null;
@property({ attribute: false }) @property({ attribute: false })
public hass?: HomeAssistant; public elements?: PictureElements;
@property({ attribute: false })
public conditionStateManager?: ConditionStateManager;
@state()
private _root: HuiConditionalElement | null = null;
private _renderedElements?: PictureElements;
private _templateRenderer = new TemplateRenderer();
/** /**
* Create a transparent render root. * Create a transparent render root.
@@ -104,7 +114,7 @@ export class AdvancedCameraCardElementsCore extends LitElement {
const config = { const config = {
type: 'conditional', type: 'conditional',
conditions: [], conditions: [],
elements: this.elements, elements: this._renderedElements,
}; };
try { try {
element.setConfig(config); element.setConfig(config);
@@ -115,26 +125,58 @@ export class AdvancedCameraCardElementsCore extends LitElement {
return element; return element;
} }
/** private _setNewRoot = (): void => {
* Create the root as necessary prior to rendering. if (!this.hass) {
*/ return;
protected willUpdate(changedProps: PropertyValues): void { }
const elements = this._templateRenderer.renderRecursively(this.hass, this.elements, {
conditionState: this.conditionStateManager?.getState(),
}) as PictureElements | undefined;
// Condition state changes won't change the actual rendered config unless
// `elements` has a template, which is more likely does not. Avoid updating
// the root if nothing changes.
if (this._root && isEqual(this._renderedElements, elements)) {
return;
}
try { try {
// The root is only created once per elements configuration change, to this._renderedElements = elements;
// avoid the elements being continually re-created & destroyed (for some this._root = this._createRoot();
// elements, e.g. image, recreation causes a flicker).
if (this.elements && (!this._root || changedProps.has('elements'))) {
this._root = this._createRoot();
}
} catch (e) { } catch (e) {
return dispatchAdvancedCameraCardErrorEvent(this, e as AdvancedCameraCardError); return dispatchAdvancedCameraCardErrorEvent(this, e as AdvancedCameraCardError);
} }
};
connectedCallback(): void {
super.connectedCallback();
this.conditionStateManager?.addListener(this._setNewRoot);
}
disconnectedCallback(): void {
this.conditionStateManager?.removeListener(this._setNewRoot);
super.disconnectedCallback();
}
protected willUpdate(changedProps: PropertyValues): void {
if (changedProps.has('conditionStateManager') && this.conditionStateManager) {
changedProps.get('conditionStateManager')?.removeEventListener(this._setNewRoot);
this.conditionStateManager.addListener(this._setNewRoot);
}
// The root is only created once per elements configuration change, to
// avoid the elements being continually re-created & destroyed (for some
// elements, e.g. image, recreation causes a flicker).
if (
!this._root ||
changedProps.has('elements') ||
changedProps.has('conditionStateManager')
) {
this._setNewRoot();
}
} }
/**
* Render the elements.
* @returns A rendered template or void.
*/
protected render(): TemplateResult | void { protected render(): TemplateResult | void {
return html`${this._root || ''}`; return html`${this._root || ''}`;
} }
@@ -148,16 +190,16 @@ export class AdvancedCameraCardElementsCore extends LitElement {
} }
} }
/**
* The master <advanced-camera-card-elements> class, handles event listeners and styles.
*/
@customElement('advanced-camera-card-elements') @customElement('advanced-camera-card-elements')
export class AdvancedCameraCardElements extends LitElement { export class AdvancedCameraCardElements extends LitElement {
@property({ attribute: false }) @property({ attribute: false })
public hass?: HomeAssistant; public hass?: HomeAssistant;
@property({ attribute: false }) @property({ attribute: false })
public elements: PictureElements; public elements?: PictureElements;
@property({ attribute: false })
public conditionStateManager?: ConditionStateManager;
protected _addHandler( protected _addHandler(
target: EventTarget, target: EventTarget,
@@ -238,6 +280,7 @@ export class AdvancedCameraCardElements extends LitElement {
protected render(): TemplateResult { protected render(): TemplateResult {
return html`<advanced-camera-card-elements-core return html`<advanced-camera-card-elements-core
.conditionStateManager=${this.conditionStateManager}
.hass=${this.hass} .hass=${this.hass}
.elements=${this.elements} .elements=${this.elements}
> >
@@ -285,9 +328,6 @@ export class AdvancedCameraCardElementsConditional extends LitElement {
return this; return this;
} }
/**
* Connected callback.
*/
connectedCallback(): void { connectedCallback(): void {
super.connectedCallback(); super.connectedCallback();
@@ -317,9 +357,6 @@ export class AdvancedCameraCardElementsConditional extends LitElement {
this._conditionManager.addListener(() => this.requestUpdate()); this._conditionManager.addListener(() => this.requestUpdate());
} }
/**
* Render the card.
*/
protected render(): TemplateResult | void { protected render(): TemplateResult | void {
if (this._conditionManager?.getEvaluation()?.result) { if (this._conditionManager?.getEvaluation()?.result) {
return html` <advanced-camera-card-elements-core return html` <advanced-camera-card-elements-core
+1 -1
View File
@@ -17,7 +17,7 @@ export class ConditionStateManager implements ConditionStateManagerReadonlyInter
this._listeners.push(listener); this._listeners.push(listener);
} }
public removeListener(listener: ConditionStateListener): void { public removeListener(listener?: ConditionStateListener): void {
this._listeners = this._listeners.filter((l) => l !== listener); this._listeners = this._listeners.filter((l) => l !== listener);
} }