Convert the viewer into a carousel.

This commit is contained in:
Dermot Duffy
2021-10-25 23:08:58 -07:00
parent c45c2ec973
commit 30adb637a8
5 changed files with 400 additions and 156 deletions
+1
View File
@@ -19,6 +19,7 @@
"@material/image-list": "^12.0.0", "@material/image-list": "^12.0.0",
"custom-card-helpers": "^1.8.0", "custom-card-helpers": "^1.8.0",
"dayjs": "^1.10.7", "dayjs": "^1.10.7",
"embla-carousel": "^5.0.1",
"home-assistant-js-websocket": "^5.11.1", "home-assistant-js-websocket": "^5.11.1",
"lit": "^2.0.2", "lit": "^2.0.2",
"screenfull": "^5.1.0", "screenfull": "^5.1.0",
+5 -1
View File
@@ -43,6 +43,10 @@ export async function homeAssistantWSRequest<T>(
return parseResult.data; return parseResult.data;
} }
export function isTrueMedia(media: BrowseMediaSource): boolean {
return !media.can_expand;
}
// From a BrowseMediaSource item extract the first true media item (i.e. a // From a BrowseMediaSource item extract the first true media item (i.e. a
// clip/snapshot, not a folder). // clip/snapshot, not a folder).
export function getFirstTrueMediaChildIndex( export function getFirstTrueMediaChildIndex(
@@ -52,7 +56,7 @@ export function getFirstTrueMediaChildIndex(
return null; return null;
} }
for (let i = 0; i < media.children.length; i++) { for (let i = 0; i < media.children.length; i++) {
if (!media.children[i].can_expand) { if (isTrueMedia(media.children[i])) {
return i; return i;
} }
} }
+17 -39
View File
@@ -2,72 +2,50 @@ import { CSSResultGroup, LitElement, TemplateResult, html, unsafeCSS } from 'lit
import { customElement, property } from 'lit/decorators.js'; import { customElement, property } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js'; import { classMap } from 'lit/directives/class-map.js';
import { BrowseMediaSource, NextPreviousControlStyle } from '../types.js'; import { NextPreviousControlStyle } from '../types.js';
import { View } from '../view.js';
import controlStyle from '../scss/next-previous-control.scss'; import controlStyle from '../scss/next-previous-control.scss';
@customElement('frigate-card-next-previous-control') @customElement('frigate-card-next-previous-control')
export class FrigateCardMessage extends LitElement { export class FrigateCardMessage extends LitElement {
@property({ attribute: false }) @property({ attribute: false })
protected control!: "next" | "previous"; protected direction?: 'next' | 'previous';
@property({ attribute: false }) @property({ attribute: false })
protected controlStyle!: NextPreviousControlStyle; protected controlStyle?: NextPreviousControlStyle;
@property({ attribute: false }) @property({ attribute: false })
protected parent!: BrowseMediaSource; protected thumbnail?: string;
@property({ attribute: false }) protected render(): TemplateResult {
protected childIndex!: number; if (!this.controlStyle || this.controlStyle == 'none') {
@property({ attribute: false })
protected view!: View;
protected _changeView(): void {
new View({
view: this.view.view,
target: this.parent,
childIndex: this.childIndex,
}).dispatchChangeEvent(this);
}
protected render() : TemplateResult {
if (this.controlStyle == 'none' || !this.parent.children) {
return html``;
}
const target = this.parent.children[this.childIndex];
if (!target) {
return html``; return html``;
} }
const classes = { const classes = {
controls: true, controls: true,
previous: this.control == "previous", previous: this.direction == 'previous',
next: this.control == "next", next: this.direction == 'next',
thumbnails: this.controlStyle == "thumbnails", thumbnails: this.controlStyle == 'thumbnails',
chevrons: this.controlStyle == "chevrons", chevrons: this.controlStyle == 'chevrons',
button: this.controlStyle == "chevrons", button: this.controlStyle == 'chevrons',
}; };
if (this.controlStyle == "chevrons") { if (this.controlStyle == 'chevrons') {
return html` <ha-icon-button return html` <ha-icon-button
icon=${this.control == "previous" ? 'mdi:chevron-left' : 'mdi:chevron-right'} icon=${this.direction == 'previous' ? 'mdi:chevron-left' : 'mdi:chevron-right'}
class="${classMap(classes)}" class="${classMap(classes)}"
title=${target.title} title=${this.title}
@click=${this._changeView}
></ha-icon-button>`; ></ha-icon-button>`;
} }
if (!target.thumbnail) { if (!this.thumbnail) {
return html``; return html``;
} }
return html`<img return html`<img
src="${target.thumbnail}" src="${this.thumbnail}"
class="${classMap(classes)}" class="${classMap(classes)}"
title="${target.title}" title="${this.title}"
@click=${this._changeView}
/>`; />`;
} }
+337 -112
View File
@@ -1,7 +1,15 @@
import { CSSResultGroup, LitElement, TemplateResult, html, unsafeCSS } from 'lit'; import {
CSSResultGroup,
LitElement,
TemplateResult,
html,
unsafeCSS,
PropertyValues,
} from 'lit';
import EmblaCarousel, { EmblaCarouselType } from 'embla-carousel';
import { HomeAssistant } from 'custom-card-helpers';
import { customElement, property } from 'lit/decorators.js'; import { customElement, property } from 'lit/decorators.js';
import { until } from 'lit/directives/until.js'; import { until } from 'lit/directives/until.js';
import { HomeAssistant } from 'custom-card-helpers';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import dayjs_custom_parse_format from 'dayjs/plugin/customParseFormat.js'; import dayjs_custom_parse_format from 'dayjs/plugin/customParseFormat.js';
@@ -13,6 +21,7 @@ import type {
ExtendedHomeAssistant, ExtendedHomeAssistant,
NextPreviousControlStyle, NextPreviousControlStyle,
} from '../types.js'; } from '../types.js';
import { ResolvedMediaCache, ResolvedMediaUtil } from '../resolved-media.js';
import { localize } from '../localize/localize.js'; import { localize } from '../localize/localize.js';
import { import {
browseMediaQuery, browseMediaQuery,
@@ -22,17 +31,15 @@ import {
dispatchPauseEvent, dispatchPauseEvent,
dispatchPlayEvent, dispatchPlayEvent,
getFirstTrueMediaChildIndex, getFirstTrueMediaChildIndex,
isTrueMedia,
} from '../common.js'; } from '../common.js';
import { View } from '../view.js'; import { View } from '../view.js';
import { import { renderProgressIndicator } from '../components/message.js';
renderProgressIndicator,
} from '../components/message.js';
import './next-prev-control.js'; import './next-prev-control.js';
import viewerStyle from '../scss/viewer.scss'; import viewerStyle from '../scss/viewer.scss';
import { ResolvedMediaCache, ResolvedMediaUtil } from '../resolved-media.js';
// Load dayjs plugin(s). // Load dayjs plugin(s).
dayjs.extend(dayjs_custom_parse_format); dayjs.extend(dayjs_custom_parse_format);
@@ -61,6 +68,33 @@ export class FrigateCardViewer extends LitElement {
return html`${until(this._render(), renderProgressIndicator())}`; return html`${until(this._render(), renderProgressIndicator())}`;
} }
/**
* Resolve all the given media for a target.
* @param target The target to resolve media from.
* @returns True if the resolutions were all error free.
*/
protected async _resolveAllMediaForTarget(target: BrowseMediaSource): Promise<boolean> {
if (!this.hass) {
return false;
}
let errorFree = true;
for (let i = 0; target.children && i < (target.children || []).length; ++i) {
if (isTrueMedia(target.children[i])) {
errorFree &&= !!(await ResolvedMediaUtil.resolveMedia(
this.hass,
target.children[i],
this.resolvedMediaCache,
));
}
}
return errorFree;
}
/**
* Asyncronously render the element.
* @returns A template to render.
*/
protected async _render(): Promise<TemplateResult | void> { protected async _render(): Promise<TemplateResult | void> {
if (!this.hass || !this.view || !this.browseMediaQueryParameters) { if (!this.hass || !this.view || !this.browseMediaQueryParameters) {
return html``; return html``;
@@ -90,7 +124,7 @@ export class FrigateCardViewer extends LitElement {
view: this.view.view, view: this.view.view,
target: parent, target: parent,
childIndex: childIndex, childIndex: childIndex,
}) });
// In this block, no clip has been manually selected, so this is loading // In this block, no clip has been manually selected, so this is loading
// the most recent clip on card load. In this mode, autoplay of the clip // the most recent clip on card load. In this mode, autoplay of the clip
@@ -100,31 +134,29 @@ export class FrigateCardViewer extends LitElement {
autoplay = this.autoplayClip ?? true; autoplay = this.autoplayClip ?? true;
} }
const resolvedMedia = await ResolvedMediaUtil.resolveMedia( if (view.target && !(await this._resolveAllMediaForTarget(view.target))) {
this.hass, view.media, this.resolvedMediaCache);
if (!resolvedMedia) {
// Home Assistant could not resolve media item.
return dispatchErrorMessageEvent(this, localize('error.could_not_resolve')); return dispatchErrorMessageEvent(this, localize('error.could_not_resolve'));
} }
return html` return html` <frigate-card-viewer-core
<frigate-card-viewer-core .view=${view}
.view=${view} .nextPreviousControlStyle=${this.nextPreviousControlStyle}
.nextPreviousControlStyle=${this.nextPreviousControlStyle} .resolvedMediaCache=${this.resolvedMediaCache}
.resolvedMediaCache=${this.resolvedMediaCache} .autoplayClip=${autoplay}
.autoplayClip=${autoplay} .hass=${this.hass}
.hass=${this.hass} .browseMediaQueryParameters=${this.browseMediaQueryParameters}
.browseMediaQueryParameters=${this.browseMediaQueryParameters} >
> </frigate-card-viewer-core>`;
</frigate-card-viewer-core>`;
} }
/**
* Get element styles.
*/
static get styles(): CSSResultGroup { static get styles(): CSSResultGroup {
return unsafeCSS(viewerStyle); return unsafeCSS(viewerStyle);
} }
} }
@customElement('frigate-card-viewer-core') @customElement('frigate-card-viewer-core')
export class FrigateCardViewerCore extends LitElement { export class FrigateCardViewerCore extends LitElement {
@property({ attribute: false }) @property({ attribute: false })
@@ -145,6 +177,58 @@ export class FrigateCardViewerCore extends LitElement {
@property({ attribute: false }) @property({ attribute: false })
protected browseMediaQueryParameters?: BrowseMediaQueryParameters; protected browseMediaQueryParameters?: BrowseMediaQueryParameters;
// Media carousel object.
protected _carousel?: EmblaCarouselType;
protected _loadedCarousel = false;
// Mapping of slide # to BrowseMediaSource child #.
// (Folders are not media items that can be rendered).
protected _slideToChild: Record<number, number> = {};
/**
* The updated lifecycle callback for this element.
* @param changedProperties The properties that were changed in this render.
*/
updated(changedProperties: PropertyValues): void {
super.updated(changedProperties);
if (!this._loadedCarousel) {
this.updateComplete.then(() => {
this._loadCarousel();
});
}
}
/**
* Load the carousel with "slides" (clips or snapshots).
*/
protected _loadCarousel(): void {
const carouselNode = this.renderRoot.querySelector(
'.embla__viewport',
) as HTMLElement;
if (carouselNode) {
this._loadedCarousel = true;
// Start the carousel on the selected child number.
const startIndex = Number(
Object.keys(this._slideToChild).find(
(key) => this._slideToChild[key] === this.view?.childIndex,
),
);
this._carousel = EmblaCarousel(carouselNode, {
startIndex: isNaN(startIndex) ? undefined : startIndex,
});
this._carousel.on('select', this._slideSelectHandler.bind(this));
}
}
/**
* Get the event start time from a media object.
* @param browseMedia The media object to extract the start time from.
* @returns The start time in unix/epoch time, or null if it cannot be determined.
*/
protected _extractEventStartTimeFromBrowseMedia( protected _extractEventStartTimeFromBrowseMedia(
browseMedia: BrowseMediaSource, browseMedia: BrowseMediaSource,
): number | null { ): number | null {
@@ -162,12 +246,18 @@ export class FrigateCardViewerCore extends LitElement {
return null; return null;
} }
// Get the previous and next real media items, given the index /**
protected _getMediaNeighbors() : BrowseMediaNeighbors | null { * Get the previous and next true media items from the current view.
if (!this.view || * @returns A BrowseMediaNeighbors with indices and objects of true media
!this.view.target || * neighbors.
!this.view.target.children || */
this.view.childIndex === undefined) { protected _getMediaNeighbors(): BrowseMediaNeighbors | null {
if (
!this.view ||
!this.view.target ||
!this.view.target.children ||
this.view.childIndex === undefined
) {
return null; return null;
} }
@@ -175,7 +265,7 @@ export class FrigateCardViewerCore extends LitElement {
let prevIndex: number | null = null; let prevIndex: number | null = null;
for (let i = this.view.childIndex - 1; i >= 0; i--) { for (let i = this.view.childIndex - 1; i >= 0; i--) {
const media = this.view.target.children[i]; const media = this.view.target.children[i];
if (media && !media.can_expand) { if (media && isTrueMedia(media)) {
prevIndex = i; prevIndex = i;
break; break;
} }
@@ -185,7 +275,7 @@ export class FrigateCardViewerCore extends LitElement {
let nextIndex: number | null = null; let nextIndex: number | null = null;
for (let i = this.view.childIndex + 1; i < this.view.target.children.length; i++) { for (let i = this.view.childIndex + 1; i < this.view.target.children.length; i++) {
const media = this.view.target.children[i]; const media = this.view.target.children[i];
if (media && !media.can_expand) { if (media && isTrueMedia(media)) {
nextIndex = i; nextIndex = i;
break; break;
} }
@@ -199,115 +289,250 @@ export class FrigateCardViewerCore extends LitElement {
}; };
} }
// Get a clip at the same time as a snapshot. /**
protected async _findRelatedClips( * Get a clip view that matches a given snapshot. Includes clips within the
snapshot: BrowseMediaSource | null, * same range as the current view.
): Promise<BrowseMediaSource | null> { * @param snapshot The snapshot to find a matching clip for.
if (!snapshot || !this.hass || !this.browseMediaQueryParameters) { * @returns The view that would show the matching clip.
*/
protected async _findRelatedClipView(
snapshot: BrowseMediaSource,
): Promise<View | null> {
if (!this.hass ||
!this.view ||
!this.view.target ||
!this.view.target.children ||
!this.view.target.children.length ||
!this.browseMediaQueryParameters) {
return null; return null;
} }
const startTime = this._extractEventStartTimeFromBrowseMedia(snapshot); const snapshotStartTime = this._extractEventStartTimeFromBrowseMedia(snapshot);
if (startTime) { if (!snapshotStartTime) {
try { return null;
// Fetch clips within the same second (same camera/zone/label, etc). }
const clipsAtSameTime = await browseMediaQuery(this.hass, {
...this.browseMediaQueryParameters, // Heuristic: At this point, the user has a particular snapshot that they
mediaType: 'clips', // are interested in and want to see a related clip, yet the viewer code
before: startTime + 1, // does not know the exact search criteria that led to that snapshot (e.g.
after: startTime, // it could be a 10-deep folder in the gallery). To give the user to ability
// to 'navigate' in the clips view once they change into that mode, this
// heuristic finds the earliest and latest snapshot that the user is
// currently viewing and mirrors that range into the clips view. Then,
// within the results see if there's a clip that matches the same time as
// the snapshot.
let earliest: number | null = null, latest: number | null = null;
for (let i = 0; i < this.view.target.children.length; i++) {
const child = this.view.target.children[i];
if (!isTrueMedia(child)) {
continue;
}
const startTime = this._extractEventStartTimeFromBrowseMedia(child);
if (startTime && (earliest === null || startTime < earliest)) {
earliest = startTime;
}
if (startTime && (latest === null || startTime > latest)) {
latest = startTime;
}
}
if (!earliest || !latest) {
return null;
}
let clips: BrowseMediaSource | null;
try {
clips = await browseMediaQuery(this.hass, {
...this.browseMediaQueryParameters,
mediaType: 'clips',
before: latest,
after: earliest,
});
} catch (e) {
// This is best effort.
return null
}
console.info(clips);
if (!clips || !clips.children || !clips.children.length) {
return null;
}
for (let i = 0; i < clips.children.length; i++) {
const child = clips.children[i];
if (!isTrueMedia(child)) {
continue;
}
const clipStartTime = this._extractEventStartTimeFromBrowseMedia(child);
if (clipStartTime && clipStartTime === snapshotStartTime) {
return new View({
view: 'clip',
target: clips,
childIndex: i,
previous: this.view
}); });
if (clipsAtSameTime) {
const index = getFirstTrueMediaChildIndex(clipsAtSameTime);
if (index != null && clipsAtSameTime.children?.length) {
return clipsAtSameTime.children[index];
}
}
} catch (e) {
// Pass. This is best effort.
} }
} }
return null; return null;
} }
/**
* Handle the user selecting a new slide in the carousel.
*/
protected _slideSelectHandler(): void {
if (!this._carousel || !this.view) {
return;
}
// Update the childIndex in the view (without re-render)
const slidesInView = this._carousel.slidesInView(true);
if (slidesInView.length) {
const childIndex = this._slideToChild[slidesInView[0]];
if (childIndex !== undefined) {
// Update the currently live view in place.
this.view.childIndex = childIndex;
this.requestUpdate();
}
}
}
/**
* Handle a next/previous control interaction.
* @param direction The direction requested, previous or next.
*/
protected _nextPreviousHandler(direction: 'previous' | 'next'): void {
console.info(`next/prev handler: ${direction}`);
if (direction == 'previous') {
this._carousel?.scrollPrev();
} else if (direction == 'next') {
this._carousel?.scrollNext();
}
}
/**
* Render the element.
* @returns A template to display to the user.
*/
protected render(): TemplateResult | void { protected render(): TemplateResult | void {
if (!this.view || !this.resolvedMediaCache) { if (
!this.view ||
!this.view.target ||
!this.view.target.children ||
!this.view.target.children.length ||
this.view.childIndex === undefined ||
!this.resolvedMediaCache
) {
return html``; return html``;
} }
const mediaToRender = this.view.media; const slides: TemplateResult[] = [];
const resolvedMedia = mediaToRender ? this.resolvedMediaCache.get( this._slideToChild = {};
mediaToRender.media_content_id) : undefined;
if (!mediaToRender || !resolvedMedia) { for (let i = 0; i < this.view.target.children?.length; ++i) {
return html``; const slide = this._renderMediaItem(this.view.target.children[i]);
if (slide) {
this._slideToChild[slides.length] = i;
slides.push(slide);
}
} }
const neighbors = this._getMediaNeighbors(); const neighbors = this._getMediaNeighbors();
return html` <div>
${neighbors?.previousIndex != null return html`<div class="container">
${neighbors && neighbors.previous
? html`<frigate-card-next-previous-control ? html`<frigate-card-next-previous-control
.control=${'previous'} .direction=${'previous'}
.controlStyle=${this.nextPreviousControlStyle} .controlStyle=${this.nextPreviousControlStyle}
.parent=${this.view.target} .thumbnail=${neighbors.previous.thumbnail}
.childIndex=${neighbors.previousIndex} .title=${neighbors.previous.title}
.view=${this.view} @click=${() => this._nextPreviousHandler('previous')}
></frigate-card-next-previous-control>` ></frigate-card-next-previous-control>`
: ``} : ``}
${this.view.is('clip') <div class="embla">
? resolvedMedia?.mime_type.toLowerCase() == 'application/x-mpegurl' <div class="embla__viewport">
? html`<frigate-card-ha-hls-player <div class="embla__container">${slides}</div>
.hass=${this.hass} </div>
.url=${resolvedMedia.url} </div>
title="${mediaToRender.title}" ${neighbors && neighbors.next
muted
controls
playsinline
allow-exoplayer
?autoplay="${this.autoplayClip}"
>
</frigate-card-ha-hls-player>`
: html`<video
title="${mediaToRender.title}"
muted
controls
playsinline
?autoplay="${this.autoplayClip}"
@loadedmetadata=${(e) => dispatchMediaLoadEvent(this, e)}a
@play=${() => dispatchPlayEvent(this)}
@pause=${() => dispatchPauseEvent(this)}
>
<source src="${resolvedMedia.url}" type="${resolvedMedia.mime_type}" />
</video>`
: html`<img
src=${resolvedMedia.url}
title="${mediaToRender.title}"
@click=${() => {
// Get clips potentially related to this snapshot.
this._findRelatedClips(mediaToRender).then((relatedClip) => {
if (relatedClip) {
new View({
view: 'clip',
target: relatedClip,
}).dispatchChangeEvent(this);
}
});
}}
@load=${(e) => {
dispatchMediaLoadEvent(this, e);
}}
/>`}
${neighbors?.nextIndex != null
? html`<frigate-card-next-previous-control ? html`<frigate-card-next-previous-control
.control=${'next'} .direction=${'next'}
.controlStyle=${this.nextPreviousControlStyle} .controlStyle=${this.nextPreviousControlStyle}
.parent=${this.view.target} .thumbnail=${neighbors.next.thumbnail}
.childIndex=${neighbors.nextIndex} .title=${neighbors.next.title}
.view=${this.view} @click=${() => this._nextPreviousHandler('next')}
></frigate-card-next-previous-control>` ></frigate-card-next-previous-control>`
: ``} : ``}
</div>`; </div>`;
} }
/**
* Render a given media item.
* @param mediaToRender The media item to render.
* @returns A template or void if the item could not be rendered.
*/
protected _renderMediaItem(mediaToRender: BrowseMediaSource): TemplateResult | void {
// media that can be expanded (folders) cannot be resolved to a single media
// item, skip them.
if (!this.view || !isTrueMedia(mediaToRender)) {
return;
}
const resolvedMedia = this.resolvedMediaCache?.get(mediaToRender.media_content_id);
if (!resolvedMedia) {
return;
}
return html`
<div class="embla__slide">
${this.view.is('clip')
? resolvedMedia?.mime_type.toLowerCase() == 'application/x-mpegurl'
? html`<frigate-card-ha-hls-player
.hass=${this.hass}
.url=${resolvedMedia.url}
title="${mediaToRender.title}"
muted
controls
playsinline
allow-exoplayer
?autoplay="${this.autoplayClip}"
>
</frigate-card-ha-hls-player>`
: html`<video
title="${mediaToRender.title}"
muted
controls
playsinline
?autoplay="${this.autoplayClip}"
@loadedmetadata="${(e) => dispatchMediaLoadEvent(this, e)}"
@play=${() => dispatchPlayEvent(this)}
@pause=${() => dispatchPauseEvent(this)}
>
<source src="${resolvedMedia.url}" type="${resolvedMedia.mime_type}" />
</video>`
: html`<img
src=${resolvedMedia.url}
title="${mediaToRender.title}"
@click=${() => {
if (this._carousel?.clickAllowed()) {
this._findRelatedClipView(mediaToRender).then((view) => {
if (view) {
view.dispatchChangeEvent(this);
}
});
}
}}
@load=${(e) => {
dispatchMediaLoadEvent(this, e);
}}
/>`}
</div>
`;
}
/**
* Get element styles.
*/
static get styles(): CSSResultGroup { static get styles(): CSSResultGroup {
return unsafeCSS(viewerStyle); return unsafeCSS(viewerStyle);
} }
+39 -3
View File
@@ -2,11 +2,47 @@ ha-hls-player {
transform-style: preserve-3d; transform-style: preserve-3d;
} }
img,video { img,video {
width: 100%;
height: 100%;
display: block; display: block;
max-width: 100%;
} }
div {
div.container {
// Keep the controls positioned relative to the video. // Keep the controls positioned relative to the video.
position: relative; position: relative;
} }
.embla {
position: relative;
margin-left: auto;
margin-right: auto;
}
.embla__viewport {
overflow: hidden;
width: 100%;
}
.embla__container {
display: flex;
user-select: none;
-webkit-touch-callout: none;
-khtml-user-select: none;
-webkit-tap-highlight-color: transparent;
}
.embla__viewport.is-draggable {
cursor: move;
cursor: grab;
}
.embla__viewport.is-dragging {
cursor: grabbing;
}
.embla__slide {
position: relative;
min-width: 100%;
max-width: 100%;
margin-right: 10px;
overflow: hidden;
}