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)_
328 lines
10 KiB
TypeScript
328 lines
10 KiB
TypeScript
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
|
|
|
import { TemplateManager } from '../../../src/card-controller/templates';
|
|
import { ConditionsManager } from '../../../src/condition-trigger/conditions/conditions-manager';
|
|
import { ConditionStateManager } from '../../../src/condition-trigger/conditions/state-manager';
|
|
import {
|
|
createHASS,
|
|
createMockTemplateRenderer,
|
|
createStateEntity,
|
|
} from '../../test-utils';
|
|
|
|
// A mock renderer for the orchestration tests, which never render templates.
|
|
// The `enabled` template suite below uses its own real, loaded engine.
|
|
const templateManager = createMockTemplateRenderer();
|
|
|
|
// Per-condition-type evaluation is covered by tests/conditions/conditions/<type>.test.ts.
|
|
// This file covers the manager's own orchestration: building/destroying evaluators,
|
|
// listener management, trigger-data merging, and notifying (or not) on changes.
|
|
|
|
// @vitest-environment jsdom
|
|
describe('ConditionsManager', () => {
|
|
afterEach(() => {
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
it('should not call listeners for HA state changes without a relevant condition', () => {
|
|
const stateManager = new ConditionStateManager();
|
|
const manager = new ConditionsManager(
|
|
[
|
|
{
|
|
condition: 'fullscreen' as const,
|
|
fullscreen: true,
|
|
},
|
|
],
|
|
templateManager,
|
|
stateManager,
|
|
);
|
|
|
|
const listener = vi.fn();
|
|
manager.addListener(listener);
|
|
|
|
stateManager.setState({
|
|
hass: createHASS({ 'sensor.foo': createStateEntity({ state: '11' }) }),
|
|
});
|
|
|
|
expect(listener).not.toBeCalled();
|
|
});
|
|
|
|
it('should forward the triggering state change to listeners', () => {
|
|
const stateManager = new ConditionStateManager();
|
|
const manager = new ConditionsManager(
|
|
[{ condition: 'fullscreen' as const, fullscreen: true }],
|
|
templateManager,
|
|
stateManager,
|
|
);
|
|
|
|
const listener = vi.fn();
|
|
manager.addListener(listener);
|
|
|
|
stateManager.setState({ fullscreen: true });
|
|
|
|
// The change that prompted the evaluation is passed through verbatim.
|
|
expect(listener).toHaveBeenLastCalledWith(expect.anything(), {
|
|
old: {},
|
|
change: { fullscreen: true },
|
|
new: { fullscreen: true },
|
|
});
|
|
});
|
|
|
|
it('should re-evaluate and notify when a subscribed condition source changes', () => {
|
|
const addEventListener = vi.fn();
|
|
const removeEventListener = vi.fn();
|
|
vi.spyOn(window, 'matchMedia')
|
|
.mockReturnValueOnce({
|
|
addEventListener: addEventListener,
|
|
removeEventListener: removeEventListener,
|
|
} as unknown as MediaQueryList)
|
|
.mockReturnValueOnce({
|
|
matches: false,
|
|
} as unknown as MediaQueryList)
|
|
.mockReturnValueOnce({
|
|
matches: true,
|
|
} as unknown as MediaQueryList);
|
|
|
|
const manager = new ConditionsManager(
|
|
[{ condition: 'screen' as const, media_query: 'whatever' }],
|
|
templateManager,
|
|
);
|
|
|
|
const listener = vi.fn();
|
|
manager.addListener(listener);
|
|
|
|
// Fire the media-query change; the manager re-evaluates and notifies.
|
|
addEventListener.mock.calls[0][1]();
|
|
expect(listener).toBeCalledWith({ result: true }, undefined);
|
|
|
|
// Destroy tears the subscription down.
|
|
manager.destroy();
|
|
expect(removeEventListener).toBeCalled();
|
|
});
|
|
|
|
describe('should handle listeners correctly', () => {
|
|
it('should add listener', () => {
|
|
const stateManager = new ConditionStateManager();
|
|
const manager = new ConditionsManager(
|
|
[{ condition: 'fullscreen' as const, fullscreen: true }],
|
|
templateManager,
|
|
stateManager,
|
|
);
|
|
|
|
const listener = vi.fn();
|
|
manager.addListener(listener);
|
|
|
|
stateManager.setState({ fullscreen: true });
|
|
|
|
expect(listener).toBeCalledWith({ result: true }, expect.anything());
|
|
expect(listener).toBeCalledTimes(1);
|
|
|
|
stateManager.setState({ fullscreen: false });
|
|
expect(listener).toBeCalledWith({ result: false }, expect.anything());
|
|
expect(listener).toBeCalledTimes(2);
|
|
|
|
// Re-add the same listener (will still only be called once).
|
|
manager.addListener(listener);
|
|
|
|
stateManager.setState({ fullscreen: true });
|
|
|
|
expect(listener).toBeCalledWith({ result: true }, expect.anything());
|
|
expect(listener).toBeCalledTimes(3);
|
|
});
|
|
|
|
it('should remove listener', () => {
|
|
const stateManager = new ConditionStateManager();
|
|
const manager = new ConditionsManager(
|
|
[{ condition: 'fullscreen' as const, fullscreen: true }],
|
|
templateManager,
|
|
stateManager,
|
|
);
|
|
|
|
const listener = vi.fn();
|
|
manager.addListener(listener);
|
|
manager.removeListener(listener);
|
|
|
|
stateManager.setState({ fullscreen: true });
|
|
|
|
expect(listener).not.toBeCalled();
|
|
});
|
|
|
|
it('should remove listener on destroy', () => {
|
|
const stateManager = new ConditionStateManager();
|
|
const manager = new ConditionsManager(
|
|
[{ condition: 'fullscreen' as const, fullscreen: true }],
|
|
templateManager,
|
|
stateManager,
|
|
);
|
|
|
|
const listener = vi.fn();
|
|
manager.addListener(listener);
|
|
manager.destroy();
|
|
|
|
stateManager.setState({ fullscreen: true });
|
|
|
|
expect(listener).not.toBeCalled();
|
|
});
|
|
|
|
it('should not call listeners when the condition result does not change', () => {
|
|
const stateManager = new ConditionStateManager();
|
|
const manager = new ConditionsManager(
|
|
[{ condition: 'view' as const, views: ['live'] }],
|
|
templateManager,
|
|
stateManager,
|
|
);
|
|
|
|
const listener = vi.fn();
|
|
manager.addListener(listener);
|
|
|
|
stateManager.setState({ view: 'live' });
|
|
expect(listener).toBeCalledTimes(1);
|
|
|
|
stateManager.setState({ view: 'clip' });
|
|
expect(listener).toBeCalledTimes(2);
|
|
|
|
stateManager.setState({ view: 'clip' });
|
|
expect(listener).toBeCalledTimes(2);
|
|
|
|
stateManager.setState({ view: 'live' });
|
|
expect(listener).toBeCalledTimes(3);
|
|
|
|
stateManager.setState({ view: 'live' });
|
|
expect(listener).toBeCalledTimes(3);
|
|
});
|
|
});
|
|
|
|
describe('enabled', () => {
|
|
const ENABLED_TEMPLATE = '{{ is_state("binary_sensor.flag", "on") }}';
|
|
|
|
// These cases gate on a rendered `enabled` template, so use a real engine
|
|
// loaded for the synchronous renderer (rather than the shared mock).
|
|
const templateManager = new TemplateManager();
|
|
beforeAll(async () => {
|
|
await templateManager.loadRenderer();
|
|
});
|
|
|
|
it('should ignore a disabled condition', () => {
|
|
const stateManager = new ConditionStateManager();
|
|
const manager = new ConditionsManager(
|
|
[{ condition: 'fullscreen' as const, fullscreen: true, enabled: false }],
|
|
templateManager,
|
|
stateManager,
|
|
);
|
|
|
|
// The disabled condition is ignored, so with no remaining conditions the
|
|
// result is true even though fullscreen does not match.
|
|
stateManager.setState({ fullscreen: false });
|
|
|
|
expect(manager.getEvaluation()).toEqual({ result: true });
|
|
});
|
|
|
|
it('should evaluate an enabled condition normally', () => {
|
|
const stateManager = new ConditionStateManager();
|
|
const manager = new ConditionsManager(
|
|
[{ condition: 'fullscreen' as const, fullscreen: true, enabled: true }],
|
|
templateManager,
|
|
stateManager,
|
|
);
|
|
|
|
stateManager.setState({ fullscreen: false });
|
|
expect(manager.getEvaluation()).toEqual({ result: false });
|
|
|
|
stateManager.setState({ fullscreen: true });
|
|
expect(manager.getEvaluation()).toEqual({ result: true });
|
|
});
|
|
|
|
it('should drop a condition whose enabled template does not render true', () => {
|
|
const stateManager = new ConditionStateManager();
|
|
stateManager.setState({
|
|
hass: createHASS({ 'binary_sensor.flag': createStateEntity({ state: 'off' }) }),
|
|
});
|
|
const manager = new ConditionsManager(
|
|
[
|
|
{
|
|
condition: 'fullscreen' as const,
|
|
fullscreen: true,
|
|
enabled: ENABLED_TEMPLATE,
|
|
},
|
|
],
|
|
templateManager,
|
|
stateManager,
|
|
);
|
|
|
|
stateManager.setState({ fullscreen: false });
|
|
|
|
expect(manager.getEvaluation()).toEqual({ result: true });
|
|
});
|
|
|
|
it('should evaluate a condition whose enabled template renders true', () => {
|
|
const stateManager = new ConditionStateManager();
|
|
stateManager.setState({
|
|
hass: createHASS({ 'binary_sensor.flag': createStateEntity({ state: 'on' }) }),
|
|
});
|
|
const manager = new ConditionsManager(
|
|
[
|
|
{
|
|
condition: 'fullscreen' as const,
|
|
fullscreen: true,
|
|
enabled: ENABLED_TEMPLATE,
|
|
},
|
|
],
|
|
templateManager,
|
|
stateManager,
|
|
);
|
|
|
|
stateManager.setState({ fullscreen: false });
|
|
|
|
expect(manager.getEvaluation()).toEqual({ result: false });
|
|
});
|
|
|
|
it('should keep a condition enabled when its template cannot render without hass', () => {
|
|
const stateManager = new ConditionStateManager();
|
|
const manager = new ConditionsManager(
|
|
[
|
|
{
|
|
condition: 'fullscreen' as const,
|
|
fullscreen: true,
|
|
enabled: ENABLED_TEMPLATE,
|
|
},
|
|
],
|
|
templateManager,
|
|
stateManager,
|
|
);
|
|
|
|
stateManager.setState({ fullscreen: false });
|
|
|
|
// With no hass the enabled template cannot render, so the gate stays
|
|
// enabled and the condition is evaluated (here: fullscreen is false).
|
|
expect(manager.getEvaluation()).toEqual({ result: false });
|
|
});
|
|
|
|
it('should re-evaluate the enabled template on each evaluation', () => {
|
|
const stateManager = new ConditionStateManager();
|
|
stateManager.setState({
|
|
hass: createHASS({ 'binary_sensor.flag': createStateEntity({ state: 'off' }) }),
|
|
fullscreen: false,
|
|
});
|
|
const manager = new ConditionsManager(
|
|
[
|
|
{
|
|
condition: 'fullscreen' as const,
|
|
fullscreen: true,
|
|
enabled: ENABLED_TEMPLATE,
|
|
},
|
|
],
|
|
templateManager,
|
|
stateManager,
|
|
);
|
|
|
|
// Flag off: the condition is disabled and ignored, so the result is true.
|
|
expect(manager.getEvaluation()).toEqual({ result: true });
|
|
|
|
// Flag on: the condition is now active and fullscreen does not match.
|
|
stateManager.setState({
|
|
hass: createHASS({ 'binary_sensor.flag': createStateEntity({ state: 'on' }) }),
|
|
});
|
|
expect(manager.getEvaluation()).toEqual({ result: false });
|
|
});
|
|
});
|
|
});
|