Card Foundation
The base classes every LCARdS card is built on:
LCARdSNativeCard(the Home Assistant card contract) andLCARdSCard(core singletons, config processing, templates, entities, actions, rules and cleanup). Source:src/base/LCARdSNativeCard.js,src/base/LCARdSCard.js,src/base/LCARdSActionHandler.jsRules for card code:.claude/rules/cards.md
Overview
A Home Assistant custom card is a custom element with setConfig(config), a hass property and getCardSize(). LCARdS splits the base into two layers:
LCARdSNativeCard(src/base/LCARdSNativeCard.js) extendsLitElementand implements that contract: a deep-clonedconfig, ahasssetter that decides whether a re-render is needed, the host size keys (height,width,min_*,max_*,overflow*,z_index), a per-instance GUID, preview-mode detection, font loading, an error state, and a set of protected hooks (_onConfigSet,_onHassChanged,_onConnected,_onDisconnected,_onFirstUpdated,_onUpdated,_renderCard,_getCardSize,_getGridOptions,_validateConfig).LCARdSCard(src/base/LCARdSCard.js) extends it with the LCARdS feature set: access to the core singletons (this._singletons), config processing throughCoreConfigManager, entity subscriptions, HASS forwarding to the core, templates, theme and colour helpers, actions (a per-cardLCARdSActionHandler), the rules integration, data source dependencies, auto-sizing, zones, segments, provenance and the cleanup on disconnect. It overrides the native hooks and exposes a second, card-facing set (_handleFirstUpdate,_handleHassUpdate,_onConfigUpdated,_onRulePatchesChanged,_processCustomTemplates,_onAlertModeChanged).
The cards on top of them:
lcards-layout-card and lcards-alert-overlay extend LitElement directly and use none of the foundation below (see Layout View and Layout Card). The layout view (lcards-layout-view) and the shell strategy are not cards (see Shell Strategy). The MSD card adds its own pipeline on top of LCARdSCard (see MSD Pipeline), and the chart and astrometrics cards have pages of their own (Charts, Astrometrics).
Required static members
export class LCARdSMyCard extends LCARdSCard {
/** CoreConfigManager schema and preset lookup key */
static CARD_TYPE = 'my-card';
/** Minimal config for the Home Assistant card picker */
static getStubConfig() {
return { type: 'custom:lcards-my-card', entity: 'light.example' };
}
/** Editors are lazy chunks: import on demand, keep them out of the main bundle */
static async getConfigElement() {
await import('../editor/cards/lcards-my-card-editor.js');
return document.createElement('lcards-my-card-editor');
}
}CARD_TYPE:_processConfigAsync()passes it toconfigManager.processConfig(rawConfig, cardType, { hass }); without it the card falls back torawConfig.typeand gets no schema validation or preset merge for its type.registerSchema()(optional static):src/lcards-main.jscalls it for each card after the core has initialised, to register the card's JSON Schema withconfigManager.registerCardSchema().- Registration: the card element is defined in
src/lcards-main.jsonly, behind acustomElements.get()guard; the card picker metadata is theLCARdSCardClassesarray in the same file, pushed once intowindow.customCards. Editors register themselves in their own file. See Adding new cards.
Lifecycle
Home Assistant creates a card, configures it, hands it hass and then attaches it. hui-card normally calls setConfig() and sets hass before the element is connected, so the first _onHassChanged() usually runs before _onConnected(), when this._singletons is still null. The base handles that order (rules and data sources are deferred to _onConnected()); card code in _handleHassUpdate() must not assume the singletons are there on the first call.
Hooks on LCARdSNativeCard
| Hook | Called from | Base behaviour |
|---|---|---|
_onConfigSet(config) | setConfig(), after the clone and validation | Applies height, width, min_height, min_width, max_height, max_width, overflow, overflow_x, overflow_y and z_index to the host style (a bare number is px); keeps the layout-card margin correction (_parentMarginV) when no height is set |
_validateConfig(config) | setConfig() | Throws when type is missing. A throw from setConfig()'s body is caught and shown as the red "LCARdS Error" box (_errorState) instead of breaking the dashboard |
_onHassChanged(newHass, oldHass) | The hass setter, when a new HASS object arrives | No-op |
_onConnected() / _onDisconnected() | connectedCallback() / disconnectedCallback() (after _cleanup()) | No-op |
_onFirstUpdated(changedProps) | firstUpdated(), after _mountResolved = true | No-op |
_onUpdated(changedProps) | updated(), when config or hass changed | No-op |
_renderCard() | render(), inside <div class="lcards-card">, once the mount is resolved and there is no error state | Placeholder text |
_getCardSize() | getCardSize() | 1 |
_getGridOptions() | getGridOptions() | {} |
render() also adds an empty .lcards-size-ref div after the card: _setupAutoSizing() observes it rather than the host, so the SVG's own pixel size never feeds back into the measured size.
Other members: getCardGuid(), isPreviewMode(), isMountResolved(), getMountElement() (the shadow root), _configPx(value) (a px number from 400, "400" or "400px", null for relative units), _checkForAncestor(tags) (walks up through shadow roots).
Hooks on LCARdSCard
LCARdSCard implements every native hook and gives subclasses these instead. Override them, call super where the table says so.
| Hook | When | Notes |
|---|---|---|
_handleFirstUpdate(changedProps) | Once, from _onFirstUpdated() after _initialized = true | Register for rules, set up actions, _setupAutoSizing(). Runs once per element: a reconnect does not call it again |
_handleHassUpdate(newHass, oldHass) | Every new HASS object, at the end of _onHassChanged() | Called even when nothing the card uses changed; check the entities you care about |
_onConfigUpdated() | After _processConfigAsync() has replaced this.config with the merged config | Re-resolve styles and caches from the merged config |
_onRulePatchesChanged() | After _applyRulePatches() changed or cleared this card's patches. No arguments | this.config already carries the patches (or is restored) |
_processCustomTemplates() | From _processTemplates(), after the icon is processed | Evaluate the card's own template fields. May return true / false (whether any result changed; button, elbow, slider) so a hass-driven pass can skip a redundant render; anything else always re-renders |
_onAlertModeChanged(mode) | When an alert mode rewrites the palette | Default: _reprocessForThemeChange() and _refreshBackgroundAnimationColors(); override for a cheaper repaint |
_getAnimationSetup() | setupActions(), rules registration, disconnect | Returns { overlayId, elementSelector }; the default scope id is lcards-card-{guid} |
_applyRuleResults(results) | After every rules callback | No-op; the MSD card applies its base_svg filters here |
_onConnected() / _onDisconnected() | As above | When overriding: call super._onConnected() first, super._onDisconnected() last |
_renderCard() | Every render | Shows "Initializing..." until _initialized; subclasses must override |
_onConnected() is async (it awaits setupHassMonitoring()), but everything up to and including _initializeSingletons() and the rules load runs synchronously, so a subclass that calls super._onConnected() without awaiting it can use this._singletons on the next line.
Config processing
setConfig() must be synchronous for Home Assistant, so LCARdSCard.setConfig() does the quick work and starts the rest in the background:
_rawConfig = config(the untouched, frozen config Home Assistant passed).super.setConfig(config):this.configbecomes a deep clone, preview mode is detected,_onConfigSet()runs with the raw config._rebaseRulePatches(): when a rule patch is active, the new config becomes the unpatched base and the patch is applied to it again (see Applying patches)._configProcessingPromise = _processConfigAsync(config), not awaited.
_onConfigSet() (LCARdSCard override) stores _entity when hass is present, sets the card's rules (or flags them for _onConnected(), see Rules), registers template data source dependencies when the singletons are ready, and processes templates (_processTemplates() before the first update, _scheduleTemplateUpdate() after).
_processConfigAsync(rawConfig) returns at once when core.configManager is not initialised, and this.config stays the plain clone. In practice it is ready: src/lcards-main.js defines the card elements only after lcardsCore.initialize() has resolved. Otherwise it awaits configManager.processConfig(rawConfig, CARD_TYPE, { hass }), which merges card defaults, theme defaults, the preset, the component and the user config with provenance (see Config Manager), and then:
- logs validation errors and warnings (it applies the merged config even when validation failed);
- drops the result when a newer run started meanwhile (
_configRunId; theme override events start new runs); - sets
this.config = result.mergedConfig, re-scans_trackedEntities, records provenance, calls_onConfigUpdated()andrequestUpdate(); - creates the card's
data_sources:(_processDataSourcesConfig(), which needsdataSourceManager;_onConnected()retries when the singletons were not ready).
Subclasses that need the merged config before they continue await this._configProcessingPromise (the chart does).
Theme changes. processConfig() bakes resolved theme: values into this.config, so a plain re-render would keep stale colours. _subscribeThemeChanges() (from _onFirstUpdated() and every _onConnected()) listens for lcards:theme-overrides-changed on window and subscribes to themeManager.subscribeToAlertMode(); both lead to _reprocessForThemeChange(), which re-runs _processConfigAsync(_rawConfig).
HASS flow
- Re-render gate. The setter always calls
_onHassChanged(), but callsrequestUpdate()only when_shouldUpdateOnHassChange()says so: on the first HASS, or when the state object ofconfig.entityor of any_trackedEntitiesentry changed (Home Assistant replaces a state object when it changes, so!==is enough). An unrelated entity change costs no render. - Forwarding to the core is gated the same way, and an entity the card holds a
subscribeToEntity()subscription to counts as well (_subscribedEntityCounts), so its callback fires even when nothing else tracks it. One forwarded HASS updates every service, andCoreSystemsManager.updateHass()diffs every watched entity (read or subscribed; it never enumerateshass.states), so changes to entities no card forwarded for are still delivered. The distribution order, the microtask deduplication and the global HASS feed for pages without cards are documented in HASS distribution and Systems Manager: HASS Update Flow. - Light colour variable.
_updateLightColorVariable()runs on every HASS the card sees (any entity), but writes--lcards-light-color-<guid>/--lcards-light-alpha-<guid>and calls_onLightColorChanged()only when the light's colour and brightness differ from what the page holds (_lightVarsKey,'off'or'colour|alpha';src/base/LCARdSCard.js:3991-4077). The button's hook re-resolves its style; colours keyed bystate_attribute/ranges_attributefollow attribute-only changes of the card's own entity through_handleHassUpdate()instead, once per update, unless_styleFollowsAttributes()returnsfalse(the slider, which resolves its own style;src/cards/lcards-button.js:343,src/cards/lcards-slider.js:592). - Synthetic HASS. A parent card may hand a child a rewritten HASS copy for that child only (the select menu does for its option buttons).
isSyntheticHass()(src/utils/synthetic-hass.js) marks it; such a copy never reaches the core or the helper manager. - Ordering.
_onHassChanged()isasync: on the first HASS it awaitssetupHassMonitoring()before it forwards and calls_handleHassUpdate().
_trackedEntities
_updateTrackedEntities() runs after every merged config and collects:
config.entity;entityofon_entity_changeanimations;when.entityof rules, including the direct children of a top-levelall/any(deeper nesting is not scanned; the Rules Engine has its own subscription, so this only affects forwarding and re-render);- every Jinja2 entity reference found in any config string (
TemplateParser.extractJinja2Entities()); - every
map_range.entityanywhere in the config; triggers_updateentries, the escape hatch for JavaScript templates ([[[...]]]is never scanned).
Subclasses extend it (super._updateTrackedEntities() first): the slider, data grid and astrometrics card add their own. An entity the card only subscribes to (the elbow's segment entities) needs no entry here: subscribeToEntity() already makes its changes reach the core, and the callback re-renders.
Entity access
// Event-driven: unsubscribed automatically on disconnect
this.subscribeToEntity(entityId, (id, newState, oldState) => {
this._value = newState?.state;
this.requestUpdate();
});
// Snapshot (cache first, then hass.states)
const state = this.getEntityState('sensor.temperature');
const own = this.getEntityState(); // config.entitysubscribeToEntity(entityId, callback)callssystemsManager.subscribeToEntity(entityId, callback, this._cardGuid), counts the entity in_subscribedEntityCounts(so a change to it is forwarded to the core, see HASS flow) and keeps a release function in_entitySubscriptions. It returns that release: it unsubscribes, removes it from the set and drops the count (the entity still gates forwarding while another subscription or the tracked set holds it); a second call does nothing. Without the singletons (before_onConnected()) it warns and returns a no-op. The callback is not called on subscribe: it fires whenCoreSystemsManager.updateHass()sees the entity change (witholdStatenullthe first time the entity enters the cache,newStatenullwhen the entity is removed). Read the current value withgetEntityState().- Reconnects.
_onDisconnected()drops every subscription, and_handleFirstUpdate()never runs again, so a card that subscribes there loses its subscriptions after the first disconnect (Home Assistant disconnects cards on edit mode, view changes and moves). Subscribe from a method you also call in_onConnected()when_initializedis true, as the elbow does for its segment entities (_subscribeSegmentEntities(),src/cards/lcards-elbow.js). this._entityis the state object ofconfig.entity, refreshed on every HASS (and fromhassin_onConfigSet()). Most cards render from it plus_trackedEntities, which already re-render the card.- Display helpers:
_getStateDisplay(entity),_getEntityName(entity),_getAttributeDisplay(key, entity)and_getAttributeName(key, entity)wrapsrc/utils/ha-entity-display.js(see Home Assistant Entity Display). Never callhass.format*()directly. - Exception: history. The chart needs history for a time window, so
src/charts/chart-series-fetcher.jssubscribes to Home Assistant'shistory/stream(andrecorder/statistics_during_period) onhass.connectionitself and stops in_onDisconnected(). See Charts.
The systems manager's cache, change detection and subscription semantics are in Systems Manager.
Templates
processTemplate(template, options)evaluates one string with all four template types (JavaScript[[[...]]], tokens{entity.state}, data sources{ds:name}, Jinja2{{ ... }}) throughUnifiedTemplateEvaluator.evaluateAsync(). Options:displayFormat(friendly,raw,parts,unit),field(provenance path),entity(evaluate against another entity,nullfor none) andextra(more names for the template)._processTemplates()runs_processIcon(), clears the style template cache (_evaluatedStyleCache) and calls_processCustomTemplates()._scheduleTemplateUpdate(reason)batches it into the next animation frame and re-renders afterwards; tracked entity changes, data source updates and config changes call it.- Skipped re-render (2026-11-17). With
reason'hass'(a change of an entity the card uses, other than the first hass, which the hass setter has already rendered), the re-render is skipped when the pass returnedfalse(no template result changed) ortrueafter the card asked for a render itself once its results were written (the button family's_onTemplatesChanged()ends inrequestUpdate(); counted in_templateRenderRequests). Every other reason, a pass that returns nothing, and two passes overlapping (_templatePassId) render as before. Buttons and sliders went from three renders per state change to two, an elbow without templates from two to one; the DOM after each change was compared with the old bundle's for every button, elbow and slider fixture. Tests:tests/browser/render-count.spec.js. _preEvaluateStyleTemplates(obj)/_resolveTemplateValue(value): evaluate Jinja2 and JavaScript templates in style values ahead of time, so the synchronous SVG builders can read the results.- Data sources in templates.
_registerTemplateDatasourceDependencies()finds{ds:...}references in the config, waits up to 5 s for each source, registers the card as a dependent (createDataSource()with the source's own config) and subscribes, so a new value schedules a template update.
Syntax and evaluator internals: Template System.
Theme, colours and presets
| Member | Purpose |
|---|---|
getThemeToken(path, fallback, usedByField) | themeManager.getToken(path, fallback), recorded in provenance |
getStylePreset(type, name) | stylePresetManager.getPreset(type, name, themeManager) |
_resolveColorValue(value, fallback) | A concrete colour (for SVG attributes, Canvas2D, anime.js): resolveColor(value, { concrete: true, element }) |
_resolveEntityStateColor(colorConfig, fallback) | A state-keyed colour map resolved for the card's entity, kept as CSS (var() stays live, so alert modes recolour without a re-render) |
_classifyEntityState(entity) / _resolveStateValue(options) | The state key (active, inactive, unavailable, ...) a state-keyed map is read with |
Colour syntax lives only in src/core/themes/color-syntax.js; see .claude/rules/state-color.md and Theme System. Theme tokens are always read through window.lcards.core.themeManager, never a module import.
Actions, sounds and services
async _handleFirstUpdate() {
super._handleFirstUpdate();
// The first render was the loading placeholder: wait for the card's own DOM
await this.updateComplete;
const el = this.shadowRoot.querySelector('.interactive');
if (!el) return;
this._actionCleanup?.();
this._actionCleanup = this.setupActions(el, {
tap_action: this.config.tap_action,
hold_action: this.config.hold_action,
double_tap_action: this.config.double_tap_action
});
}Wait for the DOM.
_handleFirstUpdate()runs fromfirstUpdated(), whose render was still the "Loading LCARdS..." placeholder:_mountResolvedturnstruethere and the card's own template renders in the next update. QueryshadowRootafterawait this.updateComplete(the button does, inlcards-button.js), or the element isnull.One handler per card. The constructor creates
this._actionHandler = new LCARdSActionHandler(); there is no shared core action handler.setupActions(element, actions, options)adds the card'sanimations,getAnimationSetup,shadowRoot, the entity (options.entityfirst, thenconfig.entity),getHassand the card-level sound overrides (_cardSoundOverride(), fromconfig.sounds), and callsthis._actionHandler.setupActions(element, actions, this.hass, options). It also registers the card's animation scope with the Animation Manager, so rules can animate the card even when it has noanimations:.Cleanup.
setupActions()returns a function that removes the listeners. The base class does not keep or call it: the listeners live on the card's own shadow DOM elements. A card that rebuilds the element or rebinds (the button does on config changes) calls the previous cleanup first._playSound(eventType)plays a sound for direct call sites (slider drags, toggles), honouringconfig.sounds.callService(domain, service, data)wrapshass.callService()with logging and error handling. Use it instead ofthis.hass.callService().
Gestures, dispatch and the supported actions: Action Handler.
Rules integration
Rules are page-wide: every card's rules: go into the one shared Rules Engine, and any rule can patch any registered card. A card takes part in two separate ways: it owns the rules in its config, and it registers itself as a target.
Owning rules
_onConfigSet()calls_loadRulesFromConfig(config.rules)on every config change when the singletons are ready, and with[]when a card that had rules has none left. Before_onConnected()it sets_hasRulesToLoadinstead, and_onConnected()loads them._loadRulesFromConfig()callsrulesEngine.setCardRules(this._cardGuid, rules, { sourceCardId, sourceCardType }): the card instance owns its rules, so a config change replaces them and an empty list removes them._ownsRulesrecords whether it holds any.- On disconnect,
_scheduleRulesRelease()removes them withremoveCardRules(this._cardGuid)afterRULES_RELEASE_MS(3000 ms, exported fromLCARdSCard.js) if the card is still disconnected._onConnected()and a later_loadRulesFromConfig()cancel the timer (_cancelRulesRelease()), so a card that Home Assistant moves or re-attaches keeps its rules; a released card sets them again on its next connect. - The card also calls
rulesEngine.setupHassMonitoring(hass)on its first HASS, and again in_onConnected()right after loading rules when HASS is already there, so the engine'sstate_changedsubscription is made once rule entities are known.
Being a target
_handleFirstUpdate() {
super._handleFirstUpdate();
this._registerOverlayForRules(this.config.id || `my-card-${this._cardGuid}`, 'my-card', this.config.tags || []);
}
_onRulePatchesChanged() {
this._resolveStyle(); // this.config now carries the patches; must end in requestUpdate()
}_registerOverlayForRules(overlayId, type, tags = []) takes positional arguments. It:
- remembers them in
_rulesRegistration, so_onConnected()registers again after a reconnect (the disconnect unregistered the card, and_handleFirstUpdate()will not run again); - returns when the singletons are missing or the card is already registered (
_overlayRegistered): one registration per card; - registers the overlay with
systemsManager.registerOverlay(overlayId, { id, type, tags, sourceCardId, animationScope }), whereanimationScopeis_getAnimationSetup().overlayId, so a rule animation aimed at the card'sidreaches the card's animation scope; - registers one callback with
rulesEngine.setReEvaluationCallback(). The callback awaitsevaluateDirty({ entity, getEntity }), then calls_applyRulePatches(results.overlayPatches)and_applyRuleResults(results); - with HASS present, calls
markAllDirty()and runs the callback once, so a rule that already matches applies on load.
Rule YAML targets the id, a tag, the type or a pattern under apply.overlays:
type: custom:lcards-button
id: bedroom_light
preset: lozenge
entity: light.bedroom
tags:
- bedroom
rules:
- id: bedroom_light_on
when:
entity: light.bedroom
state: "on"
apply:
overlays:
tag:bedroom:
style:
card:
color:
background: var(--lcars-green)Applying patches
_applyRulePatches(overlayPatches) (base behaviour; the MSD card overrides it for all its overlays):
- A patch can change any config key (
style,text,icon, ...), not onlystyle, because it is merged onto the whole config. Every cycle starts from the_baseConfigsnapshot, so patches never accumulate. - When no rule patches the card any more,
this.configis restored from the snapshot. - A new config keeps the patch. Whenever
this.configis replaced while a patch is active (setConfig(), and_processConfigAsync()committing its merged config: a theme override change, an alert mode re-process),_rebaseRulePatches()takes the new config as_baseConfig, merges the active patch onto a copy and calls_onRulePatchesChanged(). Without it the next rules callback would see the same patch, return early, and the rule styling would be gone until the patch changed. _getMergedStyleWithRules(style)deep-merges the patch'sstyle(_lastRulePatches.style) ontostyleand returns it (unchanged when there is no patch). The button, slider, chart and data grid call it as the last step of style resolution, so a rule also wins over defaults the card added after readingthis.config.style(theme tokens, state opacity). Other patched keys (text,icon, ...) are read fromthis.config. The select menu mergesthis._lastRulePatches?.styleitself._unregisterOverlayFromRules()(from_onDisconnected()) removes the callback and unregisters the overlay; when a patch is applied it restoresthis.configfrom_baseConfigfirst and calls_onRulePatchesChanged(). A reconnect registers again and snapshots that unpatched config, so a patch never sticks after the rule stops matching.- Removed rules. Removing a card's rules from the shared engine (
setCardRules(), also on a config edit that takes a rule out) runs the rules callbacks even when no rule is left dirty, so cards the rule patched restore their config.
Rendering rules for patched styles: write patched values as inline styles or attributes, not into a static <style> block, and never use !important in static CSS for properties a rule may patch.
Sizing
- Card size. Override
_getCardSize()when the card is taller than one row, e.g.return Math.ceil((this._configPx(this.config?.height) || 200) / 50);(the chart and MSD do this). - Host size keys.
height,width,min_*,max_*,overflow*andz_indexare applied to the host byLCARdSNativeCard._onConfigSet(); an explicitheight/widthsets the matchingmin-*to0px. _setupAutoSizing(onResize)(call from_handleFirstUpdate()): aResizeObserveron.lcards-size-refstoresthis._containerSize = { width, height }and callsonResize(width, height)(default:requestUpdate()). The first measurement waits one animation frame (parents such as the layout card inject margins in their own first update); later ones are debounced (150 ms) with a 2 px hysteresis. It also detects a parentcard_marginand setscalc(100% - Npx)on the host (_parentMarginV). Inside an MSDforeignObjectit locks_containerSizeto the design size instead._onConnected()re-creates the observer after a reconnect.- Sizing inside nested grids (
hui-card, layout card and view tracks) follows the rules in.claude/rules/cards.md("Sizing in Nested Grids").
Preview mode
this._isPreviewMode is set by _detectPreviewMode(): true when hui-card set .preview or .editMode on the card, the dashboard is in edit mode, the card is inside hui-card-picker or hui-dialog-edit-card, or the URL contains edit=1. It runs in setConfig() and again in LCARdSNativeCard.connectedCallback() on every connect; when the result changed, the card re-renders.
hui-card calls setConfig() (inside tryCreateCardElement()) before it sets preview on the card and before it attaches it (src/panels/lovelace/cards/hui-card.ts in the Home Assistant frontend), so on a card's first config the detection in setConfig() finds no parent and no preview property and returns false; the check on connect sees both. Subclasses that override _detectPreviewMode() (the MSD's tiers) get the same second check. Because hui-view sets preview on every card while the dashboard is in edit mode, true also means "dashboard edit mode": the select menu shows its picker placeholder only for _checkForAncestor(['hui-card-picker']) (_isInCardPicker), not for every preview.
Use it for work that is decided again later (the background renderer skips its off-screen IntersectionObserver in previews). Do not skip one-time setup in _handleFirstUpdate() on it: that hook runs once per element, and a dashboard card leaves edit mode without being created again. To skip setup only in the card picker, which a card never leaves:
_handleFirstUpdate() {
super._handleFirstUpdate();
if (this._checkForAncestor(['hui-card-picker'])) return;
this._startExpensiveSetup();
}The MSD card overrides _detectPreviewMode() and returns 'picker' / 'editor' instead of true; only lcards-msd.js relies on that form.
Zones and segments
- Zones are named rectangles text fields are placed in (
zone: <name>). Cards override_calculateZones(width, height)and call_rebuildZones(width, height)at the top of each render, which recalculates and merges user zones (_mergeUserZones())._generateZoneTextMarkup(),_generateZoneDebugMarkup()and_injectTextFieldsToElement()are defined onLCARdSButton(so the button, elbow and slider have them), not onLCARdSCard. - Segments:
_extractSegmentIds(),_processSegmentConfig(),_setupSegmentInteractivity()and_attachSegmentActions()give each SVG element with an id its own style and actions (button component mode).
See .claude/rules/cards.md ("Zone System") for the rules.
Cleanup on disconnect
LCARdSNativeCard.disconnectedCallback() calls _cleanup() (removes the font loadingdone listener), then _onDisconnected(). LCARdSCard._onDisconnected() then:
- removes the card from
LCARdSCard.findByConfig()'s set of connected cards; - unsubscribes data source subscriptions and removes the card from each data source it registered with (
removeCardFromSource()); - unsubscribes every
subscribeToEntity()subscription; - unregisters from rules (
_unregisterOverlayFromRules()) and schedules the release of its own rules (_scheduleRulesRelease()); - removes the light colour CSS variable and clears
_lightVarsKey, so a reconnect writes it again; - disconnects the
ResizeObserverand the window resize fallback; - drops the theme override listener and the alert-mode subscription;
- calls
core.unregisterCard(this._cardGuid)(which also unregisters it from the systems manager); - destroys the default animation scope (
animationManager.destroyOverlayScope(_getAnimationSetup().overlayId)); cards with more scopes (button, slider, MSD) destroy their own.
Cards override _onDisconnected() only for their own resources (timers, AbortControllers, third-party instances, the chart's series fetcher) and call super._onDisconnected() last. They must not repeat the calls above.
Everything set up in _handleFirstUpdate() that the list removes must be set up again in _onConnected() when _initialized is true. The base already does this for rules registration, auto-sizing, theme subscriptions, data sources and singletons; card-level entity subscriptions are the card's job (see Entity access).
Adding a new card
- Create
src/cards/lcards-mycard.jsextendingLCARdSCard, withstatic CARD_TYPE,static getStubConfig()and a lazystatic getConfigElement(). - Create the editor at
src/editor/cards/lcards-mycard-editor.jsextendingLCARdSBaseEditor; it registers its own element behind acustomElements.get()guard. - Register the card element in
src/lcards-main.jswith the guard, add{ type, name, description, ... }toLCARdSCardClassesthere, and call yourregisterSchema()with the others. - Add the schema to
scripts/lib/card-schemas.js(doc validation, description check, published schema); every property needs adescription. - Override
_getCardSize()when the card has a pixel height. - Run
npm run buildand test in Home Assistant.
Debugging
window.lcards.setGlobalLogLevel('debug'); // every [LCARdSCard] / [RulesEngine] log line
window.lcards.core.systemsManager.getEntityState('light.bedroom');
window.lcards.core.rulesManager.rules; // every loaded rule, with _sourceCardId- A card's merged config and where each value came from:
card.getProvenance(),card.debugProvenance(),card.printConfigTree()(see Config Manager). - The rules a card currently receives:
card._lastRulePatches; its registration:card._overlayId,card._rulesRegistration. - Rule evaluation traces and the console API are in Rules Engine: Console access.
API reference
LCARdSCard state
| Property | Type | Description |
|---|---|---|
config | Object | The working config: the deep clone from setConfig(), replaced by the merged config, then patched by rules |
_rawConfig | Object | The config Home Assistant passed (frozen) |
_entity | Object | null | State object of config.entity |
_singletons | Object | null | { systemsManager, themeManager, rulesEngine, animationManager, dataSourceManager, validationService, stylePresetManager }, set in _onConnected() (_initializeSingletons()). rulesEngine is core.rulesManager |
_initialized | boolean | true from the first update on |
_trackedEntities | string[] | Entities that re-render the card and forward HASS to the core |
_entitySubscriptions | Set<Function> | Unsubscribe functions of subscribeToEntity() |
_actionHandler | LCARdSActionHandler | This card's action handler |
_overlayId, _overlayTags | string, string[] | The rules registration of this card |
_overlayRegistered | boolean | Registered as a rules target |
_rulesRegistration | Object | null | The last _registerOverlayForRules() arguments, for reconnects |
_ownsRules, _hasRulesToLoad | boolean | This card's rules are in the engine / are waiting for _onConnected() |
_lastRulePatches | Object | null | The merged rule patch currently applied |
_baseConfig | Object | null | config without the active patch (taken on the first patch, renewed when the config is replaced), restored when patches clear or the card disconnects |
_containerSize | { width, height } | Last measured size (with _setupAutoSizing()) |
_configProcessingPromise | Promise | The running _processConfigAsync() |
LCARdSCard methods
| Method | Returns | Description |
|---|---|---|
getEntityState(entityId?) | Object | null | Cached state (systems manager), else hass.states; defaults to config.entity |
subscribeToEntity(entityId, callback) | Function | Subscribe; auto-unsubscribed on disconnect |
callService(domain, service, data?) | Promise | Service call with logging |
setupActions(element, actions, options?) | Function | Tap, hold, double-tap, hover; returns the cleanup |
processTemplate(template, options?) | Promise<string> | Evaluate all four template types |
getThemeToken(path, fallback?, usedByField?) | any | Theme token, recorded in provenance |
getStylePreset(type, name) | Object | null | A style preset |
_registerOverlayForRules(overlayId, type, tags?) | void | Register as a rules target (once per card) |
_getMergedStyleWithRules(style) | Object | style deep-merged with the current rule patch's style (see Applying patches) |
_rebaseRulePatches() | void | After this.config was replaced: new base snapshot, active patch applied again |
_applyRulePatches(overlayPatches) | void | Apply this card's patches to config (see above) |
_setupAutoSizing(onResize?) | void | Container size tracking |
_rebuildZones(width, height) | void | Recalculate zones before rendering |
getProvenance(path?), debugProvenance(), printConfigTree() | various | Provenance inspection |
static findByConfig(config) | LCARdSCard | null | The connected card rendered from this config (the editor preview when there are two) |
See also
- Core Subsystems (initialization order, HASS distribution)
- Systems Manager
- Rules Engine
- Action Handler
- Animation Manager
- Config Manager
- Template System
- Theme System