Prettier formatting.

This commit is contained in:
Dermot Duffy
2021-08-17 20:36:27 -07:00
parent 0e3290998a
commit 0497c92779
11 changed files with 365 additions and 309 deletions
+191 -187
View File
@@ -11,7 +11,7 @@ import {
unsafeCSS,
} from 'lit-element';
import { NodePart } from "lit-html";
import { NodePart } from 'lit-html';
import { until } from 'lit-html/directives/until.js';
import {
@@ -23,11 +23,18 @@ import {
import './editor';
import frigate_card_style from './frigate-card.scss'
import frigate_card_menu_style from './frigate-card-menu.scss'
import frigate_card_style from './frigate-card.scss';
import frigate_card_menu_style from './frigate-card-menu.scss';
import { frigateCardConfigSchema, frigateGetEventsResponseSchema } from './types';
import type { FrigateCardView, FrigateCardConfig, FrigateEvent, FrigateGetEventsResponse, GetEventsParameters, ControlVideosParameters } from './types';
import type {
FrigateCardView,
FrigateCardConfig,
FrigateEvent,
FrigateGetEventsResponse,
GetEventsParameters,
ControlVideosParameters,
} from './types';
import { CARD_VERSION } from './const';
import { localize } from './localize/localize';
import dayjs from 'dayjs';
@@ -67,9 +74,9 @@ function shouldUpdateBasedOnHass(
if (!entities.length) {
return false;
}
if (oldHass) {
for(let i = 0; i < entities.length; i++) {
for (let i = 0; i < entities.length; i++) {
const entity = entities[i];
if (!entity) {
continue;
@@ -105,20 +112,21 @@ export class FrigateCardMenu extends LitElement {
return shouldUpdateBasedOnHass(
this.hass,
changedProps.get('hass') as HomeAssistant | undefined,
[this.motionEntity]);
[this.motionEntity],
);
}
// Render the Frigate menu button.
protected _renderFrigateButton(): TemplateResult {
return html`
<ha-icon-button
class="button"
icon=${this.expand ? "mdi:alpha-f-box" : "mdi:alpha-f-box-outline"}
data-toggle="tooltip" title="Frigate menu"
@click=${() => {
this.expand = !this.expand;
}}
></ha-icon-button>`;
return html` <ha-icon-button
class="button"
icon=${this.expand ? 'mdi:alpha-f-box' : 'mdi:alpha-f-box-outline'}
data-toggle="tooltip"
title="Frigate menu"
@click=${() => {
this.expand = !this.expand;
}}
></ha-icon-button>`;
}
// Call the callback.
@@ -131,76 +139,77 @@ export class FrigateCardMenu extends LitElement {
// Render the menu.
protected render(): TemplateResult | void | ((part: NodePart) => Promise<void>) {
if (!this.expand) {
return html`
<div class="frigate-card-menu">
${this._renderFrigateButton()}
</div>`;
return html` <div class="frigate-card-menu">${this._renderFrigateButton()}</div>`;
}
let motionIcon: string | null = null;
if (this.motionEntity && this.hass) {
motionIcon = this.hass.states[this.motionEntity]?.state == "on" ? "mdi:motion-sensor" : "mdi:walk";
motionIcon =
this.hass.states[this.motionEntity]?.state == 'on'
? 'mdi:motion-sensor'
: 'mdi:walk';
}
return html`
<div class="frigate-card-menu-container">
<div
class="frigate-card-menu-expanded"
>
<div class="frigate-card-menu-expanded">
${this._renderFrigateButton()}
<ha-icon-button
class="button"
icon="mdi:cctv"
data-toggle="tooltip" title="View live"
data-toggle="tooltip"
title="View live"
@click=${() => {
this.expand = false;
this._callAction("live");
this._callAction('live');
}}
></ha-icon-button>
<ha-icon-button
class="button"
icon = "mdi:filmstrip"
data-toggle="tooltip" title="View clips"
icon="mdi:filmstrip"
data-toggle="tooltip"
title="View clips"
@click=${() => {
this.expand = false;
this._callAction("clips");
this._callAction('clips');
}}
></ha-icon-button>
<ha-icon-button
class="button"
icon = "mdi:camera"
data-toggle="tooltip" title="View snapshots"
icon="mdi:camera"
data-toggle="tooltip"
title="View snapshots"
@click=${() => {
this.expand = false;
this._callAction("snapshots");
this._callAction('snapshots');
}}
></ha-icon-button>
<ha-icon-button
class="button"
icon = "mdi:web"
data-toggle="tooltip" title="View Frigate UI"
icon="mdi:web"
data-toggle="tooltip"
title="View Frigate UI"
@click=${() => {
this.expand = false;
this._callAction("frigate-ui");
this._callAction('frigate-ui');
}}
></ha-icon-button>
${!motionIcon ? html`` : html`
<ha-icon-button
data-toggle="tooltip" title="View motion sensor"
class="button"
icon="${motionIcon}"
@click=${() => {
this.expand = false;
this._callAction("motion");
}}
></ha-icon-button>`
}
${!motionIcon
? html``
: html` <ha-icon-button
data-toggle="tooltip"
title="View motion sensor"
class="button"
icon="${motionIcon}"
@click=${() => {
this.expand = false;
this._callAction('motion');
}}
></ha-icon-button>`}
</div>
${this.heading ? html`
<div class="frigate-card-menu-title">
${this.heading}
</div>
` : ``}
${this.heading
? html` <div class="frigate-card-menu-title">${this.heading}</div> `
: ``}
</div>
`;
}
@@ -211,11 +220,9 @@ export class FrigateCardMenu extends LitElement {
}
}
// Main FrigateCard class.
@customElement('frigate-card')
export class FrigateCard extends LitElement {
// Get the configuration element.
public static async getConfigElement(): Promise<LovelaceCardEditor> {
return document.createElement('frigate-card-editor');
@@ -239,7 +246,7 @@ export class FrigateCard extends LitElement {
public config!: FrigateCardConfig;
@property({ attribute: false })
protected _viewMode: FrigateCardView = "live";
protected _viewMode: FrigateCardView = 'live';
@property({ attribute: false })
protected _viewEvent: FrigateEvent | null = null;
@@ -248,7 +255,7 @@ export class FrigateCard extends LitElement {
protected _showMenu = false;
@state()
protected _heading: string | null = null;
protected _heading: string | null = null;
protected _interactionTimerID: number | null = null;
protected _webrtcElement: any | null = null;
@@ -261,9 +268,9 @@ export class FrigateCard extends LitElement {
const parseResult = frigateCardConfigSchema.safeParse(inputConfig);
if (!parseResult.success) {
const errors = parseResult.error.format()
const keys = Object.keys(errors).filter(v => !v.startsWith("_"));
throw new Error(localize('common.invalid_configuration') + ": " + keys.join(", "));
const errors = parseResult.error.format();
const keys = Object.keys(errors).filter((v) => !v.startsWith('_'));
throw new Error(localize('common.invalid_configuration') + ': ' + keys.join(', '));
}
const config = parseResult.data;
@@ -273,14 +280,14 @@ export class FrigateCard extends LitElement {
if (!config.frigate_camera_name) {
// No camera name specified, so just assume it's the same as the entity name.
if (config.camera_entity.includes(".")) {
config.frigate_camera_name = config.camera_entity.split('.', 2)[1]
if (config.camera_entity.includes('.')) {
config.frigate_camera_name = config.camera_entity.split('.', 2)[1];
} else {
throw new Error(localize('common.invalid_configuration') + ": camera_entity");
throw new Error(localize('common.invalid_configuration') + ': camera_entity');
}
}
if (config.live_provider == "webrtc") {
if (config.live_provider == 'webrtc') {
// Create a WebRTC element (https://github.com/AlexxIT/WebRTC)
const webrtcElement = customElements.get('webrtc-camera');
if (webrtcElement) {
@@ -300,8 +307,8 @@ export class FrigateCard extends LitElement {
// Set the view mode to the configured default.
protected _setViewModeToDefault(): void {
this._viewMode = this.config.view_default;
if (["clip", "snapshot"].includes(this._viewMode)) {
this._viewEvent = null;
if (['clip', 'snapshot'].includes(this._viewMode)) {
this._viewEvent = null;
}
}
@@ -317,7 +324,8 @@ export class FrigateCard extends LitElement {
return shouldUpdateBasedOnHass(
this._hass,
changedProps.get('_hass') as HomeAssistant | undefined,
[this.config.camera_entity, this.config.motion_entity]);
[this.config.camera_entity, this.config.motion_entity],
);
}
// Get FrigateEvents from the Frigate server API.
@@ -328,13 +336,13 @@ export class FrigateCard extends LitElement {
}: GetEventsParameters): Promise<FrigateGetEventsResponse> {
let url = `${this.config.frigate_url}/api/events?camera=${this.config.frigate_camera_name}`;
if (has_clip) {
url += `&has_clip=1`
url += `&has_clip=1`;
}
if (has_snapshot) {
url += `&has_snapshot=1`
url += `&has_snapshot=1`;
}
if (limit > 0) {
url += `&limit=${limit}`
url += `&limit=${limit}`;
}
if (this.config.label) {
@@ -349,13 +357,13 @@ export class FrigateCard extends LitElement {
let raw_json;
try {
raw_json = await response.json();
} catch(e) {
} catch (e) {
console.warn(e);
throw new Error(`Could not JSON decode Frigate API response: ${e}`);
}
try {
return frigateGetEventsResponseSchema.parse(raw_json);
} catch(e) {
} catch (e) {
console.warn(e);
throw new Error(`Frigate events were malformed: ${e}`);
}
@@ -367,28 +375,27 @@ export class FrigateCard extends LitElement {
}
protected _renderAttentionIcon(icon: string): TemplateResult {
return html`
<div class="frigate-card-attention">
<ha-icon icon="${icon}">
</ha-icon>
</div>`;
return html` <div class="frigate-card-attention">
<ha-icon icon="${icon}"> </ha-icon>
</div>`;
}
// Render an embedded error situation.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected _renderError(_error: string) : TemplateResult {
return this._renderAttentionIcon("mdi:alert-circle");
protected _renderError(_error: string): TemplateResult {
return this._renderAttentionIcon('mdi:alert-circle');
}
// Generate a human-readable title from an event.
// MediaBrowser title: 2021-08-12 19:20:14 [10s, Person 76%]
protected _getEventTitle(event: FrigateEvent) : string {
const date = dayjs.unix(event.end_time).tz("UTC").local();
protected _getEventTitle(event: FrigateEvent): string {
const date = dayjs.unix(event.end_time).tz('UTC').local();
const iso_datetime = date.format("YYYY-MM-DD HH:mm:ss");
const duration = Math.trunc(event.end_time > event.start_time ?
event.end_time - event.start_time : 0);
const score = Math.trunc(event.top_score*100);
const iso_datetime = date.format('YYYY-MM-DD HH:mm:ss');
const duration = Math.trunc(
event.end_time > event.start_time ? event.end_time - event.start_time : 0,
);
const score = Math.trunc(event.top_score * 100);
// Capitalize the label.
const label = event.label.charAt(0).toUpperCase() + event.label.slice(1);
@@ -397,8 +404,8 @@ export class FrigateCard extends LitElement {
}
// Render Frigate events into a card gallery.
protected async _renderEvents() : Promise<TemplateResult> {
const want_clips = (this._viewMode == "clips");
protected async _renderEvents(): Promise<TemplateResult> {
const want_clips = this._viewMode == 'clips';
let events;
try {
events = await this._getEvents({
@@ -410,45 +417,45 @@ export class FrigateCard extends LitElement {
}
if (!events.length) {
return this._renderAttentionIcon(want_clips ? "mdi:filmstrip-off" : "mdi:camera-off");
return this._renderAttentionIcon(
want_clips ? 'mdi:filmstrip-off' : 'mdi:camera-off',
);
}
return html`
<ul class= "mdc-image-list frigate-card-image-list">
${events.map(event => html`
<li class="mdc-image-list__item">
<div class="mdc-image-list__image-aspect-container">
<img
data-toggle="tooltip" title="${this._getEventTitle(event)}"
class="mdc-image-list__image"
src="data:image/png;base64,${event.thumbnail}"
@click=${() => {
this._showMenu = false;
this._viewEvent = event;
this._viewMode = want_clips ? "clip" : "snapshot";
}}
>
</div>
</li>`)}
</ul>`;
return html` <ul class="mdc-image-list frigate-card-image-list">
${events.map(
(event) => html` <li class="mdc-image-list__item">
<div class="mdc-image-list__image-aspect-container">
<img
data-toggle="tooltip"
title="${this._getEventTitle(event)}"
class="mdc-image-list__image"
src="data:image/png;base64,${event.thumbnail}"
@click=${() => {
this._showMenu = false;
this._viewEvent = event;
this._viewMode = want_clips ? 'clip' : 'snapshot';
}}
/>
</div>
</li>`,
)}
</ul>`;
}
// Render a progress spinner while content loads.
protected _renderProgressIndicator(): TemplateResult {
return html`
<div class="frigate-card-attention">
<ha-circular-progress
active="true"
size="large"
></ha-circular-progress>
</div>`
return html` <div class="frigate-card-attention">
<ha-circular-progress active="true" size="large"></ha-circular-progress>
</div>`;
}
// Stop/Play video controls.
protected _controlVideos({
stop,
control_live = false,
control_clip = false}: ControlVideosParameters): void {
stop,
control_live = false,
control_clip = false,
}: ControlVideosParameters): void {
const controlVideo = (stop: boolean, is_live: boolean, video: HTMLVideoElement) => {
if (video) {
if (stop) {
@@ -464,7 +471,7 @@ export class FrigateCard extends LitElement {
video.play();
}
}
}
};
if (!this.shadowRoot) {
return;
}
@@ -472,8 +479,8 @@ export class FrigateCard extends LitElement {
controlVideo(
stop,
false,
this.shadowRoot?.
querySelector('video.frigate-card-viewer') as HTMLVideoElement);
this.shadowRoot?.querySelector('video.frigate-card-viewer') as HTMLVideoElement,
);
}
if (control_live) {
// Don't have direct access to the live video player as it is buried in
@@ -482,50 +489,49 @@ export class FrigateCard extends LitElement {
controlVideo(
stop,
true,
this.shadowRoot?.
querySelector('webrtc-camera video') as HTMLVideoElement
)
this.shadowRoot?.querySelector('webrtc-camera video') as HTMLVideoElement,
);
} else {
controlVideo(
stop,
true,
this.shadowRoot?.
querySelector('ha-camera-stream')?.shadowRoot?.
querySelector('ha-hls-player')?.shadowRoot?.
querySelector('video') as HTMLVideoElement
)
this.shadowRoot
?.querySelector('ha-camera-stream')
?.shadowRoot?.querySelector('ha-hls-player')
?.shadowRoot?.querySelector('video') as HTMLVideoElement,
);
}
}
}
protected _menuActionHandler(name: string): void {
switch (name) {
case "live":
this._controlVideos({stop: true, control_clip: true});
this._controlVideos({stop: false, control_live: true});
case 'live':
this._controlVideos({ stop: true, control_clip: true });
this._controlVideos({ stop: false, control_live: true });
this._viewMode = name;
this._heading = null;
break;
case "clips":
this._controlVideos({stop: true, control_live: true});
case 'clips':
this._controlVideos({ stop: true, control_live: true });
this._viewMode = name;
this._heading = null;
break;
case "snapshots":
this._controlVideos({stop: true, control_clip: true, control_live: true});
case 'snapshots':
this._controlVideos({ stop: true, control_clip: true, control_live: true });
this._viewMode = name;
this._heading = null;
break;
case "frigate-ui":
case 'frigate-ui':
window.open(this.config.frigate_url);
break;
case "motion":
case 'motion':
if (this.config.motion_entity) {
fireEvent(this, "hass-more-info", {entityId: this.config.motion_entity});
fireEvent(this, 'hass-more-info', { entityId: this.config.motion_entity });
}
break;
default:
console.warn("Unknown Frigate card menu option.")
console.warn('Unknown Frigate card menu option.');
}
}
@@ -538,23 +544,21 @@ export class FrigateCard extends LitElement {
try {
events = await this._getEvents({
has_clip: true,
limit: 1
limit: 1,
});
} catch (e) {
return this._renderError(e);
}
if (!events.length) {
return this._renderAttentionIcon("mdi:camera-off");
return this._renderAttentionIcon('mdi:camera-off');
}
event = events[0];
}
this._heading = this._getEventTitle(event);
const url = `${this.config.frigate_url}/clips/` +
`${event.camera}-${event.id}.mp4`;
return html`
<video class="frigate-card-viewer" autoplay muted controls>
<source src="${url}" type="video/mp4">
</video>`
const url = `${this.config.frigate_url}/clips/` + `${event.camera}-${event.id}.mp4`;
return html` <video class="frigate-card-viewer" autoplay muted controls>
<source src="${url}" type="video/mp4" />
</video>`;
}
// Render a snapshot.
@@ -566,19 +570,19 @@ export class FrigateCard extends LitElement {
try {
events = await this._getEvents({
has_snapshot: true,
limit: 1
limit: 1,
});
} catch (e) {
return this._renderError(e);
}
if (!events.length) {
return this._renderAttentionIcon("mdi:filmstrip-off");
return this._renderAttentionIcon('mdi:filmstrip-off');
}
event = events[0];
}
this._heading = this._getEventTitle(event);
const url = `${this.config.frigate_url}/clips/${event.camera}-${event.id}.jpg`;
return html`<img class="frigate-card-viewer" src="${url}">`
return html`<img class="frigate-card-viewer" src="${url}" />`;
}
// Render the live viewer.
@@ -586,25 +590,21 @@ export class FrigateCard extends LitElement {
// is always rendered (but sometimes hidden).
protected _renderLiveViewer(): TemplateResult {
if (!this._hass || !(this.config.camera_entity in this._hass.states)) {
return this._renderError("mdi:camera-off")
return this._renderError('mdi:camera-off');
}
if (this._webrtcElement) {
return html`
<div
class=${this._viewMode == "live" ? 'visible' : 'invisible'}
>
${this._webrtcElement}
</div>`;
return html` <div class=${this._viewMode == 'live' ? 'visible' : 'invisible'}>
${this._webrtcElement}
</div>`;
}
return html`
<ha-camera-stream
.hass=${this._hass}
.stateObj=${this._hass.states[this.config.camera_entity]}
.controls=${true}
.muted=${true}
class=${this._viewMode == "live" ? 'visible' : 'invisible'}
>
</ha-camera-stream>`;
return html` <ha-camera-stream
.hass=${this._hass}
.stateObj=${this._hass.states[this.config.camera_entity]}
.controls=${true}
.muted=${true}
class=${this._viewMode == 'live' ? 'visible' : 'invisible'}
>
</ha-camera-stream>`;
}
// Record interactions with the card.
@@ -633,25 +633,33 @@ export class FrigateCard extends LitElement {
return html`
<ha-card @click=${this._interactionHandler}>
</frigate-card-menu>
${this._viewMode == "clips" ?
html`<div class="frigate-card-gallery">
${until(this._renderEvents(), this._renderProgressIndicator())}
</div>` : ``
${
this._viewMode == 'clips'
? html`<div class="frigate-card-gallery">
${until(this._renderEvents(), this._renderProgressIndicator())}
</div>`
: ``
}
${this._viewMode == "snapshots" ?
html`<div class="frigate-card-gallery">
${until(this._renderEvents(), this._renderProgressIndicator())}
</div>` : ``
${
this._viewMode == 'snapshots'
? html`<div class="frigate-card-gallery">
${until(this._renderEvents(), this._renderProgressIndicator())}
</div>`
: ``
}
${this._viewMode == "clip" ?
html`<div class="frigate-card-viewer">
${until(this._renderClipPlayer(), this._renderProgressIndicator())}
</div>` : ``
${
this._viewMode == 'clip'
? html`<div class="frigate-card-viewer">
${until(this._renderClipPlayer(), this._renderProgressIndicator())}
</div>`
: ``
}
${this._viewMode == "snapshot" ?
html`<div class="frigate-card-viewer">
${until(this._renderSnapshotViewer(), this._renderProgressIndicator())}
</div>` : ``
${
this._viewMode == 'snapshot'
? html`<div class="frigate-card-viewer">
${until(this._renderSnapshotViewer(), this._renderProgressIndicator())}
</div>`
: ``
}
${this._renderLiveViewer()}
<frigate-card-menu
@@ -665,9 +673,7 @@ export class FrigateCard extends LitElement {
// Show a warning card.
private _showWarning(warning: string): TemplateResult {
return html`
<hui-warning> ${warning} </hui-warning>
`;
return html` <hui-warning> ${warning} </hui-warning> `;
}
// Show an error card.
@@ -679,9 +685,7 @@ export class FrigateCard extends LitElement {
origConfig: this.config,
});
return html`
${errorCard}
`;
return html` ${errorCard} `;
}
// Return compiled CSS styles (thus safe to use with unsafeCSS).
@@ -693,4 +697,4 @@ export class FrigateCard extends LitElement {
static getCardSize(): number {
return 5;
}
}
}