Better integrate elements into stock HA custom element support.

This commit is contained in:
Dermot Duffy
2021-10-09 15:52:52 -07:00
parent 49455ab741
commit 9a915af390
7 changed files with 201 additions and 80 deletions
+19 -5
View File
@@ -222,18 +222,18 @@ This card supports all [Picture Elements](https://www.home-assistant.io/lovelace
| Element name | Description | | Element name | Description |
| ------------- | --------------------------------------------- | | ------------- | --------------------------------------------- |
| `menu-icon` | Add an arbitrary icon to the Frigate Card menu. Configuration is ~identical to that of the [Picture elements icon](https://www.home-assistant.io/lovelace/picture-elements/#icon-element).| | `custom:frigate-card-menu-icon` | Add an arbitrary icon to the Frigate Card menu. Configuration is ~identical to that of the [Picture elements icon](https://www.home-assistant.io/lovelace/picture-elements/#icon-element).|
| `menu-state-icon` | Add a state icon to the Frigate Card menu that represents the state of a Home Assistant entity. Configuration is ~identical to that of the [Picture elements state icon](https://www.home-assistant.io/lovelace/picture-elements/#state-icon).| | `custom:frigate-card-menu-state-icon` | Add a state icon to the Frigate Card menu that represents the state of a Home Assistant entity. Configuration is ~identical to that of the [Picture elements state icon](https://www.home-assistant.io/lovelace/picture-elements/#state-icon).|
See the [action documentation](https://www.home-assistant.io/lovelace/actions/#hold-action) for more information on the action options available. See the [action documentation](https://www.home-assistant.io/lovelace/actions/#hold-action) for more information on the action options available.
#### Elements Example #### Elements Examples
Add an icon that represents the state of the `light.office_main_lights` entity, that shows more information on single click (the default action) and toggles the light on double click. Add an icon that represents the state of the `light.office_main_lights` entity, that shows more information on single click (the default action) and toggles the light on double click.
```yaml ```yaml
elements: elements:
- type: menu-state-icon - type: custom:frigate-card-menu-state-icon
entity: light.office_main_lights entity: light.office_main_lights
double_tap_action: double_tap_action:
action: toggle action: toggle
@@ -242,7 +242,7 @@ elements:
Add an icon that navigates the brower to the releases page for this card: Add an icon that navigates the brower to the releases page for this card:
```yaml ```yaml
- type: menu-icon - type: custom:frigate-card-menu-icon
icon: mdi:book icon: mdi:book
tap_action: tap_action:
action: url action: url
@@ -263,6 +263,20 @@ Add a state badge showing the temperature but hide the label text:
<img src="https://raw.githubusercontent.com/dermotduffy/frigate-hass-card/main/images/picture_elements_temperature.png" alt="Picture elements temperature example" width="400px"> <img src="https://raw.githubusercontent.com/dermotduffy/frigate-hass-card/main/images/picture_elements_temperature.png" alt="Picture elements temperature example" width="400px">
You can also have icons conditionally added to the menu, such as only showing a menu icon if a light is on:
```yaml
- type: conditional
conditions:
- entity: light.kitchen
state: 'on'
elements:
- type: custom:frigate-card-menu-state-icon
entity: light.kitchen
tap_action:
action: toggle
```
<a name="views"></a> <a name="views"></a>
## Views ## Views
+13 -10
View File
@@ -19,7 +19,11 @@ import {
} from 'custom-card-helpers'; } from 'custom-card-helpers';
import screenfull from 'screenfull'; import screenfull from 'screenfull';
import { entitySchema, frigateCardConfigSchema, Message } from './types'; import {
entitySchema,
frigateCardConfigSchema,
Message,
} from './types';
import type { import type {
BrowseMediaQueryParameters, BrowseMediaQueryParameters,
Entity, Entity,
@@ -204,14 +208,6 @@ export class FrigateCard extends LitElement {
icon: screenfull.isFullscreen ? 'mdi:fullscreen-exit' : 'mdi:fullscreen', icon: screenfull.isFullscreen ? 'mdi:fullscreen-exit' : 'mdi:fullscreen',
}); });
} }
const elements = this.config.elements || [];
for (let i = 0; this._hass && i < elements.length; i++) {
const element = elements[i];
if (element.type == 'menu-icon' || element.type == 'menu-state-icon') {
buttons.push(element);
}
}
return buttons; return buttons;
} }
@@ -573,7 +569,7 @@ export class FrigateCard extends LitElement {
this._frigateCameraName = await this._getFrigateCameraName(); this._frigateCameraName = await this._getFrigateCameraName();
} }
const mediaQueryParameters = this._getBrowseMediaQueryParameters(); const mediaQueryParameters = this._getBrowseMediaQueryParameters();
if (!this._frigateCameraName || !mediaQueryParameters) { if (!this._hass || !this._frigateCameraName || !mediaQueryParameters) {
return this._setMessageAndUpdate({ return this._setMessageAndUpdate({
message: localize('error.no_frigate_camera_name'), message: localize('error.no_frigate_camera_name'),
type: 'error', type: 'error',
@@ -629,6 +625,13 @@ export class FrigateCard extends LitElement {
<frigate-card-elements <frigate-card-elements
.hass=${this._hass} .hass=${this._hass}
.pictureElements=${this.config.elements} .pictureElements=${this.config.elements}
@frigate-card:message=${this._messageHandler}
@frigate-card:menu-add=${(e) => {
this._menu.addButton(e.detail);
}}
@frigate-card:menu-remove=${(e) => {
this._menu.removeButton(e.detail);
}}
> >
</frigate-card-elements> </frigate-card-elements>
</div> </div>
+124 -58
View File
@@ -2,91 +2,136 @@ import { LitElement, TemplateResult, html, CSSResultGroup, unsafeCSS } from 'lit
import { HomeAssistant } from 'custom-card-helpers'; import { HomeAssistant } from 'custom-card-helpers';
import { customElement, property } from 'lit/decorators'; import { customElement, property } from 'lit/decorators';
import { ExtendedHomeAssistant, PictureElement, PictureElements } from '../types'; import { ExtendedHomeAssistant, MenuButton, MenuIcon, MenuStateIcon, menuStateIconSchema, PictureElements } from '../types';
import { menuIconSchema } from '../types'
import { dispatchErrorMessageEvent, dispatchEvent, getParseErrorKeys } from '../common';
import elementsStyle from '../scss/elements.scss'; import elementsStyle from '../scss/elements.scss';
import { localize } from '../localize/localize';
import { z } from 'zod';
/* 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 <frigate-card-elements> 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 <frigate-card-elements> to re-dispatch a removal event for
* upper layers to handle correctly.
*/
@customElement('frigate-card-elements') @customElement('frigate-card-elements')
export class FrigateCardElements extends LitElement { export class FrigateCardElements extends LitElement {
@property({ attribute: false }) @property({ attribute: false })
protected _pictureElements: PictureElements; protected pictureElements: PictureElements;
protected _hass!: HomeAssistant & ExtendedHomeAssistant; protected _hass!: HomeAssistant & ExtendedHomeAssistant;
protected _elements: HTMLElement[] = []; protected _root: HTMLElement | null = null;
set hass(hass: HomeAssistant & ExtendedHomeAssistant) { set hass(hass: HomeAssistant & ExtendedHomeAssistant) {
for (let i = 0; hass && i < this._elements.length; i++) { if (this._root) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any (this._root as any).hass = hass;
(this._elements[i] as any).hass = hass;
} }
this._hass = hass; this._hass = hass;
} }
set pictureElements(pictureElements: PictureElements) { protected _menuRemoveHandler(ev: Event): void {
if (this._elements.length > 0) { // Re-dispatch event from this element (instead of the disconnected one, as
this._elements.forEach((el: HTMLElement) => { // there is no parent of the disconnected element).
if (el.parentElement) { dispatchEvent<MenuButton>(this, 'menu-remove', (ev as CustomEvent).detail);
el.parentElement.removeChild(el); }
}
}); protected _menuAddHandler(ev: Event): void {
this._elements = []; ev = ev as CustomEvent<MenuButton>;
} const path = ev.composedPath()
if (!pictureElements) { if (!path.length) {
return; return;
} }
for (let i = 0; i < pictureElements.length && pictureElements[i]; i++) {
const element = this._createPictureElement(pictureElements[i]); // See 'A note on custom elements' above to explain what's going on here.
if (element) {
this._elements.push(element); // Ensure listener is only attached 1 time by removing it first.
} path[0].removeEventListener(
'frigate-card:menu-remove',
this._menuRemoveHandler.bind(this));
path[0].addEventListener(
'frigate-card:menu-remove',
this._menuRemoveHandler.bind(this));
}
connectedCallback(): void {
super.connectedCallback();
// Catch icons being added to the menu (so their removal can be subsequently
// handled).
this.addEventListener(
'frigate-card:menu-add',
this._menuAddHandler,
);
if (!this._root) {
this._createRoot();
} }
} }
@property({ attribute: false }) disconnectedCallback(): void {
protected _createPictureElement(pictureElement: PictureElement): HTMLElement | null { this.removeEventListener(
let customElementName: string | null = null; 'frigate-card:menu-add',
this._menuAddHandler,
switch (pictureElement.type) { );
case 'state-badge': super.disconnectedCallback();
case 'state-icon': }
case 'state-label':
case 'service-button':
case 'icon':
case 'image':
case 'conditional':
customElementName = `hui-${pictureElement.type}-element`;
break;
}
if (!customElementName) {
return null;
}
protected _createRoot(): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const elementConstructor = customElements.get(customElementName) as any; const elementConstructor = customElements.get('hui-conditional-element') as any;
if (!elementConstructor) { if (!elementConstructor) {
return null; return;
} }
const element = new elementConstructor(); const element = new elementConstructor();
element.hass = this._hass; element.hass = this._hass;
const config = {
type: 'conditional',
conditions: [],
elements: this.pictureElements,
}
try { try {
element.setConfig(pictureElement); element.setConfig(config);
} catch (e) { } catch (e) {
console.error(e, (e as Error).stack); console.error(e, (e as Error).stack);
return null; return;
} }
element.classList.add('element'); this._root = element;
const targetStyle = pictureElement.style || {};
Object.keys(targetStyle).forEach((prop) => {
element.style.setProperty(prop, targetStyle[prop]);
});
return element;
} }
protected render(): TemplateResult { protected render(): TemplateResult {
return html`${this._elements.map((element) => element)}`; return html`${this._root || ''}`;
} }
static get styles(): CSSResultGroup { static get styles(): CSSResultGroup {
@@ -94,10 +139,31 @@ export class FrigateCardElements extends LitElement {
} }
} }
export function renderFrigateCardElements( export class FrigateCardElementsBaseMenuIcon<T> extends LitElement {
hass: HomeAssistant & ExtendedHomeAssistant, @property({ attribute: false })
pictureElements: PictureElements, protected _config: T | null = null;
): TemplateResult {
return html` <frigate-card-elements .hass=${hass} .pictureElements=${pictureElements}> public setConfig(config: T): void {
</frigate-card-elements>`; this._config = config;
}
connectedCallback(): void {
super.connectedCallback()
if (this._config) {
dispatchEvent<T>(this, 'menu-add', this._config);
}
}
disconnectedCallback(): void {
if (this._config) {
dispatchEvent<T>(this, 'menu-remove', this._config);
}
super.disconnectedCallback()
}
} }
@customElement('frigate-card-menu-icon')
export class FrigateCardElementsMenuIcon extends FrigateCardElementsBaseMenuIcon<MenuIcon> {}
@customElement('frigate-card-menu-state-icon')
export class FrigateCardElementsMenuStateIcon extends FrigateCardElementsBaseMenuIcon<MenuStateIcon> {}
+13 -3
View File
@@ -33,6 +33,16 @@ export class FrigateCardMenu extends LitElement {
@property({ attribute: false }) @property({ attribute: false })
public buttons: MenuButton[] = []; public buttons: MenuButton[] = [];
public addButton(button: MenuButton): void {
if (!this.buttons.includes(button)) {
this.buttons = [...this.buttons, button];
}
}
public removeButton(target: MenuButton): void {
this.buttons = this.buttons.filter(button => button != target);
}
// Call the callback. // Call the callback.
protected _callAction(ev: CustomEvent, button: MenuButton): void { protected _callAction(ev: CustomEvent, button: MenuButton): void {
if (this.menuMode.startsWith('hidden-')) { if (this.menuMode.startsWith('hidden-')) {
@@ -53,7 +63,7 @@ export class FrigateCardMenu extends LitElement {
protected shouldUpdate(changedProps: PropertyValues): boolean { protected shouldUpdate(changedProps: PropertyValues): boolean {
const oldHass = changedProps.get('hass') as HomeAssistant | undefined; const oldHass = changedProps.get('hass') as HomeAssistant | undefined;
if (!oldHass) { if (changedProps.size > 1 || !oldHass) {
return true; return true;
} }
@@ -61,7 +71,7 @@ export class FrigateCardMenu extends LitElement {
const entities: string[] = [] const entities: string[] = []
for (let i = 0; i < this.buttons.length; i++) { for (let i = 0; i < this.buttons.length; i++) {
const button = this.buttons[i]; const button = this.buttons[i];
if (button.type == 'menu-state-icon') { if (button.type == 'custom:frigate-card-menu-state-icon') {
entities.push(button.entity); entities.push(button.entity);
} }
} }
@@ -76,7 +86,7 @@ export class FrigateCardMenu extends LitElement {
let icon = button.icon; let icon = button.icon;
const style = ('style' in button ? button.style : {}) || {}; const style = ('style' in button ? button.style : {}) || {};
if (button.type === 'menu-state-icon') { if (button.type === 'custom:frigate-card-menu-state-icon') {
state = this.hass.states[button.entity]; state = this.hass.states[button.entity];
emphasize = emphasize =
!!state && button.state_color && ['on', 'active', 'home'].includes(state.state); !!state && button.state_color && ['on', 'active', 'home'].includes(state.state);
+8
View File
@@ -1,4 +1,12 @@
.element { .element {
position: absolute; position: absolute;
transform: translate(-50%, -50%); transform: translate(-50%, -50%);
}
// Errors encountered by HA (not the card) during parsing of the configuration
// (e.g. custom picture element that does not exist).
hui-error-card.element {
inset: 0px;
background-color: var(--secondary-background-color, black);
transform: unset;
} }
+7
View File
@@ -3,6 +3,13 @@
:host { :host {
overflow: auto; overflow: auto;
-ms-overflow-style: none; /* Hide scrollbar: IE and Edge */
scrollbar-width: none; /* Hide scrollbar: Firefox */
}
/* Hide scrollbar for Chrome, Safari and Opera */
:host::-webkit-scrollbar {
display: none;
} }
.frigate-card-gallery { .frigate-card-gallery {
+17 -4
View File
@@ -114,6 +114,10 @@ const elementsBaseSchema = z.object({
/** /**
* Picture Element Types * Picture Element Types
*
* All picture element types are validated (not just the Frigate card custom
* ones) as a convenience to present the user with a consistent error display
* up-front regardless of where they made their error.
*/ */
// https://www.home-assistant.io/lovelace/picture-elements/#state-badge // https://www.home-assistant.io/lovelace/picture-elements/#state-badge
@@ -188,19 +192,27 @@ const conditionalSchema = elementsBaseSchema.merge(
elements: z.lazy(() => pictureElementsSchema), elements: z.lazy(() => pictureElementsSchema),
})); }));
// https://www.home-assistant.io/lovelace/picture-elements/#custom-elements
const customSchema = z.object({
// Insist that Frigate card custom elements are handled by other schemas.
type: z.string().regex(/^custom:(?!frigate-card).+/),
}).passthrough();
/** /**
* Menu Element Types * Menu Element Types
*/ */
const menuIconSchema = iconSchema.merge( export const menuIconSchema = iconSchema.merge(
z.object({ z.object({
type: z.literal('menu-icon'), type: z.literal('custom:frigate-card-menu-icon'),
})); }));
export type MenuIcon = z.infer<typeof menuIconSchema>;
const menuStateIconSchema = stateIconSchema.merge( export const menuStateIconSchema = stateIconSchema.merge(
z.object({ z.object({
type: z.literal('menu-state-icon'), type: z.literal('custom:frigate-card-menu-state-icon'),
})); }));
export type MenuStateIcon = z.infer<typeof menuStateIconSchema>;
// Schema for card (non-user configured) menu icons. // Schema for card (non-user configured) menu icons.
const internalMenuIconSchema = z const internalMenuIconSchema = z
@@ -231,6 +243,7 @@ const pictureElementSchema = z.union([
iconSchema, iconSchema,
imageSchema, imageSchema,
conditionalSchema, conditionalSchema,
customSchema,
]); ]);
export type PictureElement = z.infer<typeof pictureElementSchema>; export type PictureElement = z.infer<typeof pictureElementSchema>;