import {
CSSResultGroup,
html,
LitElement,
PropertyValues,
TemplateResult,
unsafeCSS,
} from 'lit';
import { customElement, property, state } from 'lit/decorators.js';
import { dispatchAdvancedCameraCardErrorEvent } from '../components-lib/message/dispatch.js';
import { ConditionsManager } from '../conditions/conditions-manager.js';
import { getConditionStateManagerViaEvent } from '../conditions/state-manager-via-event.js';
import {
StatusBarIcon,
StatusBarImage,
StatusBarItem,
StatusBarString,
} from '../config/schema/actions/types.js';
import { MenuIcon } from '../config/schema/elements/custom/menu/icon.js';
import { MenuStateIcon } from '../config/schema/elements/custom/menu/state-icon.js';
import { MenuSubmenuSelect } from '../config/schema/elements/custom/menu/submenu-select.js';
import { MenuSubmenu } from '../config/schema/elements/custom/menu/submenu.js';
import { MenuItem } from '../config/schema/elements/custom/menu/types.js';
import {
AdvancedCameraCardConditional,
PictureElements,
} from '../config/schema/elements/types.js';
import { 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';
/* 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 elements?: PictureElements;
protected _root: HuiConditionalElement | null = null;
@property({ attribute: false })
public hass?: HomeAssistant;
/**
* Create a transparent render root.
*/
createRenderRoot(): LitElement {
return this;
}
/**
* Create the root node for our picture elements.
* @returns The newly created root.
*/
protected _createRoot(): HuiConditionalElement {
const elementConstructor = customElements.get('hui-conditional-element');
if (!elementConstructor || !this.hass) {
throw new Error(localize('error.could_not_render_elements'));
}
const element = new elementConstructor() as HuiConditionalElement;
element.hass = this.hass;
const config = {
type: 'conditional',
conditions: [],
elements: this.elements,
};
try {
element.setConfig(config);
} catch (e) {
errorToConsole(e as Error, console.error);
throw new AdvancedCameraCardError(localize('error.invalid_elements_config'));
}
return element;
}
/**
* Create the root as necessary prior to rendering.
*/
protected willUpdate(changedProps: PropertyValues): void {
try {
// 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.elements && (!this._root || changedProps.has('elements'))) {
this._root = this._createRoot();
}
} catch (e) {
return dispatchAdvancedCameraCardErrorEvent(this, e as AdvancedCameraCardError);
}
}
/**
* Render the elements.
* @returns A rendered template or void.
*/
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;
}
}
}
/**
* The master class, handles event listeners and styles.
*/
@customElement('advanced-camera-card-elements')
export class AdvancedCameraCardElements extends LitElement {
@property({ attribute: false })
public hass?: HomeAssistant;
@property({ attribute: false })
public elements: PictureElements;
protected _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);
}
protected _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