import {
html,
LitElement,
unsafeCSS,
type CSSResultGroup,
type PropertyValues,
type TemplateResult,
} from 'lit';
import { customElement, property, state } from 'lit/decorators.js';
import { isEqual } from 'lodash-es';
import type { IssueTriggerEventData } from '../card-controller/issues/types.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';
import type {
StatusBarIcon,
StatusBarImage,
StatusBarItem,
StatusBarString,
} from '../config/schema/actions/types.js';
import type { MenuIcon } from '../config/schema/elements/custom/menu/icon.js';
import type { MenuStateIcon } from '../config/schema/elements/custom/menu/state-icon.js';
import type { MenuSubmenuSelect } from '../config/schema/elements/custom/menu/submenu-select.js';
import type { MenuSubmenu } from '../config/schema/elements/custom/menu/submenu.js';
import type { MenuItem } from '../config/schema/elements/custom/menu/types.js';
import type {
AdvancedCameraCardConditional,
PictureElements,
} from '../config/schema/elements/types.js';
import type { HomeAssistant } from '../ha/types.js';
import { localize } from '../localize/localize.js';
import elementsStyle from '../scss/elements.scss';
import { AdvancedCameraCardError } from '../types.js';
import { errorToConsole } from '../utils/basic.js';
import { fireAdvancedCameraCardEvent } from '../utils/fire-advanced-camera-card-event.js';
class ElementsCreationError extends AdvancedCameraCardError {
constructor(context?: unknown) {
super(localize('error.could_not_create_elements'), context);
}
}
/* A note on picture element rendering:
*
* To avoid needing to deal with the rendering of all the picture elements
* ourselves, instead the card relies on a stock conditional element (with no
* conditions) to render elements (this._root). This has a few advantages:
*
* - Does not depend on (much of!) an internal API -- conditional picture
* elements are unlikely to go away or change.
* - Forces usage of elements that HA understands. If the rendering is done
* directly, it is (ask me how I know!) very tempting to render things in such
* a way that a nested conditional element would not be able to render, i.e.
* the custom rendering logic would only apply at the first level.
*/
/* A note on custom elements:
*
* The native HA support for custom elements is used for the menu-icon and
* menu-state-icon elements. This ensures multi-nested conditionals will work
* correctly. These custom elements 'render' by firing events that are caught by
* the card to call for inclusion/exclusion of the menu icon in question.
*
* One major complexity here is that the top element
* will not necessarily know when a menu icon is no longer rendered because of a
* conditional that no-longer evaluates to true. As such, it cannot know when to
* signal for the menu icon removal. Furthermore, the menu icon element itself
* will only know it's been removed _after_ it's been disconnected from the DOM,
* so normal event propagation at that point will not work. Instead, we must
* catch the menu icon _addition_ and register the eventhandler for the removal
* directly on the child (which will have no parent at time of calling). That
* then triggers to re-dispatch a removal event for
* upper layers to handle correctly.
*/
interface HuiConditionalElement extends HTMLElement {
hass: HomeAssistant;
setConfig(config: unknown): void;
}
// A small wrapper around a HA conditional element used to render a set of
// picture elements.
@customElement('advanced-camera-card-elements-core')
export class AdvancedCameraCardElementsCore extends LitElement {
@property({ attribute: false })
public hass?: HomeAssistant;
@property({ attribute: false })
public elements?: PictureElements;
@property({ attribute: false })
public conditionStateManager?: ConditionStateManager;
@property({ attribute: false })
public templateRenderer?: TemplateRenderer;
@state()
private _root: HuiConditionalElement | null = null;
private _renderedElements?: PictureElements;
/**
* Create a transparent render root.
*/
createRenderRoot(): LitElement {
return this;
}
/**
* Create the root node for our picture elements.
* @returns The newly created root.
*/
private _createRoot(): HuiConditionalElement {
const elementConstructor = customElements.get('hui-conditional-element');
if (!elementConstructor || !this.hass) {
throw new ElementsCreationError(this._renderedElements);
}
const element = new elementConstructor() as HuiConditionalElement;
element.hass = this.hass;
const config = {
type: 'conditional',
conditions: [],
elements: this._renderedElements,
};
try {
element.setConfig(config);
} catch (e) {
errorToConsole(e, console.error);
throw new AdvancedCameraCardError(localize('error.invalid_elements_config'));
}
return element;
}
private _setNewRoot = (): void => {
if (!this.hass) {
return;
}
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
// the root if nothing changes.
if (this._root && isEqual(this._renderedElements, elements)) {
return;
}
try {
this._renderedElements = elements;
this._root = this._createRoot();
} catch (e) {
errorToConsole(e);
fireAdvancedCameraCardEvent(this, 'issue:trigger', {
key: 'config_error',
error: new ElementsCreationError(elements),
});
}
};
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();
}
}
protected render(): TemplateResult | void {
return html`${this._root || ''}`;
}
protected updated(): void {
if (this.hass && this._root) {
// Always update hass. It is used as a trigger to re-evaluate conditions
// down the chain, see the note on AdvancedCameraCardElementsConditional.
this._root.hass = this.hass;
}
}
}
@customElement('advanced-camera-card-elements')
export class AdvancedCameraCardElements extends LitElement {
@property({ attribute: false })
public hass?: HomeAssistant;
@property({ attribute: false })
public elements?: PictureElements;
@property({ attribute: false })
public conditionStateManager?: ConditionStateManager;
@property({ attribute: false })
public templateRenderer?: TemplateRenderer;
private _addHandler(
target: EventTarget,
eventName: string,
handler: (ev: Event) => void,
) {
// Ensure listener is only attached 1 time by removing it first.
target.removeEventListener(eventName, handler);
target.addEventListener(eventName, handler);
}
private _menuRemoveHandler = (ev: Event): void => {
// Re-dispatch event from this element (instead of the disconnected one, as
// there is no parent of the disconnected element).
fireAdvancedCameraCardEvent