From 7f76543bbd26f95b30c6ae0738f5e5f2258af4ea Mon Sep 17 00:00:00 2001 From: Dermot Duffy Date: Sat, 9 Oct 2021 23:33:54 -0700 Subject: [PATCH] Add frigate-card-conditional element to select views. --- README.md | 164 ++++++++++++++++++++--- src/card.ts | 28 ++-- src/components/elements.ts | 229 +++++++++++++++++++++++++-------- src/components/message.ts | 6 +- src/localize/languages/en.json | 4 +- src/scss/message.scss | 4 + src/types.ts | 47 ++++--- 7 files changed, 367 insertions(+), 115 deletions(-) diff --git a/README.md b/README.md index e2d564ee..b04ce8ec 100644 --- a/README.md +++ b/README.md @@ -207,39 +207,55 @@ entities: show: false ``` -### Picture Elements / Menu customizations +## Picture Elements / Menu customizations This card supports the [Picture Elements configuration syntax](https://www.home-assistant.io/lovelace/picture-elements/) to seamlessly allow the user to add custom elements to the card, which may be configured to perform a variety of actions on `tap`, `double_tap` and `hold`. -In the card YAML configuration, elements may be manually added under an `elements` key. +In the card YAML configuration, elements may be manually added under an +`elements` key. -#### Special Elements +See the [action +documentation](https://www.home-assistant.io/lovelace/actions/#hold-action) for +more information on the action options available. -This card supports all [Picture Elements](https://www.home-assistant.io/lovelace/picture-elements/#icon-element) using the same syntax. The card also supports two special elements to add plain icons and state-based icons to the Frigate card menu. +### Special Elements + +This card supports all [Picture Elements](https://www.home-assistant.io/lovelace/picture-elements/#icon-element) using the same syntax. The card also supports a handful of custom special elements to add special Frigate card functionality. | Element name | Description | | ------------- | --------------------------------------------- | -| `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).| -| `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).| +| `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) except with a type name of `custom:frigate-card-menu-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) except with a type name of `custom:frigate-card-menu-state-icon`.| +| `custom:frigate-card-conditional` | Restrict a set of elements to only render when the card is showing particular a particular [view](#views). See [configuration below](#frigate-card-conditional).| -See the [action documentation](https://www.home-assistant.io/lovelace/actions/#hold-action) for more information on the action options available. + -#### Elements Examples +### `custom:frigate-card-conditional` -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. +Parameters for the `custom:frigate-card-conditional` element: -```yaml -elements: - - type: custom:frigate-card-menu-state-icon - entity: light.office_main_lights - double_tap_action: - action: toggle -``` +| Parameter | Description | +| ------------- | --------------------------------------------- | +| `type` | Must be `custom:frigate-card-conditional`. | +| `conditions` | A set of conditions that must evaluate to true in order for the elements to be rendered. | +| `conditions.view` | A list of [views](#views) in which these elements should be rendered. | +| `elements` | The elements to render. Can be any supported element, include additional condition or custom elements. | -Add an icon that navigates the brower to the releases page for this card: +See the [PTZ example below](#frigate-card-conditional-example) for a real-world example. +### Elements Examples + +#### Menu icons + +You can add custom icons to the menu with arbitrary actions. + +
+ Expand: Custom menu icon + +This example adds an icon that navigates the brower to the releases page for this +card: ```yaml - type: custom:frigate-card-menu-icon @@ -248,8 +264,35 @@ Add an icon that navigates the brower to the releases page for this card: action: url url_path: https://github.com/dermotduffy/frigate-hass-card/releases ``` +
-Add a state badge showing the temperature but hide the label text: +#### Menu state icons + +You can add custom state icons to the menu to show the state of an entity and complete arbitrary actions. + +
+ Expand: Custom menu state icon + +This example adds an icon that represents the state of the +`light.office_main_lights` entity, that toggles the light on double click. + +```yaml +elements: + - type: custom:frigate-card-menu-state-icon + entity: light.office_main_lights + tap_action: + action: toggle +``` +
+ +#### State badges + +You can adds a state badge to the card showing arbitrary entity states. + +
+ Expand: State badge + +This example adds a state badge showing the temperature and hides the label text: ```yaml - type: state-badge @@ -262,8 +305,16 @@ Add a state badge showing the temperature but hide the label text: ``` Picture elements temperature example +
-You can also have icons conditionally added to the menu, such as only showing a menu icon if a light is on: +#### Conditional menu icons + +You can have icons conditionally added to the menu based on entity state. + +
+ Expand: Conditional menu icons + +This example only adds the light entity to the menu if a light is on. ```yaml - type: conditional @@ -276,6 +327,81 @@ You can also have icons conditionally added to the menu, such as only showing a tap_action: action: toggle ``` +
+ + + +#### Restricting icons to certain views + +You can restrict icons to only show for certain [views](#views) using a +`custom:frigate-card-conditional` element (e.g. PTZ controls) + +
+ Expand: View-based conditions (e.g. PTZ controls) + +This example shows PTZ icons that call a PTZ service, but only in the `live` view. + +```yaml +elements: + - type: custom:frigate-card-conditional + conditions: + view: + - live + elements: + - type: icon + icon: mdi:arrow-up + style: + background: rgba(255, 255, 255, 0.25) + border-radius: 5px + right: 25px + bottom: 50px + tap_action: + action: call-service + service: amcrest.ptz_control + service_data: + entity_id: camera.kitchen + movement: up + - type: icon + icon: mdi:arrow-down + style: + background: rgba(255, 255, 255, 0.25) + border-radius: 5px + right: 25px + bottom: 0px + tap_action: + action: call-service + service: amcrest.ptz_control + service_data: + entity_id: camera.kitchen + movement: down + - type: icon + icon: mdi:arrow-left + style: + background: rgba(255, 255, 255, 0.25) + border-radius: 5px + right: 50px + bottom: 25px + tap_action: + action: call-service + service: amcrest.ptz_control + service_data: + entity_id: camera.kitchen + movement: left + - type: icon + icon: mdi:arrow-right + style: + background: rgba(255, 255, 255, 0.25) + border-radius: 5px + right: 0px + bottom: 25px + tap_action: + action: call-service + service: amcrest.ptz_control + service_data: + entity_id: camera.kitchen + movement: right +``` +
diff --git a/src/card.ts b/src/card.ts index 6c2b3b96..392a2c98 100644 --- a/src/card.ts +++ b/src/card.ts @@ -19,11 +19,7 @@ import { } from 'custom-card-helpers'; import screenfull from 'screenfull'; -import { - entitySchema, - frigateCardConfigSchema, - Message, -} from './types'; +import { entitySchema, frigateCardConfigSchema, Message } from './types'; import type { BrowseMediaQueryParameters, Entity, @@ -280,6 +276,8 @@ export class FrigateCard extends LitElement { } protected _changeView(view?: View | undefined): void { + this._message = null; + if (view === undefined) { this._view = new View({ view: this.config.view_default }); } else { @@ -412,8 +410,8 @@ export class FrigateCard extends LitElement { } protected _setMessageAndUpdate(message: Message): void { - // Only register the first message. - if (!this._message) { + // Register the first message, or prioritize errors if there's pre-render competition. + if (!this._message || (message.type == 'error' && this._message.type != 'error')) { this._message = message; this.requestUpdate(); } @@ -423,15 +421,6 @@ export class FrigateCard extends LitElement { return this._setMessageAndUpdate(e.detail); } - protected _renderAndResetMessage(): TemplateResult | void { - if (this._message) { - const message = this._message; - this._message = null; - return renderMessage(message); - } - return html``; - } - protected _mediaLoadHandler(e: CustomEvent): void { const mediaInfo = e.detail; // In Safari, with WebRTC, 0x0 is occasionally returned during loading, @@ -556,7 +545,7 @@ export class FrigateCard extends LitElement {
${this._message - ? this._renderAndResetMessage() + ? renderMessage(this._message) : until(this._render(), renderProgressIndicator())}
@@ -624,7 +613,7 @@ export class FrigateCard extends LitElement { : ``} { this._menu.addButton(e.detail); @@ -632,6 +621,9 @@ export class FrigateCard extends LitElement { @frigate-card:menu-remove=${(e) => { this._menu.removeButton(e.detail); }} + @frigate-card:state-request=${(e) => { + e.view = this._view; + }} > diff --git a/src/components/elements.ts b/src/components/elements.ts index 6b5f4a20..a0da7511 100644 --- a/src/components/elements.ts +++ b/src/components/elements.ts @@ -1,21 +1,27 @@ import { LitElement, TemplateResult, html, CSSResultGroup, unsafeCSS } from 'lit'; import { HomeAssistant } from 'custom-card-helpers'; -import { customElement, property } from 'lit/decorators'; +import { customElement, property, query } from 'lit/decorators'; -import { ExtendedHomeAssistant, MenuButton, MenuIcon, MenuStateIcon, menuStateIconSchema, PictureElements } from '../types'; -import { menuIconSchema } from '../types' -import { dispatchErrorMessageEvent, dispatchEvent, getParseErrorKeys } from '../common'; +import { + ExtendedHomeAssistant, + FrigateConditional, + MenuButton, + MenuIcon, + MenuStateIcon, + PictureElements, +} from '../types'; +import { dispatchErrorMessageEvent, dispatchEvent } from '../common'; import elementsStyle from '../scss/elements.scss'; import { localize } from '../localize/localize'; -import { z } from 'zod'; +import { View } from '../view'; /* 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 @@ -30,7 +36,7 @@ import { z } from 'zod'; * 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 @@ -43,22 +49,82 @@ import { z } from 'zod'; * upper layers to handle correctly. */ - -@customElement('frigate-card-elements') -export class FrigateCardElements extends LitElement { +// A small wrapper around a HA conditional element used to render a set of +// picture elements. +@customElement('frigate-card-elements-core') +class FrigateCardElementsCore extends LitElement { @property({ attribute: false }) - protected pictureElements: PictureElements; + protected elements: PictureElements; - protected _hass!: HomeAssistant & ExtendedHomeAssistant; protected _root: HTMLElement | null = null; + protected _hass!: HomeAssistant & ExtendedHomeAssistant; set hass(hass: HomeAssistant & ExtendedHomeAssistant) { if (this._root) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._root as any).hass = hass; } this._hass = hass; } + // Transparent to elements. + createRenderRoot(): LitElement { + return this; + } + + protected _createRoot(): void { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const elementConstructor = customElements.get('hui-conditional-element') as any; + if (!elementConstructor) { + throw new Error(localize('error.could_not_render_elements')); + } + + const element = new elementConstructor(); + element.hass = this._hass; + const config = { + type: 'conditional', + conditions: [], + elements: this.elements, + }; + try { + element.setConfig(config); + } catch (e) { + console.error(e, (e as Error).stack); + throw new Error(localize('error.invalid_elements_config')); + } + this._root = element; + } + + protected render(): TemplateResult | void { + if (!this._root) { + try { + this._createRoot(); + } catch (e) { + return dispatchErrorMessageEvent(this, (e as Error).message); + } + } + return html`${this._root || ''}`; + } +} + +// THe master class, handles event listeners and styles. +@customElement('frigate-card-elements') +export class FrigateCardElements extends LitElement { + @property({ attribute: false }) + protected elements: PictureElements; + + protected _hass!: HomeAssistant & ExtendedHomeAssistant; + + @query('frigate-card-elements-core') + _core!: FrigateCardElementsCore; + + set hass(hass: HomeAssistant & ExtendedHomeAssistant) { + if (this._core) { + this._core.hass = hass; + } + this._hass = hass; + } + 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). @@ -67,7 +133,7 @@ export class FrigateCardElements extends LitElement { protected _menuAddHandler(ev: Event): void { ev = ev as CustomEvent; - const path = ev.composedPath() + const path = ev.composedPath(); if (!path.length) { return; } @@ -77,11 +143,13 @@ export class FrigateCardElements extends LitElement { // Ensure listener is only attached 1 time by removing it first. path[0].removeEventListener( 'frigate-card:menu-remove', - this._menuRemoveHandler.bind(this)); + this._menuRemoveHandler.bind(this), + ); path[0].addEventListener( 'frigate-card:menu-remove', - this._menuRemoveHandler.bind(this)); + this._menuRemoveHandler.bind(this), + ); } connectedCallback(): void { @@ -89,49 +157,20 @@ export class FrigateCardElements extends LitElement { // 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(); - } + this.addEventListener('frigate-card:menu-add', this._menuAddHandler); } disconnectedCallback(): void { - this.removeEventListener( - 'frigate-card:menu-add', - this._menuAddHandler, - ); + this.removeEventListener('frigate-card:menu-add', this._menuAddHandler); super.disconnectedCallback(); } - protected _createRoot(): void { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const elementConstructor = customElements.get('hui-conditional-element') as any; - if (!elementConstructor) { - return; - } - - const element = new elementConstructor(); - element.hass = this._hass; - const config = { - type: 'conditional', - conditions: [], - elements: this.pictureElements, - } - try { - element.setConfig(config); - } catch (e) { - console.error(e, (e as Error).stack); - return; - } - this._root = element; - } - protected render(): TemplateResult { - return html`${this._root || ''}`; + return html` + `; } static get styles(): CSSResultGroup { @@ -139,6 +178,84 @@ export class FrigateCardElements extends LitElement { } } +class StateRequestEvent extends Event { + public view: View | undefined; +} + +// An element that can render others based on Frigate state (e.g. only show +// overlays in particular views). This is the Frigate Card equivalent to the HA +// conditional card. +@customElement('frigate-card-conditional') +export class FrigateCardElementsConditional extends LitElement { + protected _config: FrigateConditional | null = null; + protected _hass!: HomeAssistant & ExtendedHomeAssistant; + + @query('frigate-card-elements-core') + _core!: FrigateCardElementsCore; + + set hass(hass: HomeAssistant & ExtendedHomeAssistant) { + if (this._core) { + this._core.hass = hass; + } + this._hass = hass; + } + + public setConfig(config: FrigateConditional): void { + this._config = config; + } + + // Transparent to elements. + createRenderRoot(): LitElement { + return this; + } + + protected evaluate(stateEvent: StateRequestEvent): boolean { + if (stateEvent.view && this._config.conditions.view) { + return this._config.conditions.view.includes(stateEvent.view.view); + } + return true; + } + + connectedCallback(): void { + super.connectedCallback(); + + // HA will automatically attach the 'element' class to picture elements. As + // this is a transparent 'conditional' element (just like the stock HA + // 'conditional' element), it should not have positioning. + this.className = ''; + } + + protected render(): TemplateResult | void { + const stateEvent = new StateRequestEvent(`frigate-card:state-request`, { + bubbles: true, + composed: true, + }); + + /* Special note on what's going on here: + * + * Picture elements all are descendents of , but + * there may be arbitrary complexity and layers (that this card doesn't + * control) between that master element and this custom conditional element. + * This element needs Frigate card state to function (e.g. view), but + * there's no clean way to pass state from the rest of card down through + * these layers. Instead, we dispatch a "request for state" + * (StateRequestEvent) event upwards which is caught by the outer card and + * state added to the event object. Because event propagation is handled + * synchronously, the state will be added to the event before the flow + * proceeds. + */ + this.dispatchEvent(stateEvent); + if (this.evaluate(stateEvent)) { + return html` + `; + } + } +} + +// A base class for rendering menu icons / menu state icons. export class FrigateCardElementsBaseMenuIcon extends LitElement { @property({ attribute: false }) protected _config: T | null = null; @@ -148,17 +265,17 @@ export class FrigateCardElementsBaseMenuIcon extends LitElement { } connectedCallback(): void { - super.connectedCallback() + super.connectedCallback(); if (this._config) { - dispatchEvent(this, 'menu-add', this._config); + dispatchEvent(this, 'menu-add', this._config); } } disconnectedCallback(): void { if (this._config) { - dispatchEvent(this, 'menu-remove', this._config); + dispatchEvent(this, 'menu-remove', this._config); } - super.disconnectedCallback() + super.disconnectedCallback(); } } @@ -166,4 +283,4 @@ export class FrigateCardElementsBaseMenuIcon extends LitElement { export class FrigateCardElementsMenuIcon extends FrigateCardElementsBaseMenuIcon {} @customElement('frigate-card-menu-state-icon') -export class FrigateCardElementsMenuStateIcon extends FrigateCardElementsBaseMenuIcon {} \ No newline at end of file +export class FrigateCardElementsMenuStateIcon extends FrigateCardElementsBaseMenuIcon {} diff --git a/src/components/message.ts b/src/components/message.ts index e63961ca..c0fc5b90 100644 --- a/src/components/message.ts +++ b/src/components/message.ts @@ -24,7 +24,9 @@ export class FrigateCardMessage extends LitElement { return html`
- ${this.message ? html` ${this.message}` : ''} + + + ${this.message ? html`${this.message}` : ''}
`; } @@ -42,7 +44,7 @@ export class FrigateCardErrorMessage extends LitElement { protected render(): TemplateResult { return html` ${localize('error.troubleshooting')} .`} + ${localize('error.troubleshooting')}.`} .icon=${'mdi:alert-circle'} > `; diff --git a/src/localize/languages/en.json b/src/localize/languages/en.json index 0a943bdc..7bdb8f9e 100644 --- a/src/localize/languages/en.json +++ b/src/localize/languages/en.json @@ -95,6 +95,8 @@ "no_live_camera": "No live camera", "invalid_configuration": "Invalid configuration", "missing_webrtc": "WebRTC component not found", - "no_frigate_camera_name": "Cannot derive frigate_camera_name, you may need to set it manually" + "no_frigate_camera_name": "Cannot derive frigate_camera_name, you may need to set it manually", + "could_not_render_elements": "Could not render picture elements", + "invalid_elements_config": "Invalid picture elements configuration" } } diff --git a/src/scss/message.scss b/src/scss/message.scss index aa789cb0..6becbe0c 100644 --- a/src/scss/message.scss +++ b/src/scss/message.scss @@ -10,3 +10,7 @@ .message a { color: var(--primary-text-color, white); } + +span { + padding: 10px; +} \ No newline at end of file diff --git a/src/types.ts b/src/types.ts index dc983c3d..2fe0ea71 100644 --- a/src/types.ts +++ b/src/types.ts @@ -181,8 +181,7 @@ const imageSchema = elementsBaseSchema.merge( })); // https://www.home-assistant.io/lovelace/picture-elements/#image-element -const conditionalSchema = elementsBaseSchema.merge( - z.object({ +const conditionalSchema = z.object({ type: z.literal('conditional'), conditions: z.object({ entity: z.string(), @@ -190,7 +189,7 @@ const conditionalSchema = elementsBaseSchema.merge( state_not: z.string().optional(), }).array(), elements: z.lazy(() => pictureElementsSchema), - })); + }); // https://www.home-assistant.io/lovelace/picture-elements/#custom-elements const customSchema = z.object({ @@ -199,7 +198,7 @@ const customSchema = z.object({ }).passthrough(); /** - * Menu Element Types + * Custom Element Types */ export const menuIconSchema = iconSchema.merge( @@ -214,28 +213,22 @@ export const menuStateIconSchema = stateIconSchema.merge( })); export type MenuStateIcon = z.infer; -// Schema for card (non-user configured) menu icons. -const internalMenuIconSchema = z - .object({ - type: z.literal('internal-menu-icon'), - title: z.string(), - icon: z.string().optional(), - emphasize: z.boolean().default(false).optional(), - card_action: z.string(), - }); +const frigateConditionalSchema = z.object({ + type: z.literal('custom:frigate-card-conditional'), + conditions: z.object({ + view: z.string().array().optional(), + }), + elements: z.lazy(() => pictureElementsSchema), +}); +export type FrigateConditional = z.infer; -const menuButtonSchema = z.union([ - menuIconSchema, - menuStateIconSchema, - internalMenuIconSchema, -]); -export type MenuButton = z.infer; // 'internalMenuIconSchema' is excluded to disallow the user from manually // changing the internal menu buttons. const pictureElementSchema = z.union([ menuStateIconSchema, menuIconSchema, + frigateConditionalSchema, stateBadgeIconSchema, stateIconSchema, stateLabelSchema, @@ -323,6 +316,22 @@ export const frigateCardConfigSchema = z.object({ }); export type FrigateCardConfig = z.infer; +// Schema for card (non-user configured) menu icons. +const internalMenuIconSchema = z + .object({ + type: z.literal('internal-menu-icon'), + title: z.string(), + icon: z.string().optional(), + emphasize: z.boolean().default(false).optional(), + card_action: z.string(), + }); + +const menuButtonSchema = z.union([ + menuIconSchema, + menuStateIconSchema, + internalMenuIconSchema, +]); +export type MenuButton = z.infer; export interface ExtendedHomeAssistant { hassUrl(path?): string; }