perf(bundle): lazy-load the nunjucks template engine (#2535)

Closes #2531.

## Summary

The full `nunjucks` templating engine (~226KB) plus `ha-nunjucks`
(~46KB) — roughly **272KB, ~13% of the eager entry chunk** — was
statically imported and downloaded by every card on initial load, even
though templates only apply when a config value contains a `{{ … }}` /
`{% … %}` delimiter. Most cards use no templates and never need the
engine.

This defers the engine behind a dynamic `import('ha-nunjucks/dist')` so
it ships in a separate, on-demand chunk instead of the eager
`card-*.js`.

## Approach

The render path (`TemplateRenderer.renderRecursively`) is **kept
synchronous** — it is called from many synchronous hot paths
(condition/trigger evaluators, picture-elements rendering, actions,
folder matchers), and making it async would be a large, high-risk
refactor of the evaluation core.

Instead:

- **New `src/card-controller/templates/engine.ts`** — a module-level
singleton lazy loader (`loadTemplateEngine()` / `getTemplateEngine()`)
shared across all `TemplateRenderer` instances, plus a
`containsTemplate()` delimiter helper.
- **Delimiter gating** — strings without a delimiter never touch the
engine (the overwhelming majority of renders).
- **Pre-warm at config time** — because every template string originates
in the config, a new mandatory `TEMPLATE_ENGINE` initialization aspect
loads the engine before first render whenever the config contains a
delimiter. This **guarantees no raw `{{ … }}` flash**: content/condition
rendering is blocked until the engine is present for template-using
cards. Cards without templates never load it.

## Result

- nunjucks + ha-nunjucks move out of the eager chunk into a separate
chunk fetched only when a card actually uses templates.
- No change to the synchronous public render API; condition/trigger
evaluation core untouched.

## Tests

- New `engine.ts` loader coverage (concurrent load, cached reuse,
not-loaded fallback).
- The 11 existing test files that render real (delimiter-bearing)
templates declare their dependency explicitly via
`beforeAll(loadTemplateEngine)` — no global/implicit setup hook.
- Full suite green (4764 tests), lint and ts-prune clean, per-file 100%
coverage maintained for the affected directories.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_016ykWemdkZrgywvC71pHc6c

---
_Generated by [Claude
Code](https://claude.ai/code/session_016ykWemdkZrgywvC71pHc6c)_
This commit is contained in:
Dermot Duffy
2026-06-30 17:45:13 -07:00
committed by dermotduffy
parent b33c034810
commit ea251ca988
59 changed files with 1420 additions and 541 deletions
+20 -10
View File
@@ -10,7 +10,8 @@ import { customElement, property, state } from 'lit/decorators.js';
import { isEqual } from 'lodash-es';
import type { IssueTriggerEventData } from '../card-controller/issues/types.js';
import { TemplateRenderer } from '../card-controller/templates/index.js';
import type { TemplateRenderer } from '../card-controller/templates/index.js';
import { getTemplateRendererViaEvent } from '../card-controller/templates/renderer-via-event.js';
import { ConditionsManager } from '../condition-trigger/conditions/conditions-manager.js';
import { getConditionStateManagerViaEvent } from '../condition-trigger/conditions/state-manager-via-event.js';
import type { ConditionStateManager } from '../condition-trigger/conditions/state-manager.js';
@@ -93,11 +94,13 @@ export class AdvancedCameraCardElementsCore extends LitElement {
@property({ attribute: false })
public conditionStateManager?: ConditionStateManager;
@property({ attribute: false })
public templateRenderer?: TemplateRenderer;
@state()
private _root: HuiConditionalElement | null = null;
private _renderedElements?: PictureElements;
private _templateRenderer = new TemplateRenderer();
/**
* Create a transparent render root.
@@ -137,13 +140,11 @@ export class AdvancedCameraCardElementsCore extends LitElement {
return;
}
const elements = this._templateRenderer.renderRecursivelyAsType(
this.hass,
this.elements,
{
conditionState: this.conditionStateManager?.getState(),
},
);
const elements = this.templateRenderer
? this.templateRenderer.renderRecursivelyAsType(this.hass, this.elements, {
conditionState: this.conditionStateManager?.getState(),
})
: this.elements;
// Condition state changes won't change the actual rendered config unless
// `elements` has a template, which is more likely does not. Avoid updating
@@ -216,6 +217,9 @@ export class AdvancedCameraCardElements extends LitElement {
@property({ attribute: false })
public conditionStateManager?: ConditionStateManager;
@property({ attribute: false })
public templateRenderer?: TemplateRenderer;
private _addHandler(
target: EventTarget,
eventName: string,
@@ -298,6 +302,7 @@ export class AdvancedCameraCardElements extends LitElement {
.conditionStateManager=${this.conditionStateManager}
.hass=${this.hass}
.elements=${this.elements}
.templateRenderer=${this.templateRenderer}
>
</advanced-camera-card-elements-core>`;
}
@@ -316,6 +321,7 @@ export class AdvancedCameraCardElements extends LitElement {
export class AdvancedCameraCardElementsConditional extends LitElement {
private _config?: AdvancedCameraCardConditional;
private _conditionManager: ConditionsManager | null = null;
private _templateRenderer: TemplateRenderer | null = null;
// A note on hass as an update mechanism:
//
@@ -361,12 +367,15 @@ export class AdvancedCameraCardElementsConditional extends LitElement {
private _createConditionManager(): void {
const conditionStateManager = getConditionStateManagerViaEvent(this);
if (!this._config || !conditionStateManager) {
const templateRenderer = getTemplateRendererViaEvent(this);
if (!this._config || !conditionStateManager || !templateRenderer) {
return;
}
this._templateRenderer = templateRenderer;
this._conditionManager?.destroy();
this._conditionManager = new ConditionsManager(
this._config.conditions,
templateRenderer,
conditionStateManager,
);
this._conditionManager.addListener(() => this.requestUpdate());
@@ -377,6 +386,7 @@ export class AdvancedCameraCardElementsConditional extends LitElement {
return html` <advanced-camera-card-elements-core
.hass=${this.hass}
.elements=${this._config?.elements}
.templateRenderer=${this._templateRenderer}
>
</advanced-camera-card-elements-core>`;
}