Compare commits

..
Author SHA1 Message Date
Aidan Timson 559775af9d Flatten the Status filter on the entities page 2026-11-24 14:53:54 +00:00
19 changed files with 113 additions and 732 deletions

No files matched your search

-2
View File
@@ -10,8 +10,6 @@ const SWIPE_LOCKED_COMPONENTS = new Set([
"ha-chart-base",
"ha-more-info-control-select-container",
"ha-filter-chip",
// Toasts are inside the sheet while it is open
"notification-manager",
]);
const SWIPE_LOCKED_CLASSES = new Set([
-8
View File
@@ -1,8 +0,0 @@
/** Loads an image, resolves with undefined when it can't be loaded. */
export const loadImage = (url: string): Promise<HTMLImageElement | undefined> =>
new Promise((resolve) => {
const image = new Image();
image.onload = () => resolve(image);
image.onerror = () => resolve(undefined);
image.src = url;
});
-35
View File
@@ -1,35 +0,0 @@
// Containers of the open modal dialogs, in opening order. A child of a
// container is in the flat tree of its native modal `<dialog>`.
const OPEN_MODALS: HTMLElement[] = [];
const listeners = new Set<() => void>();
/**
* Tracks a modal dialog. While a modal is open the browser makes everything
* outside it inert, so an element that must stay interactive has to move into
* the topmost container.
*/
export const setModalOpen = (container: HTMLElement, open: boolean) => {
// A dialog removed right after it was opened still finishes opening
// afterwards, which would move the toasts off the page.
if (open && !container.isConnected) {
return;
}
const index = OPEN_MODALS.indexOf(container);
if (index === -1 && !open) {
return;
}
if (index !== -1) {
OPEN_MODALS.splice(index, 1);
}
if (open) {
OPEN_MODALS.push(container);
}
listeners.forEach((listener) => listener());
};
export const getTopModal = (): HTMLElement | undefined =>
OPEN_MODALS[OPEN_MODALS.length - 1];
export const subscribeOpenModals = (listener: () => void) => {
listeners.add(listener);
};
+39 -122
View File
@@ -14,7 +14,6 @@ import { customElement, property, query, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { styleMap } from "lit/directives/style-map";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import { storage } from "../../common/decorators/storage";
import { deepActiveElement } from "../../common/dom/deep-active-element";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { ctrlOrCmdLabel } from "../../common/keyboard/ctrl-or-cmd";
@@ -30,16 +29,13 @@ import "../ha-spinner";
import "../ha-svg-icon";
import "./ha-camera-stream-badge";
import {
fitPicture,
clampZoomPan,
isZoomed,
panBy,
refitZoomPan,
visiblePart,
ZOOM_PAN_IDENTITY,
zoomAtPoint,
type ZoomPan,
type ZoomPanSize,
type ZoomPanViewport,
} from "./zoom-pan";
const CONTROLS_TIMEOUT = 3000;
@@ -57,9 +53,6 @@ const WHEEL_ZOOM_SPEED = 0.0025;
// The longer side of the minimap of a zoomed in picture, in pixels
const MINIMAP_SIZE = 64;
// Most cameras, for the room the player keeps until it knows the picture
const DEFAULT_ASPECT_RATIO = 16 / 9;
interface PointerInfo {
x: number;
y: number;
@@ -112,15 +105,6 @@ export class HaCameraPlayer extends LitElement {
@state() private _zoom: ZoomPan = ZOOM_PAN_IDENTITY;
@state() private _pictureSize?: ZoomPanSize;
// Known before the stream's picture, so the player can make room for it
@state() private _posterSize?: ZoomPanSize;
// Of each camera's picture last time, so the player opens at its size
@storage({ key: "cameraAspectRatios", state: true, subscribe: false })
private _storedAspectRatios?: Record<string, number>;
@state() private _gesture = false;
@state() private _fullscreen = false;
@@ -146,13 +130,13 @@ export class HaCameraPlayer extends LitElement {
// More than one finger touched since all were lifted, so it is no tap
private _multiPointer = false;
// The viewport and picture the zoom was last made for
private _zoomViewport: ZoomPanViewport = fitPicture({ width: 0, height: 0 });
// The size of the viewport the zoom was last made for
private _zoomSize: ZoomPanSize = { width: 0, height: 0 };
private _viewportResize = new ResizeController(this, {
target: null,
skipInitial: true,
callback: () => this._refitZoom(),
callback: () => this._viewportResized(),
});
private _controlsTimeout?: number;
@@ -217,8 +201,6 @@ export class HaCameraPlayer extends LitElement {
const oldStateObj = changedProps.get("stateObj");
if (oldStateObj && oldStateObj.entity_id !== this.stateObj?.entity_id) {
this._zoom = ZOOM_PAN_IDENTITY;
this._pictureSize = undefined;
this._posterSize = undefined;
}
}
@@ -276,11 +258,6 @@ export class HaCameraPlayer extends LitElement {
"camera-player-zoomed": zoomed,
gesture: this._gesture,
})}
style=${styleMap({
aspectRatio: this._fullscreen
? undefined
: String(this._aspectRatio()),
})}
@pointerdown=${this._pointerDown}
@pointerup=${this._pointerUp}
@pointercancel=${this._pointerCancel}
@@ -294,7 +271,6 @@ export class HaCameraPlayer extends LitElement {
.allowExoPlayer=${this.allowExoPlayer}
.muted=${this._muted}
mjpeg-video
measure-poster
style=${styleMap({
transform: zoomed
? `translate(${this._zoom.x}px, ${this._zoom.y}px) scale(${this._zoom.scale})`
@@ -303,7 +279,6 @@ export class HaCameraPlayer extends LitElement {
@camera-stream-status-changed=${this._statusChanged}
@load=${this._updateVideo}
@camera-capabilities-changed=${this._capabilitiesChanged}
@camera-poster-size-changed=${this._posterSizeChanged}
></ha-camera-stream>
</div>
${inApp ? nothing : this._renderControls(status, zoomed, badgeVisible)}
@@ -425,12 +400,12 @@ export class HaCameraPlayer extends LitElement {
* which isn't mirrored in right to left languages.
*/
private _renderMinimap() {
const { width, height } = this._zoomViewport.picture;
const { scale, x, y } = this._zoom;
const { width, height } = this._zoomSize;
if (!width || !height) {
return nothing;
}
const longSide = Math.max(width, height);
const area = visiblePart(this._zoom, this._zoomViewport);
return html`<div
class=${classMap({ minimap: true, gesture: this._gesture })}
style=${styleMap({
@@ -442,10 +417,10 @@ export class HaCameraPlayer extends LitElement {
<div
class="area"
style=${styleMap({
left: `${area.x * 100}%`,
top: `${area.y * 100}%`,
width: `${area.width * 100}%`,
height: `${area.height * 100}%`,
left: `${(-x / (width * scale)) * 100}%`,
top: `${(-y / (height * scale)) * 100}%`,
width: `${100 / scale}%`,
height: `${100 / scale}%`,
})}
></div>
</div>`;
@@ -548,30 +523,6 @@ export class HaCameraPlayer extends LitElement {
this._capabilities = ev.detail.capabilities;
}
/**
* Of the stream's picture, until then of the camera's picture last time,
* its poster or most cameras'.
*/
private _aspectRatio(): number {
if (this._pictureSize) {
return this._pictureSize.width / this._pictureSize.height;
}
const stored =
this.stateObj && this._storedAspectRatios?.[this.stateObj.entity_id];
if (stored) {
return stored;
}
return this._posterSize
? this._posterSize.width / this._posterSize.height
: DEFAULT_ASPECT_RATIO;
}
private _posterSizeChanged(
ev: HASSDomEvent<HASSDomEvents["camera-poster-size-changed"]>
) {
this._posterSize = ev.detail.size;
}
private _showStreamInfo() {
showCameraStreamInfoDialog(this, {
status: this._status,
@@ -587,7 +538,6 @@ export class HaCameraPlayer extends LitElement {
return;
}
this._video = this._stream?.videoElement;
this._updatePictureSize();
// Binds the video first, which resets its paused state
await this.updateComplete;
if (!this._status.connecting) {
@@ -627,7 +577,6 @@ export class HaCameraPlayer extends LitElement {
for (const type of ["play", "pause", "emptied"]) {
video.addEventListener(type, this._updatePaused);
}
video.addEventListener("resize", this._updatePictureSize);
// Only a pause from outside shows the play button, not the moment before
// a new video starts playing
this._paused = false;
@@ -646,7 +595,6 @@ export class HaCameraPlayer extends LitElement {
for (const type of ["play", "pause", "emptied"]) {
video?.removeEventListener(type, this._updatePaused);
}
video?.removeEventListener("resize", this._updatePictureSize);
video?.removeEventListener(
"enterpictureinpicture",
this._pictureInPictureChanged
@@ -755,56 +703,35 @@ export class HaCameraPlayer extends LitElement {
}
}
private _updatePictureSize = () => {
const size = this._stream?.pictureSize;
if (
size &&
(size.width !== this._pictureSize?.width ||
size.height !== this._pictureSize.height)
) {
this._pictureSize = size;
this._storeAspectRatio(size.width / size.height);
}
// The new picture can have another size
this._refitZoom();
};
private _storeAspectRatio(aspectRatio: number) {
const entityId = this.stateObj?.entity_id;
if (!entityId || this._storedAspectRatios?.[entityId] === aspectRatio) {
return;
}
this._storedAspectRatios = {
...this._storedAspectRatios,
[entityId]: aspectRatio,
};
}
private _measureViewport() {
private _viewportSize() {
const rect = this._viewport!.getBoundingClientRect();
// Kept for the minimap, every zoom and pan measures it first
this._zoomViewport = fitPicture(
{ width: rect.width, height: rect.height },
this._stream?.pictureSize ?? this._pictureSize ?? this._posterSize
);
return { rect, viewport: this._zoomViewport };
this._zoomSize = { width: rect.width, height: rect.height };
return { rect, size: this._zoomSize };
}
/**
* Keeps the same part of the picture in view when the viewport or the
* picture changes size.
* Keeps the same part of the picture in view when the size changes, like
* when turning a phone.
*/
private _refitZoom = () => {
const oldViewport = this._zoomViewport;
if (!isZoomed(this._zoom) || !this._viewport || !oldViewport.width) {
private _viewportResized() {
const oldSize = this._zoomSize;
if (!isZoomed(this._zoom) || !this._viewport || !oldSize.width) {
return;
}
const { viewport } = this._measureViewport();
if (!viewport.width || !viewport.height) {
const { size } = this._viewportSize();
if (!size.width || !size.height) {
return;
}
this._zoom = refitZoomPan(this._zoom, oldViewport, viewport);
};
this._zoom = clampZoomPan(
{
scale: this._zoom.scale,
x: (this._zoom.x * size.width) / oldSize.width,
y: (this._zoom.y * size.height) / oldSize.height,
},
size
);
}
private _resetZoom() {
this._zoom = ZOOM_PAN_IDENTITY;
@@ -822,7 +749,7 @@ export class HaCameraPlayer extends LitElement {
// Also keeps the browser from zooming the whole page
ev.preventDefault();
this._hideWheelHint();
const { rect, viewport } = this._measureViewport();
const { rect, size } = this._viewportSize();
// Lines instead of pixels, like in Firefox with a mouse wheel
const delta =
ev.deltaMode === WheelEvent.DOM_DELTA_LINE ? ev.deltaY * 33 : ev.deltaY;
@@ -831,7 +758,7 @@ export class HaCameraPlayer extends LitElement {
this._zoom,
this._zoom.scale * Math.exp(-clampedDelta * WHEEL_ZOOM_SPEED),
{ x: ev.clientX - rect.left, y: ev.clientY - rect.top },
viewport
size
);
}
@@ -862,12 +789,12 @@ export class HaCameraPlayer extends LitElement {
this._resetZoom();
return;
}
const { rect, viewport } = this._measureViewport();
const { rect, size } = this._viewportSize();
this._zoom = zoomAtPoint(
this._zoom,
2,
{ x: ev.clientX - rect.left, y: ev.clientY - rect.top },
viewport
size
);
}
@@ -901,7 +828,7 @@ export class HaCameraPlayer extends LitElement {
if (!pointer || !this._viewport) {
return;
}
const { rect, viewport } = this._measureViewport();
const { rect, size } = this._viewportSize();
if (this._pointers.size === 2) {
const [a, b] = [...this._pointers.values()];
@@ -919,13 +846,13 @@ export class HaCameraPlayer extends LitElement {
this._zoom,
(this._zoom.scale * newDistance) / oldDistance,
{ x: oldCenter.x - rect.left, y: oldCenter.y - rect.top },
viewport
size
);
this._zoom = panBy(
zoomed,
newCenter.x - oldCenter.x,
newCenter.y - oldCenter.y,
viewport
size
);
return;
}
@@ -935,7 +862,7 @@ export class HaCameraPlayer extends LitElement {
pointer.x = ev.clientX;
pointer.y = ev.clientY;
if (this._pointers.size === 1 && isZoomed(this._zoom)) {
this._zoom = panBy(this._zoom, dx, dy, viewport);
this._zoom = panBy(this._zoom, dx, dy, size);
}
}
@@ -1026,18 +953,12 @@ export class HaCameraPlayer extends LitElement {
.viewport {
position: relative;
overflow: hidden;
max-height: var(--video-max-height, calc(100vh - 97px));
/* As wide as the player also when its height is limited, which the
aspect ratio would otherwise limit the width with, so the zoomed in
picture and gestures reach into the bars next to it */
width: 100%;
/* Scrolls the page until zoomed in, pinches are handled here */
touch-action: pan-x pan-y;
/* From the poster's or a default size to the stream's */
transition: aspect-ratio var(--ha-animation-duration-normal) ease-out;
}
.player.fullscreen .viewport {
.player.fullscreen .viewport,
.player.fullscreen ha-camera-stream {
width: 100%;
height: 100%;
}
@@ -1051,11 +972,7 @@ export class HaCameraPlayer extends LitElement {
cursor: grabbing;
}
/* Sized by the viewport, a video without a picture yet would be only
as high as an empty video */
ha-camera-stream {
width: 100%;
height: 100%;
transform-origin: 0 0;
transition: transform var(--ha-animation-duration-fast) ease-out;
}
+12 -130
View File
@@ -1,7 +1,6 @@
/**
* Zoom and pan of a picture in a viewport, applied as
* `translate(x, y) scale(scale)` with the transform origin at the top left
* of the viewport.
* Zoom and pan of content that fills a viewport, applied as
* `translate(x, y) scale(scale)` with the transform origin at the top left.
*/
export interface ZoomPan {
scale: number;
@@ -14,87 +13,28 @@ export interface ZoomPanSize {
height: number;
}
export interface ZoomPanRect extends ZoomPanSize {
x: number;
y: number;
}
/**
* The viewport and where the picture shows in it before zooming, with bars
* next to it when their aspect ratios differ.
*/
export interface ZoomPanViewport extends ZoomPanSize {
picture: ZoomPanRect;
}
export const ZOOM_PAN_IDENTITY: ZoomPan = { scale: 1, x: 0, y: 0 };
export const MAX_ZOOM = 5;
export const isZoomed = (zoomPan: ZoomPan): boolean => zoomPan.scale > 1;
/**
* The viewport with the picture fit in its middle, like `object-fit:
* contain`. Without the size of the picture, it fills the viewport.
*/
export const fitPicture = (
{ width, height }: ZoomPanSize,
pictureSize?: ZoomPanSize
): ZoomPanViewport => {
if (!pictureSize?.width || !pictureSize.height || !width || !height) {
return { width, height, picture: { x: 0, y: 0, width, height } };
}
const fit = Math.min(width / pictureSize.width, height / pictureSize.height);
const pictureWidth = pictureSize.width * fit;
const pictureHeight = pictureSize.height * fit;
return {
width,
height,
picture: {
x: (width - pictureWidth) / 2,
y: (height - pictureHeight) / 2,
width: pictureWidth,
height: pictureHeight,
},
};
};
/**
* The offset on one axis that keeps the zoomed picture covering the viewport,
* or in its middle while it is still smaller than the viewport.
*/
const clampOffset = (
offset: number,
scale: number,
viewportLength: number,
pictureStart: number,
pictureLength: number
): number => {
const scaledLength = pictureLength * scale;
if (scaledLength <= viewportLength) {
return (viewportLength - scaledLength) / 2 - pictureStart * scale;
}
const min = viewportLength - (pictureStart + pictureLength) * scale;
// Not -0 when the picture starts at the edge of the viewport
const max = 0 - pictureStart * scale;
return Math.min(max, Math.max(min, offset));
};
/** Keeps the scale in range and the bars next to the picture out of view. */
/** Keeps the scale in range and the content covering the whole viewport. */
export const clampZoomPan = (
{ scale, x, y }: ZoomPan,
viewport: ZoomPanViewport,
{ width, height }: ZoomPanSize,
maxScale = MAX_ZOOM
): ZoomPan => {
const clampedScale = Math.min(Math.max(scale, 1), maxScale);
if (clampedScale === 1) {
return ZOOM_PAN_IDENTITY;
}
const { picture } = viewport;
const minX = width - width * clampedScale;
const minY = height - height * clampedScale;
return {
scale: clampedScale,
x: clampOffset(x, clampedScale, viewport.width, picture.x, picture.width),
y: clampOffset(y, clampedScale, viewport.height, picture.y, picture.height),
x: Math.min(0, Math.max(minX, x)),
y: Math.min(0, Math.max(minY, y)),
};
};
@@ -106,7 +46,7 @@ export const zoomAtPoint = (
zoomPan: ZoomPan,
scale: number,
point: { x: number; y: number },
viewport: ZoomPanViewport,
size: ZoomPanSize,
maxScale = MAX_ZOOM
): ZoomPan => {
const clampedScale = Math.min(Math.max(scale, 1), maxScale);
@@ -117,7 +57,7 @@ export const zoomAtPoint = (
x: point.x - (point.x - zoomPan.x) * ratio,
y: point.y - (point.y - zoomPan.y) * ratio,
},
viewport,
size,
maxScale
);
};
@@ -126,69 +66,11 @@ export const panBy = (
zoomPan: ZoomPan,
dx: number,
dy: number,
viewport: ZoomPanViewport,
size: ZoomPanSize,
maxScale = MAX_ZOOM
): ZoomPan =>
clampZoomPan(
{ ...zoomPan, x: zoomPan.x + dx, y: zoomPan.y + dy },
viewport,
size,
maxScale
);
/**
* Keeps the part of the picture in the middle of the viewport there when the
* viewport or the picture changes size, like when turning a phone.
*/
export const refitZoomPan = (
zoomPan: ZoomPan,
oldViewport: ZoomPanViewport,
newViewport: ZoomPanViewport,
maxScale = MAX_ZOOM
): ZoomPan => {
const { scale } = zoomPan;
const oldPicture = oldViewport.picture;
const newPicture = newViewport.picture;
if (!isZoomed(zoomPan) || !oldPicture.width || !oldPicture.height) {
return clampZoomPan(zoomPan, newViewport, maxScale);
}
const centerX =
((oldViewport.width / 2 - zoomPan.x) / scale - oldPicture.x) /
oldPicture.width;
const centerY =
((oldViewport.height / 2 - zoomPan.y) / scale - oldPicture.y) /
oldPicture.height;
return clampZoomPan(
{
scale,
x:
newViewport.width / 2 -
(newPicture.x + centerX * newPicture.width) * scale,
y:
newViewport.height / 2 -
(newPicture.y + centerY * newPicture.height) * scale,
},
newViewport,
maxScale
);
};
/**
* The part of the picture that shows, as fractions of the picture between 0
* and 1.
*/
export const visiblePart = (
{ scale, x, y }: ZoomPan,
{ width, height, picture }: ZoomPanViewport
): ZoomPanRect => {
if (!picture.width || !picture.height) {
return { x: 0, y: 0, width: 1, height: 1 };
}
const left = Math.max(0, (-x / scale - picture.x) / picture.width);
const right = Math.min(1, ((width - x) / scale - picture.x) / picture.width);
const top = Math.max(0, (-y / scale - picture.y) / picture.height);
const bottom = Math.min(
1,
((height - y) / scale - picture.y) / picture.height
);
return { x: left, y: top, width: right - left, height: bottom - top };
};
+1 -9
View File
@@ -7,7 +7,6 @@ import { consume } from "../common/decorators/consume";
import type { HASSDomEvent } from "../common/dom/fire_event";
import { fireEvent } from "../common/dom/fire_event";
import { isSwipeLocked } from "../common/dom/is-swipe-locked";
import { setModalOpen } from "../common/dom/open-modals";
import { SwipeGestureRecognizer } from "../common/util/swipe-gesture-recognizer";
import { configContext } from "../data/context";
import { ScrollableFadeMixin } from "../mixins/scrollable-fade-mixin";
@@ -80,12 +79,9 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
private _escapePressed = false;
private _handleShow = async (ev: Event) => {
private _handleShow = async () => {
this._drawerOpen = true;
this.open = true;
if (ev.eventPhase === Event.AT_TARGET) {
setModalOpen(this._drawer, true);
}
fireEvent(this, "opened");
await this.updateComplete;
@@ -135,7 +131,6 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
if (ev.eventPhase === Event.AT_TARGET) {
this.open = false;
this._drawerOpen = false;
setModalOpen(this._drawer, false);
fireEvent(this, "closed");
}
};
@@ -374,9 +369,6 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
disconnectedCallback() {
super.disconnectedCallback();
if (this._drawer) {
setModalOpen(this._drawer, false);
}
this.removeEventListener(
"slider-interaction-start",
this._handleSliderInteractionStart,
+3 -52
View File
@@ -7,7 +7,6 @@ import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { consume } from "../common/decorators/consume";
import { fireEvent, type HASSDomEvent } from "../common/dom/fire_event";
import { loadImage } from "../common/dom/load-image";
import { supportsFeature } from "../common/entity/supports-feature";
import {
CameraEntityFeature,
@@ -86,14 +85,6 @@ export class HaCameraStream extends LitElement {
@property({ type: Boolean, attribute: "mjpeg-video" })
public mjpegVideo = false;
/**
* Loads the poster first to tell its size with
* `camera-poster-size-changed`, so a player can make room for it before
* the stream loads.
*/
@property({ type: Boolean, attribute: "measure-poster" })
public measurePoster = false;
// Video background image before its loaded
@state() private _posterUrl?: string;
@@ -180,21 +171,6 @@ export class HaCameraStream extends LitElement {
return this._visiblePlayer?.videoElement;
}
/**
* The size of the shown stream's picture, before it is fit into the
* player. Undefined until it is known.
*/
public get pictureSize(): { width: number; height: number } | undefined {
const player = this._visiblePlayer;
if (player && player === this._mjpegPlayer) {
return this._mjpegPlayer.pictureSize;
}
const video = player?.videoElement;
return video?.videoWidth
? { width: video.videoWidth, height: video.videoHeight }
: undefined;
}
/** Opens the video of the shown stream picture in picture. */
public async requestPictureInPicture() {
const player = this._visiblePlayer;
@@ -401,41 +377,17 @@ export class HaCameraStream extends LitElement {
}
private async _getPosterUrl(): Promise<void> {
const entityId = this.stateObj!.entity_id;
let posterUrl: string | undefined;
try {
posterUrl = await fetchThumbnailUrlWithCache(
this._posterUrl = await fetchThumbnailUrlWithCache(
this._thumbnailApi(this._api, this._connection),
entityId,
this.stateObj!.entity_id,
this.clientWidth,
this.clientHeight
);
} catch (_err: any) {
// poster url is optional
this._posterUrl = undefined;
}
if (!this.measurePoster) {
if (this.stateObj?.entity_id === entityId) {
this._posterUrl = posterUrl;
}
return;
}
// Loaded here first for its size, the poster then uses the same image
// instead of asking the camera again
const poster = posterUrl ? await loadImage(posterUrl) : undefined;
if (this.stateObj?.entity_id !== entityId) {
return;
}
this._posterUrl = posterUrl;
fireEvent(
this,
"camera-poster-size-changed",
{
size: poster?.naturalWidth
? { width: poster.naturalWidth, height: poster.naturalHeight }
: undefined,
},
{ bubbles: false, composed: false }
);
}
private _handleImageLoad() {
@@ -539,7 +491,6 @@ declare global {
"stream-type-changed": { type?: CameraStreamType };
"camera-capabilities-changed": { capabilities?: CameraCapabilities };
"camera-stream-status-changed": CameraStreamStatus;
"camera-poster-size-changed": { size?: { width: number; height: number } };
streams: {
hasAudio: boolean;
hasVideo: boolean;
-8
View File
@@ -15,7 +15,6 @@ import { ifDefined } from "lit/directives/if-defined";
import { consume } from "../common/decorators/consume";
import type { HASSDomEvent } from "../common/dom/fire_event";
import { fireEvent } from "../common/dom/fire_event";
import { setModalOpen } from "../common/dom/open-modals";
import { withViewTransition } from "../common/util/view-transition";
import { configContext, internationalizationContext } from "../data/context";
import { ScrollableFadeMixin } from "../mixins/scrollable-fade-mixin";
@@ -130,8 +129,6 @@ export class HaDialog extends ScrollableFadeMixin(LitElement) {
@query(".body") public bodyContainer!: HTMLDivElement;
@query("wa-dialog") private _dialog?: WaDialog;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n?: ContextType<typeof internationalizationContext>;
@@ -239,7 +236,6 @@ export class HaDialog extends ScrollableFadeMixin(LitElement) {
return;
}
this._open = true;
setModalOpen(ev.currentTarget as WaDialog, true);
fireEvent(this, "opened");
await this.updateComplete;
@@ -278,7 +274,6 @@ export class HaDialog extends ScrollableFadeMixin(LitElement) {
if (ev.eventPhase === Event.AT_TARGET) {
this._open = false;
this._setFullscreen(false);
setModalOpen(ev.currentTarget as WaDialog, false);
fireEvent(this, "closed");
}
};
@@ -289,9 +284,6 @@ export class HaDialog extends ScrollableFadeMixin(LitElement) {
this._handleFullscreenChanged as EventListener
);
this._setFullscreen(false);
if (this._dialog) {
setModalOpen(this._dialog, false);
}
super.disconnectedCallback();
this._open = false;
}
+28 -101
View File
@@ -20,7 +20,6 @@ import "./ha-expansion-panel";
import "./ha-icon";
import "./ha-icon-button";
import "./ha-svg-icon";
import "./ha-tree-indicator";
import "./item/ha-list-item-option";
import type { HaListItemOption } from "./item/ha-list-item-option";
import "./list/ha-list-selectable";
@@ -35,23 +34,6 @@ export interface FilterStateOption {
iconPath?: string;
}
/**
* Two opposite options, like available and unavailable, listed under a row
* that ticks or unticks both. The row is partly ticked when one of the two is.
*/
export interface FilterStatePair {
/** Identifies the row, apart from the values of its options */
value: string;
label: string;
iconPath?: string;
options: [FilterStateOption, FilterStateOption];
}
export type FilterStateItem = FilterStateOption | FilterStatePair;
const isPair = (item: FilterStateItem): item is FilterStatePair =>
"options" in item;
@customElement("ha-filter-states")
export class HaFilterStates extends LitElement {
@state()
@@ -62,7 +44,7 @@ export class HaFilterStates extends LitElement {
@property({ attribute: false }) public value?: string[];
@property({ attribute: false }) public states?: FilterStateItem[];
@property({ attribute: false }) public states?: FilterStateOption[];
@property({ type: Boolean }) public narrow = false;
@@ -108,10 +90,29 @@ export class HaFilterStates extends LitElement {
@ha-list-item-selected=${this._handleItemToggled}
@ha-list-item-deselected=${this._handleItemToggled}
>
${this.states.map((item) =>
isPair(item)
? this._renderPair(item)
: this._renderOption(item)
${this.states.map(
(item) =>
html`<ha-list-item-option
appearance="checkbox"
selection-position="end"
.value=${item.value}
.selected=${this.value?.includes(item.value) ?? false}
>
${
item.iconPath
? html`<ha-svg-icon
slot="start"
.path=${item.iconPath}
></ha-svg-icon>`
: item.icon
? html`<ha-icon
slot="start"
.icon=${item.icon}
></ha-icon>`
: nothing
}
<span slot="headline">${item.label}</span>
</ha-list-item-option>`
)}
</ha-list-selectable>
</div>
@@ -121,56 +122,6 @@ export class HaFilterStates extends LitElement {
`;
}
private _renderOption(item: FilterStateOption, nested?: { last: boolean }) {
return html`<ha-list-item-option
appearance="checkbox"
selection-position="end"
class=${nested ? "nested" : ""}
.value=${item.value}
.selected=${this.value?.includes(item.value) ?? false}
>
${
nested
? html`<ha-tree-indicator
slot="start"
.end=${nested.last}
></ha-tree-indicator>`
: nothing
}
${this._renderIcon(item)}
<span slot="headline">${item.label}</span>
</ha-list-item-option>`;
}
private _renderPair(pair: FilterStatePair) {
const picked = pair.options.filter((option) =>
this.value?.includes(option.value)
).length;
return html`<ha-list-item-option
appearance="checkbox"
selection-position="end"
.value=${pair.value}
.selected=${picked === pair.options.length}
.indeterminate=${picked > 0 && picked < pair.options.length}
>
${this._renderIcon(pair)}
<span slot="headline">${pair.label}</span>
</ha-list-item-option>
${pair.options.map((option, index) =>
this._renderOption(option, {
last: index === pair.options.length - 1,
})
)}`;
}
private _renderIcon(item: { icon?: string; iconPath?: string }) {
return item.iconPath
? html`<ha-svg-icon slot="start" .path=${item.iconPath}></ha-svg-icon>`
: item.icon
? html`<ha-icon slot="start" .icon=${item.icon}></ha-icon>`
: nothing;
}
private _expandedChanged(ev) {
this.expanded = ev.detail.expanded;
}
@@ -185,21 +136,10 @@ export class HaFilterStates extends LitElement {
return;
}
const selected = ev.type === "ha-list-item-selected";
// A pair row ticks or unticks both of its options
const pair = this.states?.find(
(item): item is FilterStatePair =>
isPair(item) && item.value === itemValue
);
const values = pair
? pair.options.map((option) => option.value)
: [itemValue];
this.value = values.reduce(
(value, val) =>
selected ? arrayWith(value, val) : arrayWithout(value, val),
this.value
);
this.value =
ev.type === "ha-list-item-selected"
? arrayWith(this.value, itemValue)
: arrayWithout(this.value, itemValue);
fireEvent(this, "data-table-filter-changed", {
value: this.value,
@@ -229,19 +169,6 @@ export class HaFilterStates extends LitElement {
flex: 1;
min-height: 0;
}
/* Options of a pair sit under it, like areas under their floor */
.nested::part(base) {
padding-inline-start: 48px;
}
ha-tree-indicator {
width: 56px;
position: absolute;
top: 0px;
inset-inline-start: 0px;
}
ha-tree-indicator:dir(rtl) {
transform: scaleX(-1);
}
.header {
display: flex;
align-items: center;
-15
View File
@@ -1,5 +1,4 @@
import type { ContextType } from "@lit/context";
import { ResizeController } from "@lit-labs/observers/resize-controller";
import type HlsType from "hls.js";
import type { PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
@@ -79,14 +78,6 @@ export class HaHLSPlayer extends LitElement {
private _exoPlayer = false;
// The app's player only follows the video when told, also when the video
// changes size without the window, like in a dialog that grows
private _exoPlayerResize = new ResizeController(this, {
target: null,
skipInitial: true,
callback: () => this._resizeExoPlayer(),
});
private static streamCount = 0;
private _hiddenCleanupTimeout?: number;
@@ -325,7 +316,6 @@ export class HaHLSPlayer extends LitElement {
this._exoPlayer = true;
fireEvent(this, "exoplayer-changed", { active: true });
window.addEventListener("resize", this._resizeExoPlayer);
this._exoPlayerResize.observe(this._videoEl);
this.updateComplete.then(() => nextRender()).then(this._resizeExoPlayer);
this._videoEl.style.visibility = "hidden";
await this._config.auth.external!.fireMessage({
@@ -458,7 +448,6 @@ export class HaHLSPlayer extends LitElement {
}
if (this._exoPlayer) {
window.removeEventListener("resize", this._resizeExoPlayer);
this._exoPlayerResize.unobserve(this._videoEl);
this._config.auth.external!.fireMessage({ type: "exoplayer/stop" });
this._exoPlayer = false;
fireEvent(this, "exoplayer-changed", { active: false });
@@ -511,12 +500,8 @@ export class HaHLSPlayer extends LitElement {
max-height: var(--video-max-height, calc(100vh - 97px));
}
/* Scrolls in a player that is only as high as its picture */
.fatal {
display: block;
box-sizing: border-box;
max-height: 100%;
overflow: auto;
padding: 100px 16px;
}
-8
View File
@@ -47,14 +47,6 @@ export class HaMjpegPlayer extends LitElement {
return this._canCopy ? this._videoEl : undefined;
}
/** The size of the stream's frames, undefined until the first one. */
public get pictureSize(): { width: number; height: number } | undefined {
const image = this._imageEl;
return image?.naturalWidth
? { width: image.naturalWidth, height: image.naturalHeight }
: undefined;
}
/**
* Starts copying the image into the video and opens it picture in
* picture. Stops copying again when it can't be opened.
+2 -27
View File
@@ -48,30 +48,10 @@ export class HaToast extends LitElement {
private _dismissTimer?: ReturnType<typeof setTimeout>;
// When the running dismiss timer ends. Kept while disconnected.
private _dismissAt?: number;
private _closeReason: ToastCloseReason = "programmatic";
private _transitionId = 0;
// The last request, to continue it after a move to another parent.
private _shown = false;
public connectedCallback(): void {
super.connectedCallback();
if (!this._active) {
return;
}
if (this._shown && this._dismissAt !== undefined) {
this._setDismissTimer(this._dismissAt);
} else if (this._shown) {
this.show();
} else {
this.hide(this._closeReason);
}
}
public disconnectedCallback(): void {
clearTimeout(this._dismissTimer);
this._transitionId += 1;
@@ -80,8 +60,6 @@ export class HaToast extends LitElement {
public async show(): Promise<void> {
clearTimeout(this._dismissTimer);
this._dismissAt = undefined;
this._shown = true;
if (this._active && this._visible) {
this._setDismissTimer();
@@ -117,8 +95,6 @@ export class HaToast extends LitElement {
public async hide(reason: ToastCloseReason = "programmatic"): Promise<void> {
clearTimeout(this._dismissTimer);
this._dismissAt = undefined;
this._shown = false;
this._closeReason = reason;
if (!this._active) {
@@ -153,12 +129,11 @@ export class HaToast extends LitElement {
this.hide(reason);
}
private _setDismissTimer(dismissAt = Date.now() + this.timeoutMs) {
private _setDismissTimer() {
if (this.timeoutMs > 0) {
this._dismissAt = dismissAt;
this._dismissTimer = setTimeout(() => {
this.hide("timeout");
}, dismissAt - Date.now());
}, this.timeoutMs);
}
}
-7
View File
@@ -852,13 +852,6 @@ export class HaWebRtcPlayer extends LitElement {
max-height: var(--video-max-height, calc(100vh - 97px));
}
/* Scrolls in a player that is only as high as its picture */
ha-alert {
display: block;
max-height: 100%;
overflow: auto;
}
.reconnecting {
position: absolute;
inset: 0;
+1 -5
View File
@@ -229,11 +229,7 @@ export const showDialog = async (
}
const targetParent = (parentElement || element).shadowRoot!;
if (
dialogElement!.parentNode !== targetParent &&
// The notification manager moves itself into the topmost modal.
!(NON_MODAL_DIALOG_TAGS.has(dialogTag) && dialogElement!.isConnected)
) {
if (dialogElement!.parentNode !== targetParent) {
targetParent.appendChild(dialogElement!);
}
-40
View File
@@ -14,8 +14,6 @@ import type {
HASSDomCurrentTargetEvent,
HASSDomEvent,
} from "../common/dom/fire_event";
import { getTopModal, subscribeOpenModals } from "../common/dom/open-modals";
import { stopKeydownEnterSpacePropagation } from "../common/dom/stop_propagation";
import { popoverSupported } from "../common/feature-detect/support-popover";
import type { LocalizeKeys } from "../common/translations/localize";
import "../components/ha-button";
@@ -67,36 +65,6 @@ class NotificationManager extends LitElement {
private _anonymousId = 0;
private _home?: ParentNode;
public connectedCallback(): void {
super.connectedCallback();
if (this._home) {
return;
}
this._home = this.parentNode!;
subscribeOpenModals(this._modalsChanged);
this._modalsChanged();
}
// A dialog reports that it opens before it enters the top layer. Wait, so
// that the stack enters the top layer after the dialog and paints above it.
private _modalsChanged = () => {
queueMicrotask(this._moveToTopModal);
};
// A modal dialog makes everything outside it inert, so the toasts must be
// inside the topmost one for their buttons to work.
private _moveToTopModal = () => {
const parent = getTopModal() ?? this._home!;
if (this.parentNode !== parent) {
parent.appendChild(this);
}
// Also when staying, as a bottom sheet that reopens itself enters the top
// layer again above the stack.
this._showStack();
};
public async showDialog(parameters: ShowToastParams) {
if (parameters.duration === 0) {
if (parameters.id) {
@@ -163,8 +131,6 @@ class NotificationManager extends LitElement {
({ parameters }) => parameters.bottomOffset ?? 0
)
);
// Inside a dialog, Enter on a toast button would otherwise also reach
// dialogs that submit on Enter, like the one to add a user.
return html`
<div
class="stack"
@@ -172,8 +138,6 @@ class NotificationManager extends LitElement {
"--notification-stack-bottom-offset": `${bottomOffset}px`,
})}
popover=${ifDefined(popoverSupported ? "manual" : undefined)}
@keydown=${stopKeydownEnterSpacePropagation}
@keypress=${stopKeydownEnterSpacePropagation}
>
${repeat(
this._notifications,
@@ -322,10 +286,6 @@ class NotificationManager extends LitElement {
}
static override styles = css`
:host {
/* No box, so the manager does not change the layout of a dialog. */
display: contents;
}
.stack {
position: fixed;
inset-block-start: auto;
@@ -7,14 +7,11 @@ import {
mdiDotsVertical,
mdiEye,
mdiEyeOff,
mdiEyeOutline,
mdiMenuDown,
mdiMicrophoneMessage,
mdiMicrophoneMessageOff,
mdiPencilOff,
mdiPlus,
mdiPower,
mdiPulse,
mdiRestore,
mdiRestoreAlert,
mdiToggleSwitch,
@@ -78,7 +75,7 @@ import "../../../components/ha-filter-floor-areas";
import "../../../components/ha-filter-integrations";
import "../../../components/ha-filter-labels";
import "../../../components/ha-filter-states";
import type { FilterStateItem } from "../../../components/ha-filter-states";
import type { FilterStateOption } from "../../../components/ha-filter-states";
import "../../../components/ha-filter-voice-assistants";
import "../../../components/ha-icon";
import "../../../components/ha-icon-button";
@@ -324,59 +321,36 @@ export class HaConfigEntities extends LitElement {
// The icons of the options match the ones of the status column and of the
// actions for the selected entities
private _states = memoize((localize: LocalizeFunc): FilterStateItem[] => [
private _states = memoize((localize: LocalizeFunc): FilterStateOption[] => [
{
value: "availability",
label: localize("ui.panel.config.entities.picker.headers.availability"),
iconPath: mdiPulse,
options: [
{
value: "available",
label: localize("ui.panel.config.entities.picker.status.available"),
iconPath: mdiCheckCircle,
},
{
value: "unavailable",
label: localize("ui.panel.config.entities.picker.status.unavailable"),
iconPath: mdiAlertCircle,
},
],
value: "available",
label: localize("ui.panel.config.entities.picker.status.available"),
iconPath: mdiCheckCircle,
},
{
value: "activation",
label: localize(
"ui.panel.config.entities.picker.status_pairs.activation"
),
iconPath: mdiPower,
options: [
{
value: "enabled",
label: localize("ui.panel.config.entities.picker.status.enabled"),
iconPath: mdiToggleSwitch,
},
{
value: "disabled",
label: localize("ui.panel.config.entities.picker.status.disabled"),
iconPath: mdiToggleSwitchOffOutline,
},
],
value: "unavailable",
label: localize("ui.panel.config.entities.picker.status.unavailable"),
iconPath: mdiAlertCircle,
},
{
value: "visibility",
label: localize("ui.panel.config.entities.picker.headers.visibility"),
iconPath: mdiEyeOutline,
options: [
{
value: "visible",
label: localize("ui.panel.config.entities.picker.status.visible"),
iconPath: mdiEye,
},
{
value: "hidden",
label: localize("ui.panel.config.entities.picker.status.hidden"),
iconPath: mdiEyeOff,
},
],
value: "enabled",
label: localize("ui.panel.config.entities.picker.status.enabled"),
iconPath: mdiToggleSwitch,
},
{
value: "disabled",
label: localize("ui.panel.config.entities.picker.status.disabled"),
iconPath: mdiToggleSwitchOffOutline,
},
{
value: "visible",
label: localize("ui.panel.config.entities.picker.status.visible"),
iconPath: mdiEye,
},
{
value: "hidden",
label: localize("ui.panel.config.entities.picker.status.hidden"),
iconPath: mdiEyeOff,
},
{
value: "readonly",
-3
View File
@@ -7904,9 +7904,6 @@
"not_provided": "Not provided",
"unmanageable": "Unmanageable"
},
"status_pairs": {
"activation": "Activation"
},
"headers": {
"state_icon": "State icon",
"entity": "Entity",
+1 -71
View File
@@ -1,21 +1,12 @@
import { describe, expect, it } from "vitest";
import {
clampZoomPan,
fitPicture,
panBy,
refitZoomPan,
visiblePart,
ZOOM_PAN_IDENTITY,
zoomAtPoint,
} from "../../../src/components/camera/zoom-pan";
const size = fitPicture({ width: 400, height: 300 });
// A 4:3 picture in a 16:9 viewport, with 120px bars left and right
const pillarboxed = fitPicture(
{ width: 640, height: 360 },
{ width: 1600, height: 1200 }
);
const size = { width: 400, height: 300 };
// A wrong transform shows black bars next to the picture, or zooms away from
// what the user pointed at
@@ -80,64 +71,3 @@ describe("clampZoomPan", () => {
);
});
});
describe("fitPicture", () => {
it("fits the picture in the middle of the viewport", () => {
expect(pillarboxed.picture).toEqual({
x: 80,
y: 0,
width: 480,
height: 360,
});
expect(fitPicture({ width: 400, height: 300 }).picture).toEqual({
x: 0,
y: 0,
width: 400,
height: 300,
});
});
});
// Panning must not show the bars next to a picture of another aspect ratio
describe("bars next to the picture", () => {
it("keeps the picture in the middle while it is narrower than the viewport", () => {
// 480 * 1.2 = 576 is still narrower than 640
expect(
zoomAtPoint(ZOOM_PAN_IDENTITY, 1.2, { x: 0, y: 0 }, pillarboxed)
).toEqual({ scale: 1.2, x: (640 - 576) / 2 - 80 * 1.2, y: 0 });
});
it("stops at the edges of the picture, not of the viewport", () => {
// The picture spans 160 to 1120 at 2x, so it can move 320px each way
expect(panBy({ scale: 2, x: -480, y: 0 }, 1000, 0, pillarboxed).x).toBe(
-160
);
expect(panBy({ scale: 2, x: -480, y: 0 }, -1000, 0, pillarboxed).x).toBe(
640 - 1120
);
});
});
describe("visiblePart", () => {
it("is the part of the picture in view", () => {
// At 2x, the left half of the visible area is the picture's left edge
expect(visiblePart({ scale: 2, x: -160, y: 0 }, pillarboxed)).toEqual({
x: 0,
y: 0,
width: 640 / 2 / 480,
height: 0.5,
});
});
});
describe("refitZoomPan", () => {
it("keeps the middle of the view when the viewport changes", () => {
const zoomed = { scale: 2, x: -400, y: -300 };
const larger = fitPicture({ width: 800, height: 600 });
expect(refitZoomPan(zoomed, size, larger)).toEqual({
scale: 2,
x: -800,
y: -600,
});
});
});
-37
View File
@@ -71,43 +71,6 @@ describe("ha-toast", () => {
expect(listener.mock.calls[0][0].detail).toEqual({ reason: "timeout" });
});
// A toast moves with the notification manager into an open dialog. The
// move disconnects it, which stops its timer.
it("keeps its timeout after a move in the DOM", async () => {
const element = await mountToast({ timeoutMs: 1000 });
const listener = vi.fn();
element.addEventListener("toast-closed", listener);
await showToast(element);
await vi.advanceTimersByTimeAsync(900);
const parent = document.createElement("div");
document.body.append(parent);
parent.append(element);
await vi.advanceTimersByTimeAsync(50);
expect(listener).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(50);
parent.remove();
expect(listener.mock.calls[0][0].detail).toEqual({ reason: "timeout" });
});
it("finishes a close that a move in the DOM interrupted", async () => {
const element = await mountToast({ timeoutMs: -1 });
const listener = vi.fn();
element.addEventListener("toast-closed", listener);
await showToast(element);
element.hide("action");
const parent = document.createElement("div");
document.body.append(parent);
parent.append(element);
await vi.advanceTimersByTimeAsync(20);
parent.remove();
expect(listener).toHaveBeenCalledOnce();
expect(listener.mock.calls[0][0].detail).toEqual({ reason: "action" });
});
it("does not close automatically when the timeout is disabled", async () => {
const element = await mountToast({ timeoutMs: -1 });
const listener = vi.fn();