Compare commits

...
Author SHA1 Message Date
Bram Kragten 14034dda2d Bumped version to 20261125.2 2026-11-30 17:28:43 +01:00
Paul Bottein 47582923aa Keep the camera stream details in sync with the player (#56286) 2026-11-30 17:26:26 +01:00
WendelinandClaude Opus 5.5 75555390a1 Keep MJPEG picture in picture updating in Firefox (#56282)
Firefox only draws the first frame of an MJPEG image into a canvas, so
the picture in picture video froze. A bitmap of the image has the
current frame.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 17:26:25 +01:00
WendelinandClaude Opus 5.5 9e39b72de4 Show a placeholder instead of a broken image for cameras (#56271)
* Show a placeholder instead of a broken image for cameras

Picture cards show the camera placeholder instead of the broken image
when the camera is unavailable or its picture fails to load, and stop
requesting pictures while the camera is unavailable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Show the camera placeholder when a live MJPEG picture fails

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 17:26:24 +01:00
WendelinandClaude Opus 5.5 2ae815f1fd Simplify the camera stream badge and handle unavailable cameras (#56270)
* Simplify the camera stream badge and handle unavailable cameras

The badge only shows the state of the stream: Live, Connecting,
Unavailable or Disconnected. The protocol stays in the connection dialog.

Unavailable cameras don't start a stream. The player and the picture
cards show a camera-off placeholder instead of a broken image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Move the picture card placeholder to its own pull request

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep the unavailable placeholder while Home Assistant is disconnected

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Skip the camera capabilities while unavailable and explain Disconnected

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 17:26:22 +01:00
Marcin BauerandClaude Fable 5.2 92045529e2 Replace brand titles in All brands with the brand name on each card (#56262)
Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-30 17:26:21 +01:00
Jonathan DilksandClaude Opus 5.5 baaf5d1503 Fix pause button size in narrow media control card (#56256)
A missing comma in the narrow-layout selector meant the pause and stop
buttons never got the larger play-button size, so the card changed
height when switching between play and pause.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 17:26:19 +01:00
39b5f62cdb Use Marketplace icons for app install and uninstall (#56231)
The app info page now uses the same icons as the Marketplace:
mdiDownload for install and mdiDelete for uninstall. The previous
install icon filled its whole box and looked too large on the button.

Co-authored-by: Paulus Schoutsen <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 17:26:17 +01:00
Petar Petrov 77f2230f9b Open more-info from energy meter suggestion names (#56226)
* Open more-info from energy meter suggestion names

* Type the more-info handler's current target
2026-11-30 17:26:16 +01:00
darkrain-nl 2cab493aaa Keep the startup progress in view while the list scrolls (#56213) 2026-11-30 17:26:15 +01:00
darkrain-nl c024b4594a Keep the startup details dialog at a fixed height (#56209) 2026-11-30 17:26:14 +01:00
Lazizbek Ergashev b76650cb55 Show Home Assistant Link as the title of the signed out Link page (#56205) 2026-11-30 17:26:12 +01:00
Petar Petrov eae1d81471 Show the device tooltip when hovering a name in the energy devices chart (#56200) 2026-11-30 17:26:11 +01:00
Paul Bottein 99b9f2593c Fill the mobile more info with the camera picture (#56199)
* Fill the mobile more info with the camera picture

* Use the dialog's own mode for the camera fill
2026-11-30 17:26:09 +01:00
Petar Petrov 43b6d8a0ea Add a Dismiss all button to energy meter suggestions (#56198) 2026-11-30 17:26:08 +01:00
Lazizbek Ergashev caccbf3c59 Only add the entity name to energy devices when it tells them apart (#56192)
* Only add the entity name to energy devices when it tells them apart

* Keep entity names for same-named devices with several meters

* Keep entity names when a custom name shares the device label
2026-11-30 17:26:06 +01:00
e5f408fca0 Show wake word names in the voice setup wizard (#56035)
* Show wake word names in the voice setup wizard

The migration to ha-list-item-button left the wake word phrase in the
default slot, which ha-row-item does not render, so the "Change wake
word" step showed empty rows. Put the phrase in the headline slot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Remove wake word step test

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Paul Bottein <[email protected]>
2026-11-30 17:26:05 +01:00
Bram Kragten 1c70897226 Bumped version to 20261125.1 2026-11-26 17:24:46 +01:00
WendelinandClaude Opus 5.5 3a27de8e0a Load Marketplace category icons only when they are shown (#56185)
The repository page loaded the integration category icons for every
repository, also for ones without integration categories. Load them once
a shown repository has categories, and only once per page.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:04:15 +01:00
WendelinandClaude Opus 5.5 bc21f2903d Only offer the tab's categories in the Marketplace filter (#56183)
The integration category filter offered every category on every tab, so
on the installed tab a category nothing installed is in emptied the
table. It now lists the categories of the tab's repositories, and a
category picked on another tab that this one doesn't list is left out
here but kept for that tab, like statuses.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:04:15 +01:00
WendelinandClaude Opus 5.5 b067ce5515 Remove two marketplace tests that only cover helpers (#56184)
Follow-up to #55130 review: the empty integration_category link test only
covered the query param decoder, and the filtersOfTab category test only
covered a spread.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:04:15 +01:00
Paul Bottein c95ed9f16c Swipe to open or close the tilt of tilt-only covers (#56182) 2026-11-26 17:01:38 +01:00
Paul Bottein 95eb2641e2 Fix rows value bubble cut off in the card size editor (#56181) 2026-11-26 17:01:36 +01:00
Bram KragtenandClaude Opus 5.5 4cb23b772a Draw the slats of tilt-only covers from their state (#56173)
* Draw the slats of tilt-only covers from their state

A tilt-only cover that only reports open or closed, without a tilt
position, was always drawn with half open slats. When the cover can't
move up or down, its state describes the slats, so draw them at the
closed tilt position when closed and at the open tilt position when
open. Covers that also move up and down keep the neutral slats, as
their state describes the position.

Add tilt-only blinds, open and closed, to the cover more-info gallery.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Draw the slats from the state with the default tilt positions

Core only sends the open and closed tilt positions of covers that can
set their tilt position, so a tilt-only cover drawn from its state
always uses 0 and 100.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:01:35 +01:00
WendelinandClaude Opus 5.5 0bf5da2e09 Fix the Bluetooth adapter count on the dashboard (#56165)
* Fix the Bluetooth adapter count on the dashboard

The dashboard counted every bluetooth config entry that isn't disabled,
including ignored discoveries and entries without an adapter device, so
it could show more adapters than the adapters page lists. Move the
adapters page logic to a shared getBluetoothAdapters() helper and count
its enabled adapters on the dashboard. The count waits for the device
registry to load.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Show skeletons while the Bluetooth adapters load

Don't report zero adapters and an offline network before the config
entries and the device registry have loaded. Add tests for the shared
adapter selection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Show an error with retry when the Bluetooth config entries fail to load

Otherwise the dashboard would keep showing its loading skeletons.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep the Bluetooth adapters link named while it loads

A skeleton in the link made its accessible name only "Loading". Show
"Bluetooth adapters" until the count is known instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:01:34 +01:00
Erwin Douna c12ad32797 Restore dismissed energy meter suggestions (#56156)
* Restore dismissed energy meter suggestions

* Use a toolbar menu for dismissed meter suggestions and fix save races
2026-11-26 17:01:33 +01:00
2c03c2d74a Show Home Assistant Link label on WebRTC in camera stream info (#56153)
* Show Home Assistant Link label on WebRTC in camera stream info

The camera stream info dialog labels the WebRTC row with
"Enhanced by Home Assistant Link" when the cloud TURN servers are in
use. The dialog reads cloud/status and uses the same check as core:
logged in, active subscription, and cloud_ice_servers_enabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Wrap the Home Assistant Link tag on narrow screens

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Paulus Schoutsen <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:01:31 +01:00
darkrain-nl 2705e6da51 2026.12 beta - Fix add integration search focus (#56151)
* Focus autofocus elements slotted into an adaptive dialog

* Test focusing autofocus elements slotted into a dialog
2026-11-26 17:01:30 +01:00
Martin Salinas e3871d47de Give the tile icon's action its whole 48px area again (#56150)
* Give the tile icon's action its whole 48px area again

The tile container pads the icon by 6px so it is a 48px target, but the action handler was bound to the 36px circle inside it. A tap on that ring, around the circle or on a badge landed on the icon's host, which had no handler, and the container stopped it before the card's handler. Bind the action handler to the host instead.

* Let taps on the tile icon's badge reach the icon

With the action handler on the host, a tap on a badge in the default slot had the badge as its target, so a double tap across the badge and the rest of the icon fired two taps.

* Show the pointer cursor over the tile icon's whole area
2026-11-26 17:01:29 +01:00
Paul Bottein ead8c01926 Fix integration names and toast overlap in startup details (#56147)
* Fix integration names and toast overlap in startup details

* Track startup details opened from the completion toast
2026-11-26 17:01:28 +01:00
Paul Bottein 258cb6f8b9 Show the connection error when logged out and the server is offline (#56139)
* Show the connection error when logged out and the server is offline

* Show the connection error when the server responds with a 5xx

* Time out the server check before the login redirect

* Give the server check 10 seconds
2026-11-26 17:01:26 +01:00
Matthias de BaatandClaude Opus 5.5 72057cf504 Show when backup retention is paused for a location (#56088)
Automatic backup retention no longer deletes backups from locations
that are turned off for automatic backups (home-assistant/core#192788).
Show "Retention paused" in the locations list and an info alert on the
location page for those locations.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 17:01:25 +01:00
52 changed files with 1881 additions and 476 deletions

No files matched your search

+26
View File
@@ -70,6 +70,32 @@ const ENTITIES = [
CoverEntityFeature.CLOSE_TILT,
},
},
{
entity_id: "cover.tilt_only_closed",
state: "closed",
attributes: {
friendly_name: "Tilt-only blind closed",
device_class: "blind",
assumed_state: true,
supported_features:
CoverEntityFeature.OPEN_TILT +
CoverEntityFeature.STOP_TILT +
CoverEntityFeature.CLOSE_TILT,
},
},
{
entity_id: "cover.tilt_only_open",
state: "open",
attributes: {
friendly_name: "Tilt-only blind open",
device_class: "blind",
assumed_state: true,
supported_features:
CoverEntityFeature.OPEN_TILT +
CoverEntityFeature.STOP_TILT +
CoverEntityFeature.CLOSE_TILT,
},
},
{
entity_id: "cover.tilt_slider_half",
state: "on",
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "home-assistant-frontend"
version = "20261125.0"
version = "20261125.2"
license = "Apache-2.0"
license-files = ["LICENSE*"]
description = "The Home Assistant frontend"
@@ -0,0 +1,33 @@
import { mdiVideoOffOutline } from "@mdi/js";
import { css, html, LitElement } from "lit";
import { customElement } from "lit/decorators";
import "../ha-svg-icon";
/**
* @element ha-camera-placeholder
*
* @summary Shows instead of a camera's picture when there is none, like
* while the camera is unavailable.
*/
@customElement("ha-camera-placeholder")
export class HaCameraPlaceholder extends LitElement {
protected render() {
return html`<ha-svg-icon .path=${mdiVideoOffOutline}></ha-svg-icon>`;
}
static styles = css`
:host {
display: flex;
align-items: center;
justify-content: center;
color: var(--secondary-text-color);
--mdc-icon-size: 40px;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-camera-placeholder": HaCameraPlaceholder;
}
}
+108 -15
View File
@@ -22,12 +22,16 @@ import type { LocalizeFunc } from "../../common/translations/localize";
import { nextRender } from "../../common/util/render-status";
import type { CameraCapabilities, CameraEntity } from "../../data/camera";
import type { CameraStreamStatus } from "../../data/camera-streams";
import { showCameraStreamInfoDialog } from "../../dialogs/camera/show-dialog-camera-stream-info";
import {
showCameraStreamInfoDialog,
type CameraStreamInfo,
} from "../../dialogs/camera/show-dialog-camera-stream-info";
import "../ha-camera-stream";
import type { HaCameraStream } from "../ha-camera-stream";
import "../ha-icon-button";
import "../ha-spinner";
import "../ha-svg-icon";
import "./ha-camera-placeholder";
import "./ha-camera-stream-badge";
import {
fitPicture,
@@ -97,6 +101,9 @@ export class HaCameraPlayer extends LitElement {
@property({ type: Boolean, attribute: "keep-awake" })
public keepAwake = false;
/** Fills the height it is given, with the picture in the middle. */
@property({ type: Boolean, reflect: true }) public fill = false;
@state() private _status: CameraStreamStatus = {
connecting: true,
hasAudio: false,
@@ -104,6 +111,8 @@ export class HaCameraPlayer extends LitElement {
@state() private _capabilities?: CameraCapabilities;
private _streamInfoCallbacks = new Set<(info: CameraStreamInfo) => void>();
@state() private _video?: HTMLVideoElement;
@state() private _muted = false;
@@ -209,6 +218,7 @@ export class HaCameraPlayer extends LitElement {
);
clearTimeout(this._controlsTimeout);
clearTimeout(this._wheelHintTimeout);
this._streamInfoCallbacks.clear();
this._unbindVideo(this._video);
this._video = undefined;
this._pointers.clear();
@@ -248,6 +258,10 @@ export class HaCameraPlayer extends LitElement {
this._unbindVideo(changedProps.get("_video") as HTMLVideoElement);
this._bindVideo(this._video);
}
if (changedProps.has("_status") || changedProps.has("_capabilities")) {
const info = this._streamInfo();
this._streamInfoCallbacks.forEach((callback) => callback(info));
}
}
protected render() {
@@ -259,11 +273,12 @@ export class HaCameraPlayer extends LitElement {
// controls and zoom of this one can't reach, so it shows just the stream
const inApp = Boolean(status.inApp);
const zoomed = !inApp && isZoomed(this._zoom);
// Stays while the connection changes, so the user sees what happens
// Stays while not live, so the user sees what happens
const badgeVisible =
this._controlsVisible ||
status.connecting ||
status.upgrading !== undefined;
Boolean(status.unavailable) ||
Boolean(status.disconnected);
return html`
<div
@@ -284,9 +299,10 @@ export class HaCameraPlayer extends LitElement {
gesture: this._gesture,
})}
style=${styleMap({
aspectRatio: this._fullscreen
? undefined
: String(this._aspectRatio()),
aspectRatio:
this._fullscreen || this.fill
? undefined
: String(this._aspectRatio()),
})}
@pointerdown=${this._pointerDown}
@pointerup=${this._pointerUp}
@@ -303,6 +319,9 @@ export class HaCameraPlayer extends LitElement {
mjpeg-video
measure-poster
style=${styleMap({
"--picture-aspect-ratio": this.fill
? String(this._aspectRatio())
: undefined,
transform: zoomed
? `translate(${this._zoom.x}px, ${this._zoom.y}px) scale(${this._zoom.scale})`
: undefined,
@@ -312,6 +331,11 @@ export class HaCameraPlayer extends LitElement {
@camera-capabilities-changed=${this._capabilitiesChanged}
@camera-poster-size-changed=${this._posterSizeChanged}
></ha-camera-stream>
${
status.unavailable
? html`<ha-camera-placeholder></ha-camera-placeholder>`
: nothing
}
</div>
${inApp ? nothing : this._renderControls(status, zoomed, badgeVisible)}
</div>
@@ -325,7 +349,10 @@ export class HaCameraPlayer extends LitElement {
) {
return html`
${
this._paused && !status.connecting
this._paused &&
!status.connecting &&
!status.unavailable &&
!status.disconnected
? html`<ha-icon-button
class="control pinned play"
.label=${this._localize("ui.components.camera-player.play")}
@@ -536,15 +563,21 @@ export class HaCameraPlayer extends LitElement {
) {
const oldStatus = this._status;
this._status = ev.detail;
if (ev.detail.inApp) {
if (ev.detail.inApp || ev.detail.unavailable) {
this._zoom = ZOOM_PAN_IDENTITY;
}
if (
oldStatus.connecting !== ev.detail.connecting ||
oldStatus.unavailable !== ev.detail.unavailable ||
oldStatus.disconnected !== ev.detail.disconnected
) {
// Shows the new state for a moment
this._showControls();
}
if (
oldStatus.connecting !== ev.detail.connecting ||
oldStatus.type !== ev.detail.type
) {
// Shows the new connection for a moment
this._showControls();
this._updateVideo();
}
}
@@ -579,10 +612,26 @@ export class HaCameraPlayer extends LitElement {
this._posterSize = ev.detail.size;
}
private _showStreamInfo() {
showCameraStreamInfoDialog(this, {
private _streamInfo(): CameraStreamInfo {
return {
status: this._status,
supportedTypes: this._capabilities?.frontend_stream_types,
};
}
private _subscribeStreamInfo = (
callback: (info: CameraStreamInfo) => void
) => {
this._streamInfoCallbacks.add(callback);
callback(this._streamInfo());
return () => {
this._streamInfoCallbacks.delete(callback);
};
};
private _showStreamInfo() {
showCameraStreamInfoDialog(this, {
subscribe: this._subscribeStreamInfo,
});
}
@@ -813,12 +862,17 @@ export class HaCameraPlayer extends LitElement {
this._zoom = refitZoomPan(this._zoom, oldViewport, viewport);
};
// The app's own player and a camera without picture can't be zoomed
private _canZoom(): boolean {
return !this._status.inApp && !this._status.unavailable;
}
private _resetZoom() {
this._zoom = ZOOM_PAN_IDENTITY;
}
private _wheel(ev: WheelEvent) {
if (!this._viewport || this._status.inApp) {
if (!this._viewport || !this._canZoom()) {
return;
}
// A pinch on a touchpad scrolls with ctrl held
@@ -862,7 +916,7 @@ export class HaCameraPlayer extends LitElement {
}
private _doubleClick(ev: MouseEvent) {
if (!this._viewport || this._status.inApp) {
if (!this._viewport || !this._canZoom()) {
return;
}
if (isZoomed(this._zoom)) {
@@ -905,7 +959,8 @@ export class HaCameraPlayer extends LitElement {
this._showControls();
}
const pointer = this._pointers.get(ev.pointerId);
if (!pointer || !this._viewport) {
// Taps still toggle the controls when the picture can't be zoomed
if (!pointer || !this._viewport || !this._canZoom()) {
return;
}
const { rect, viewport } = this._measureViewport();
@@ -1030,6 +1085,38 @@ export class HaCameraPlayer extends LitElement {
cursor: none;
}
:host([fill]) {
position: relative;
flex: 1;
min-height: 0;
}
:host([fill]) .player {
position: absolute;
inset: 0;
}
:host([fill]) .viewport {
height: 100%;
max-height: none;
container-type: size;
--video-max-height: 100%;
}
/* As large as the picture fits in the middle, zoomed from the corner of
the viewport like a stream that fills it */
:host([fill]) ha-camera-stream {
--picture-width: min(100cqw, 100cqh * var(--picture-aspect-ratio));
--picture-height: min(100cqh, 100cqw / var(--picture-aspect-ratio));
position: absolute;
top: calc((100cqh - var(--picture-height)) / 2);
left: calc((100cqw - var(--picture-width)) / 2);
width: var(--picture-width);
height: var(--picture-height);
transform-origin: calc((var(--picture-width) - 100cqw) / 2)
calc((var(--picture-height) - 100cqh) / 2);
}
.viewport {
position: relative;
overflow: hidden;
@@ -1067,6 +1154,12 @@ export class HaCameraPlayer extends LitElement {
transition: transform var(--ha-animation-duration-fast) ease-out;
}
ha-camera-placeholder {
position: absolute;
inset: 0;
color: rgba(255, 255, 255, 0.5);
}
.viewport.gesture ha-camera-stream {
transition: none;
will-change: transform;
+24 -51
View File
@@ -6,7 +6,6 @@ import type {
CameraStreamStatus,
CameraStreamType,
} from "../../data/camera-streams";
import "../ha-spinner";
/** Names of the protocols, the same in every language. */
export const CAMERA_STREAM_TYPE_NAMES: Record<CameraStreamType, string> = {
@@ -16,8 +15,10 @@ export const CAMERA_STREAM_TYPE_NAMES: Record<CameraStreamType, string> = {
};
/**
* Shows over a camera stream how it is connected. A faster stream that still
* connects in the background is shown next to the current one.
* @element ha-camera-stream-badge
*
* @summary Shows over a camera stream whether it is live. Selecting it
* shows how it is connected.
*/
@customElement("ha-camera-stream-badge")
export class HaCameraStreamBadge extends LitElement {
@@ -32,51 +33,27 @@ export class HaCameraStreamBadge extends LitElement {
if (!status) {
return nothing;
}
const connecting = status.connecting || !status.type;
const label = connecting
? this._localize("ui.components.camera-player.connecting")
: CAMERA_STREAM_TYPE_NAMES[status.type!];
const connection = status.disconnected
? "disconnected"
: status.unavailable
? "unavailable"
: status.connecting || !status.type
? "connecting"
: "live";
return html`
<button
type="button"
aria-label=${this._ariaLabel(status)}
class=${connecting ? "connecting" : "live"}
>
<button type="button" class=${connection} aria-describedby="details">
<span class="dot"></span>
<span class="label">${label}</span>
${
status.upgrading
? html`<span class="upgrading" aria-hidden="true">
<ha-spinner></ha-spinner>
${CAMERA_STREAM_TYPE_NAMES[status.upgrading]}
</span>`
: nothing
}
<span class="label"
>${this._localize(`ui.components.camera-player.${connection}`)}</span
>
</button>
<span id="details" hidden
>${this._localize("ui.components.camera-player.show_details")}</span
>
`;
}
private _ariaLabel(status: CameraStreamStatus): string {
if (status.connecting || !status.type) {
return this._localize(
"ui.components.camera-player.stream_info_connecting"
);
}
if (status.upgrading) {
return this._localize(
"ui.components.camera-player.stream_info_upgrading",
{
type: CAMERA_STREAM_TYPE_NAMES[status.type],
upgrading: CAMERA_STREAM_TYPE_NAMES[status.upgrading],
}
);
}
return this._localize("ui.components.camera-player.stream_info", {
type: CAMERA_STREAM_TYPE_NAMES[status.type],
});
}
static styles = css`
:host {
display: inline-flex;
@@ -120,16 +97,12 @@ export class HaCameraStreamBadge extends LitElement {
animation: pulse 1.2s ease-in-out infinite;
}
.upgrading {
display: inline-flex;
align-items: center;
gap: var(--ha-space-1);
padding-inline-start: var(--ha-space-1);
border-inline-start: 1px solid rgba(255, 255, 255, 0.3);
opacity: 0.7;
--ha-spinner-indicator-color: var(--ha-color-white);
--ha-spinner-size: 10px;
--ha-spinner-divider-color: rgba(255, 255, 255, 0.3);
.unavailable .dot {
background-color: rgba(255, 255, 255, 0.5);
}
.disconnected .dot {
background-color: var(--ha-color-red-60);
}
@keyframes pulse {
+8 -2
View File
@@ -1,5 +1,6 @@
import { mdiClose } from "@mdi/js";
import type { ContextType } from "@lit/context";
import { createContext, provide } from "@lit/context";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../common/decorators/consume";
@@ -11,7 +12,10 @@ import "./ha-icon-button";
import "./ha-dialog";
import type { DialogWidth } from "./ha-dialog";
type DialogSheetMode = "dialog" | "bottom-sheet";
export type DialogSheetMode = "dialog" | "bottom-sheet";
export const adaptiveDialogModeContext =
createContext<DialogSheetMode>("adaptiveDialogMode");
export const ADAPTIVE_DIALOG_MEDIA_QUERY =
"(max-width: 870px), (max-height: 500px)";
@@ -125,7 +129,9 @@ export class HaAdaptiveDialog extends LitElement {
@property({ type: Boolean, reflect: true, attribute: "flexcontent" })
public flexContent = false;
@state() public mode: DialogSheetMode = "dialog";
@provide({ context: adaptiveDialogModeContext })
@state()
public mode: DialogSheetMode = "dialog";
@state()
@consume({ context: internationalizationContext, subscribe: true })
+116 -17
View File
@@ -34,6 +34,8 @@ import {
connectionContext,
formattersContext,
} from "../data/context";
import { UNAVAILABLE } from "../data/entity/entity";
import "./camera/ha-camera-placeholder";
import "./ha-hls-player";
import type { HaHLSPlayer } from "./ha-hls-player";
import "./ha-mjpeg-player";
@@ -111,6 +113,13 @@ export class HaCameraStream extends LitElement {
// The app plays the HLS stream in its own player, over the page
@state() private _hlsInApp = false;
// WebRTC is the only stream and failed, its player shows why
@state() private _webRtcFailed = false;
// The MJPEG image failed, it is tried again with the next access token or
// once Home Assistant reconnects
@state() private _mjpegImageFailed = false;
@query("ha-web-rtc-player") private _webRtcPlayer?: HaWebRtcPlayer;
@query("ha-mjpeg-player") private _mjpegPlayer?: HaMjpegPlayer;
@@ -153,9 +162,32 @@ export class HaCameraStream extends LitElement {
this._config.config.state === STATE_RUNNING &&
oldConfig.config?.state !== STATE_RUNNING;
if (entityChanged || backendStarted) {
this._getCapabilities();
this._getPosterUrl();
const oldStateObj = changedProps.get("stateObj") as
CameraEntity | undefined;
const becameAvailable =
!entityChanged &&
this.stateObj !== undefined &&
oldStateObj?.state === UNAVAILABLE &&
!this._unavailable;
if (entityChanged || backendStarted || becameAvailable) {
if (this._unavailable) {
// Core often doesn't know the camera then, as its integration
// didn't load. Its capabilities are fetched once it is back.
this._clearCapabilities();
} else {
this._getCapabilities();
this._getPosterUrl();
}
}
if (
oldStateObj &&
oldStateObj.attributes.access_token !==
this.stateObj?.attributes.access_token
) {
// A new token gives a new MJPEG address, worth another try
this._mjpegImageFailed = false;
}
const oldConnection = changedProps.get("_connection") as
@@ -170,6 +202,10 @@ export class HaCameraStream extends LitElement {
}
}
private get _unavailable(): boolean {
return this.stateObj?.state === UNAVAILABLE;
}
/** The microphone track sent to the camera, only on WebRTC streams. */
public get microphoneTrack(): MediaStreamTrack | undefined {
return this._webRtcPlayer?.microphoneTrack;
@@ -238,29 +274,63 @@ export class HaCameraStream extends LitElement {
this._visibleStreamType = visibleStreamType;
fireEvent(this, "stream-type-changed", { type: visibleStreamType });
}
const status: CameraStreamStatus = {
...computeCameraStreamStatus(
streams,
// Nothing plays while Home Assistant is disconnected
this._connection.connected ? this._loadedStreams : new Set(),
this._hlsStreams,
this._webRtcStreams
),
inApp: visibleStreamType === STREAM_TYPE_HLS && this._hlsInApp,
};
const status = this._computeStatus(streams, visibleStreamType);
if (
!this._status ||
status.type !== this._status.type ||
status.connecting !== this._status.connecting ||
status.upgrading !== this._status.upgrading ||
status.hasAudio !== this._status.hasAudio ||
status.inApp !== this._status.inApp
status.inApp !== this._status.inApp ||
status.unavailable !== this._status.unavailable ||
status.disconnected !== this._status.disconnected
) {
this._status = status;
fireEvent(this, "camera-stream-status-changed", status);
}
}
private _computeStatus(
streams: CameraStream[],
visibleStreamType?: CameraStreamType
): CameraStreamStatus {
// A playing WebRTC stream can come straight from the camera or an
// external go2rtc, it then keeps playing without Home Assistant
const playsWithoutHomeAssistant =
visibleStreamType === STREAM_TYPE_WEB_RTC &&
this._loadedStreams.has(STREAM_TYPE_WEB_RTC);
const inApp = visibleStreamType === STREAM_TYPE_HLS && this._hlsInApp;
if (!this._connection.connected && !playsWithoutHomeAssistant) {
// Kept so the player still shows its placeholder instead of nothing
return {
connecting: false,
hasAudio: false,
inApp,
disconnected: "home_assistant",
unavailable: this._unavailable,
};
}
if (this._unavailable) {
return { connecting: false, hasAudio: false, unavailable: true };
}
if (this._webRtcFailed) {
return {
connecting: false,
hasAudio: false,
disconnected: "stream_failed",
};
}
return {
...computeCameraStreamStatus(
streams,
this._loadedStreams,
this._hlsStreams,
this._webRtcStreams
),
inApp,
};
}
protected render() {
if (!this.stateObj) {
return nothing;
@@ -297,6 +367,11 @@ export class HaCameraStream extends LitElement {
@load=${this._handleMjpegLoad}
></ha-mjpeg-player>`;
}
if (this._mjpegImageFailed) {
return html`<ha-camera-placeholder
style=${styleMap({ aspectRatio: this.aspectRatio ?? 16 / 9 })}
></ha-camera-placeholder>`;
}
return html`<img
.src=${streamUrl}
style=${styleMap({
@@ -305,6 +380,7 @@ export class HaCameraStream extends LitElement {
})}
alt=${`Preview of the ${this._formatters?.formatEntityName(this.stateObj) ?? ""} camera.`}
@load=${this._handleImageLoad}
@error=${this._handleImageError}
/>`;
}
@@ -346,6 +422,9 @@ export class HaCameraStream extends LitElement {
}
private _currentStreams() {
if (this._unavailable) {
return [];
}
return this._streams(
this._capabilities?.frontend_stream_types,
this._hlsStreams,
@@ -353,10 +432,15 @@ export class HaCameraStream extends LitElement {
);
}
private async _getCapabilities() {
/** Returns the request number, so an older request can be dropped. */
private _clearCapabilities() {
this._capabilities = undefined;
this._resetStreams();
const request = ++this._capabilitiesRequest;
return ++this._capabilitiesRequest;
}
private async _getCapabilities() {
const request = this._clearCapabilities();
if (!supportsFeature(this.stateObj!, CameraEntityFeature.STREAM)) {
this._capabilities = {
frontend_stream_types: [],
@@ -379,11 +463,14 @@ export class HaCameraStream extends LitElement {
this._webRtcStreams = undefined;
this._loadedStreams = new Set();
this._hlsInApp = false;
this._webRtcFailed = false;
this._mjpegImageFailed = false;
this._mjpegPlayer?.restart();
}
private _restartMjpeg() {
this._setLoaded(MJPEG_STREAM, false);
this._mjpegImageFailed = false;
this._mjpegPlayer?.restart();
}
@@ -443,6 +530,11 @@ export class HaCameraStream extends LitElement {
fireEvent(this, "load");
}
private _handleImageError() {
this._mjpegImageFailed = true;
this._setLoaded(MJPEG_STREAM, false);
}
private _handleMjpegLoad() {
this._setLoaded(MJPEG_STREAM, true);
}
@@ -458,6 +550,7 @@ export class HaCameraStream extends LitElement {
}
private _handleWebRtcLoad() {
this._webRtcFailed = false;
this._setLoaded(STREAM_TYPE_WEB_RTC, true);
}
@@ -477,6 +570,7 @@ export class HaCameraStream extends LitElement {
) {
// Without another stream type, keep the player to show why it failed.
// Only a browser without WebRTC falls back to MJPEG.
this._webRtcFailed = true;
this._setLoaded(STREAM_TYPE_WEB_RTC, false);
return;
}
@@ -510,10 +604,15 @@ export class HaCameraStream extends LitElement {
display: block;
}
img {
img,
ha-camera-placeholder {
width: 100%;
}
ha-camera-placeholder {
background-color: var(--ha-color-fill-neutral-normal-resting);
}
ha-web-rtc-player {
width: 100%;
height: 100%;
+23 -3
View File
@@ -250,8 +250,8 @@ export class HaDialog extends ScrollableFadeMixin(LitElement) {
this._hassConfig?.auth.external &&
isIosApp(this._hassConfig.auth.external)
) {
const element = this.querySelector("[autofocus]");
if (element !== null) {
const element = this._autofocusElement();
if (element) {
if (!element.id) {
element.id = "ha-dialog-autofocus";
}
@@ -264,10 +264,30 @@ export class HaDialog extends ScrollableFadeMixin(LitElement) {
}
return;
}
(this.querySelector("[autofocus]") as HTMLElement | null)?.focus();
this._autofocusElement()?.focus();
});
};
// Wrappers like ha-adaptive-dialog pass their content in through slots
private _autofocusElement(): HTMLElement | null {
const element = this.querySelector<HTMLElement>("[autofocus]");
if (element) {
return element;
}
for (const slot of this.querySelectorAll("slot")) {
for (const assigned of slot.assignedElements({ flatten: true })) {
if (assigned.matches("[autofocus]")) {
return assigned as HTMLElement;
}
const nested = assigned.querySelector<HTMLElement>("[autofocus]");
if (nested) {
return nested;
}
}
}
return null;
}
private _handleAfterShow = (ev: Event) => {
if (ev.eventPhase !== Event.AT_TARGET) {
return;
+1
View File
@@ -238,6 +238,7 @@ export class HaGridSizeEditor extends LitElement {
grid-template-rows: auto auto;
grid-template-columns: auto 1fr;
gap: var(--ha-space-2);
padding-left: var(--ha-space-4);
}
.precise {
grid-area: precise;
+30 -14
View File
@@ -42,6 +42,8 @@ export class HaMjpegPlayer extends LitElement {
private _drawInterval?: number;
private _copyingFrame = false;
/** The video for picture in picture, undefined when it can't be shown. */
public get videoElement(): HTMLVideoElement | undefined {
return this._canCopy ? this._videoEl : undefined;
@@ -66,12 +68,13 @@ export class HaMjpegPlayer extends LitElement {
}
try {
if (!this._stream) {
this._drawFrame();
// The canvas already has a frame from the copy test
this._copyFrame();
// Captures a frame whenever the canvas is drawn
this._stream = this._canvas!.captureStream();
video.srcObject = this._stream;
this._drawInterval = window.setInterval(
() => this._drawFrame(),
() => this._copyFrame(),
1000 / PICTURE_IN_PICTURE_FRAME_RATE
);
}
@@ -178,32 +181,45 @@ export class HaMjpegPlayer extends LitElement {
/** An image from another origin can't be copied out of a canvas. */
private _testCopy(): boolean {
const image = this._imageEl!;
try {
this._drawFrame();
this._canvas?.getContext("2d")?.getImageData(0, 0, 1, 1);
return Boolean(this._canvas);
this._drawFrame(image, image.naturalWidth, image.naturalHeight);
this._canvas!.getContext("2d")?.getImageData(0, 0, 1, 1);
return true;
} catch (_err: unknown) {
return false;
}
}
private _drawFrame() {
// Firefox only draws the first frame of an MJPEG image, a bitmap of it
// has the current one
private async _copyFrame() {
const image = this._imageEl;
if (!image?.naturalWidth) {
if (this._copyingFrame || !image?.naturalWidth) {
return;
}
this._copyingFrame = true;
try {
const bitmap = await createImageBitmap(image);
this._drawFrame(bitmap, bitmap.width, bitmap.height);
bitmap.close();
} catch (_err: unknown) {
// The stream is between frames or restarting, the next copy tries again
} finally {
this._copyingFrame = false;
}
}
private _drawFrame(frame: CanvasImageSource, width: number, height: number) {
if (!this._canvas) {
this._canvas = document.createElement("canvas");
}
const canvas = this._canvas;
if (
canvas.width !== image.naturalWidth ||
canvas.height !== image.naturalHeight
) {
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
canvas.getContext("2d")?.drawImage(image, 0, 0);
canvas.getContext("2d")?.drawImage(frame, 0, 0);
}
private _stopVideo = () => {
+11 -3
View File
@@ -1,9 +1,9 @@
import type { TemplateResult } from "lit";
import type { PropertyValues, TemplateResult } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { ifDefined } from "lit/directives/if-defined";
import type { ActionHandlerOptions } from "../../data/lovelace/action_handler";
import { actionHandler } from "../../panels/lovelace/common/directives/action-handler-directive";
import { actionHandlerBind } from "../../panels/lovelace/common/directives/action-handler-directive";
import "../ha-icon";
import "../ha-svg-icon";
@@ -56,6 +56,11 @@ export class HaTileIcon extends LitElement {
return nothing;
}
protected updated(changedProps: PropertyValues<this>): void {
super.updated(changedProps);
actionHandlerBind(this, this.actionHandlerOptions);
}
protected render(): TemplateResult {
const hasImage = Boolean(this.imageUrl);
@@ -67,7 +72,6 @@ export class HaTileIcon extends LitElement {
aria-label=${ifDefined(
this.interactive ? this.accessibleLabel : undefined
)}
.actionHandler=${actionHandler(this.actionHandlerOptions)}
>
<slot name="icon">${this._renderIcon()}</slot>
</div>
@@ -94,6 +98,7 @@ export class HaTileIcon extends LitElement {
:host([interactive]) {
-webkit-tap-highlight-color: transparent;
pointer-events: auto;
cursor: pointer;
}
:host([interactive]:active) {
transform: scale(1.2);
@@ -143,6 +148,9 @@ export class HaTileIcon extends LitElement {
transition: color 180ms ease-in-out;
pointer-events: none;
}
::slotted(:not([slot])) {
pointer-events: none;
}
.container img {
width: 100%;
height: 100%;
+51
View File
@@ -5,6 +5,9 @@ import {
} from "home-assistant-js-websocket";
import type { Store } from "home-assistant-js-websocket/dist/store";
import type { DataTableRowData } from "../components/data-table/ha-data-table";
import type { HomeAssistant } from "../types";
import type { ConfigEntry } from "./config_entries";
import type { DeviceRegistryEntry } from "./device/device_registry";
export interface BluetoothDeviceData extends DataTableRowData {
address: string;
@@ -74,6 +77,54 @@ export const isScannerStateMismatch = (state: BluetoothScannerState): boolean =>
state.requested_mode !== "auto" &&
state.current_mode !== state.requested_mode;
export interface BluetoothAdapterDevice {
device: DeviceRegistryEntry;
entry: ConfigEntry;
}
/**
* Splits the Bluetooth adapters into enabled and disabled ones. An adapter is
* a device with a Bluetooth connection that belongs to a `bluetooth` config
* entry. Config entries without such a device (for example ignored discoveries
* or removed proxies) are not adapters, unless they are disabled, so they can
* still be enabled again.
*/
export const getBluetoothAdapters = (
devices: HomeAssistant["devices"],
configEntries: ConfigEntry[]
) => {
const entryMap = new Map(configEntries.map((e) => [e.entry_id, e]));
const enabledDevices: BluetoothAdapterDevice[] = [];
const disabledDevices: BluetoothAdapterDevice[] = [];
const matchedEntryIds = new Set<string>();
for (const device of Object.values(devices)) {
const btConnection = device.connections.find((c) => c[0] === "bluetooth");
if (!btConnection) {
continue;
}
const entry = device.config_entries
.map((id) => entryMap.get(id))
.find((e) => e !== undefined);
if (!entry) {
continue;
}
matchedEntryIds.add(entry.entry_id);
if (entry.disabled_by !== null) {
disabledDevices.push({ device, entry });
} else {
enabledDevices.push({ device, entry });
}
}
const disabledEntriesWithoutDevice = configEntries.filter(
(e) => e.disabled_by !== null && !matchedEntryIds.has(e.entry_id)
);
return { enabledDevices, disabledDevices, disabledEntriesWithoutDevice };
};
export const subscribeBluetoothScannersDetailsUpdates = (
conn: Connection,
store: Store<BluetoothScannersDetails>
+6
View File
@@ -79,6 +79,8 @@ export const selectCameraStreams = ({
];
};
export type CameraStreamDisconnectReason = "home_assistant" | "stream_failed";
/** What the player tells the user about the connection of its stream. */
export interface CameraStreamStatus {
/** The stream that is shown, undefined until the camera's types are known */
@@ -91,6 +93,10 @@ export interface CameraStreamStatus {
hasAudio: boolean;
/** The app plays the shown stream in its own player, over the page */
inApp?: boolean;
/** The camera is unavailable, no stream is started */
unavailable?: boolean;
/** Home Assistant is disconnected, or the only stream failed */
disconnected?: CameraStreamDisconnectReason;
}
export const computeCameraStreamStatus = (
+19 -5
View File
@@ -239,12 +239,29 @@ export interface CoverEntity extends HassEntityBase {
attributes: CoverEntityAttributes;
}
// For covers that report no value, the open or closed state tells where it is
const valueFromState = (stateObj: CoverEntity): number | undefined => {
if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
return undefined;
}
return stateObj.state === "closed" || stateObj.state === "opening" ? 0 : 100;
};
export const coverCurrentValue = (
stateObj: CoverEntity,
mode: CoverControlMode
): number | undefined => {
if (mode === "tilt") {
return stateObj.attributes.current_tilt_position ?? undefined;
const tilt = stateObj.attributes.current_tilt_position;
// The state only describes the slats when the cover can't move up or down
if (
tilt != null ||
coverSupportsTiltPosition(stateObj) ||
coverHasPositionControls(stateObj)
) {
return tilt ?? undefined;
}
return valueFromState(stateObj);
}
const position = stateObj.attributes.current_position;
if (
@@ -253,10 +270,7 @@ export const coverCurrentValue = (
) {
return position ?? undefined;
}
if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
return undefined;
}
return stateObj.state === "closed" || stateObj.state === "opening" ? 0 : 100;
return valueFromState(stateObj);
};
declare global {
+11 -3
View File
@@ -567,7 +567,9 @@ export const computeEnergyStatisticArea = (
* device in the same list, which happens when one device has several meters of
* the same type. Those are named with the entity name as well, so they stay
* apart in the charts. Lists hold one type of device, so an energy meter and a
* water meter of one device never collide.
* water meter of one device never collide. Separate devices that only share
* a name keep their label when their entity names match too, since adding
* those would not tell them apart, unless a custom name takes the same label.
*/
export const computeAmbiguousEnergyDevices = (
states: HomeAssistant["states"],
@@ -606,8 +608,14 @@ export const computeAmbiguousEnergyDevices = (
const ambiguous = new Set<string>();
for (const statisticIds of statisticIdsByLabel.values()) {
if (statisticIds.size > 1) {
for (const statisticId of statisticIds) {
if (!named.has(statisticId)) {
const unnamed = [...statisticIds].filter((id) => !named.has(id));
const entityLabels = new Set(
unnamed.map((statisticId) =>
formatEntityName(states[statisticId], ENERGY_DEVICE_ENTITY_NAME)
)
);
if (unnamed.length < statisticIds.size || entityLabels.size > 1) {
for (const statisticId of unnamed) {
ambiguous.add(statisticId);
}
}
+10 -4
View File
@@ -153,17 +153,23 @@ export const computeEnergySuggestions = (
};
/**
* The dismissed statistics with the new one added, dropping statistics that
* The dismissed statistics with the new ones added, dropping statistics that
* no longer exist.
*/
export const updateDismissedSuggestions = (
dismissed: string[],
statisticId: string,
statisticIds: string[],
statistics: StatisticsMetaData[]
): string[] => {
const existing = new Set(statistics.map((meta) => meta.statistic_id));
return [
...dismissed.filter((id) => id !== statisticId && existing.has(id)),
statisticId,
...dismissed.filter((id) => !statisticIds.includes(id) && existing.has(id)),
...statisticIds,
];
};
/** The dismissed statistics without the restored one. */
export const restoreDismissedSuggestion = (
dismissed: string[],
statisticId: string
): string[] => dismissed.filter((id) => id !== statisticId);
@@ -3,8 +3,11 @@ import {
mdiImageMultipleOutline,
mdiLightningBolt,
} from "@mdi/js";
import type { ContextType } from "@lit/context";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { isComponentLoaded } from "../../common/config/is_component_loaded";
import { consume } from "../../common/decorators/consume";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../common/translations/localize";
import { CAMERA_STREAM_TYPE_NAMES } from "../../components/camera/ha-camera-stream-badge";
@@ -21,9 +24,14 @@ import {
type CameraStreamType,
type StreamType,
} from "../../data/camera-streams";
import { fetchCloudStatus } from "../../data/cloud";
import { apiContext, configContext } from "../../data/context";
import { haStyleDialog, haStyleDialogFixedTop } from "../../resources/styles";
import { DialogMixin } from "../dialog-mixin";
import type { CameraStreamInfoDialogParams } from "./show-dialog-camera-stream-info";
import type {
CameraStreamInfo,
CameraStreamInfoDialogParams,
} from "./show-dialog-camera-stream-info";
// Ordered from the fastest to the most compatible
const STREAM_TYPES: { type: CameraStreamType; icon: string }[] = [
@@ -40,11 +48,56 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: apiContext })
private _api!: ContextType<typeof apiContext>;
@consume({ context: configContext })
private _hassConfig!: ContextType<typeof configContext>;
@state() private _cloudIceServers = false;
@state() private _info?: CameraStreamInfo;
private _unsubscribe?: () => void;
public connectedCallback() {
super.connectedCallback();
this._unsubscribe = this.params?.subscribe((info) => {
this._info = info;
});
}
public disconnectedCallback() {
this._unsubscribe?.();
this._unsubscribe = undefined;
super.disconnectedCallback();
}
protected firstUpdated() {
this._fetchCloudIceServers();
}
// The same check that core uses to add the cloud TURN servers
private async _fetchCloudIceServers() {
if (!isComponentLoaded(this._hassConfig.config, "cloud")) {
return;
}
try {
const status = await fetchCloudStatus(this._api.callWS);
this._cloudIceServers =
status.logged_in &&
status.active_subscription &&
status.prefs.cloud_ice_servers_enabled;
} catch (_err) {
// Without the cloud status the label stays hidden
}
}
protected render() {
if (!this.params) {
if (!this._info) {
return nothing;
}
const { status, supportedTypes } = this.params;
const { status, supportedTypes } = this._info;
// Without a video stream, still images are all the camera has
const stillImagesOnly = supportedTypes?.length === 0;
// MJPEG is only the fallback, only worth explaining while it shows
@@ -73,6 +126,22 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
: "ui.dialogs.camera_stream_info.intro"
)}
</p>
${
status.disconnected
? html`<ha-alert alert-type="error">
${this._localize(
`ui.dialogs.camera_stream_info.disconnected.${status.disconnected}`
)}
</ha-alert>`
: nothing
}
${
status.unavailable
? html`<ha-alert alert-type="warning">
${this._localize("ui.dialogs.camera_stream_info.unavailable")}
</ha-alert>`
: nothing
}
${
mjpegInUse && !stillImagesOnly
? html`<ha-alert alert-type="info">
@@ -112,7 +181,7 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
type: CameraStreamType;
icon: string;
}) {
const { status } = this.params!;
const { status } = this._info!;
const current = !status.connecting && status.type === type;
const upgrading = status.upgrading === type;
return html`
@@ -124,6 +193,18 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
wrap-supporting-text
>
<ha-svg-icon slot="start" .path=${icon}></ha-svg-icon>
${
type === STREAM_TYPE_WEB_RTC && this._cloudIceServers
? html`<span slot="headline" class="headline">
${CAMERA_STREAM_TYPE_NAMES[type]}
<span class="tag cloud"
>${this._localize(
"ui.dialogs.camera_stream_info.enhanced_by_cloud"
)}</span
>
</span>`
: nothing
}
${
current
? html`<span slot="end" class="tag current"
@@ -188,6 +269,20 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
color: var(--secondary-text-color);
}
.headline {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--ha-space-2);
/* The row keeps the headline on one line, but a long tag must wrap */
white-space: normal;
}
.tag.cloud {
background-color: var(--ha-color-fill-primary-quiet-resting);
color: var(--ha-color-on-primary-quiet);
}
.tag.current {
background-color: var(--ha-color-fill-success-quiet-resting);
color: var(--ha-color-on-success-quiet);
@@ -1,12 +1,17 @@
import { fireEvent } from "../../common/dom/fire_event";
import type { CameraStreamStatus, StreamType } from "../../data/camera-streams";
export interface CameraStreamInfoDialogParams {
export interface CameraStreamInfo {
status: CameraStreamStatus;
/** The stream types the camera supports, undefined while unknown */
supportedTypes?: StreamType[];
}
export interface CameraStreamInfoDialogParams {
/** Calls back with the current info right away and on every change */
subscribe: (callback: (info: CameraStreamInfo) => void) => () => void;
}
export const showCameraStreamInfoDialog = (
element: HTMLElement,
params: CameraStreamInfoDialogParams
+1 -1
View File
@@ -46,7 +46,7 @@ export const DOMAINS_WITH_NEW_MORE_INFO = [
"media_player",
];
/** Domains with full height more info dialog */
export const DOMAINS_FULL_HEIGHT_MORE_INFO = ["update"];
export const DOMAINS_FULL_HEIGHT_MORE_INFO = ["camera", "update"];
/** Domains with separate more info dialog. */
export const DOMAINS_WITH_MORE_INFO = [
@@ -9,6 +9,10 @@ import { consumeLocalize } from "../../../common/decorators/consume-context-entr
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import {
adaptiveDialogModeContext,
type DialogSheetMode,
} from "../../../components/ha-adaptive-dialog";
import "../../../components/ha-button";
import "../../../components/camera/ha-camera-player";
import type { HaCameraPlayer } from "../../../components/camera/ha-camera-player";
@@ -50,6 +54,10 @@ class MoreInfoCamera extends LitElement {
@state() private _attached = false;
@state()
@consume({ context: adaptiveDialogModeContext, subscribe: true })
private _dialogMode?: DialogSheetMode;
@state() private _microphoneState: WebRtcMicrophoneState = "off";
@state() private _streamType?: CameraStreamType;
@@ -133,6 +141,7 @@ class MoreInfoCamera extends LitElement {
.stateObj=${this.stateObj}
allow-exoplayer
keep-awake
?fill=${this._dialogMode === "bottom-sheet"}
@microphone-changed=${this._microphoneChanged}
@stream-type-changed=${this._streamTypeChanged}
@camera-capabilities-changed=${this._capabilitiesChanged}
@@ -315,6 +324,10 @@ class MoreInfoCamera extends LitElement {
ev: HASSDomEvent<HASSDomEvents["stream-type-changed"]>
) {
this._streamType = ev.detail.type;
// A removed WebRTC player can't tell that its microphone stopped
if (ev.detail.type !== STREAM_TYPE_WEB_RTC && !this._useAppMicrophone) {
this._microphoneState = "off";
}
}
private _capabilitiesChanged(
@@ -334,7 +347,9 @@ class MoreInfoCamera extends LitElement {
static styles = css`
:host {
display: block;
display: flex;
flex-direction: column;
flex: 1;
}
.buttons {
@@ -22,7 +22,6 @@ import {
coverHasPositionControls,
coverHasTiltControls,
coverModeAttribute,
coverSupportsPosition,
coverSupportsSetValue,
defaultCoverMode,
} from "../../../data/cover";
@@ -164,7 +163,7 @@ class MoreInfoCover extends LitElement {
if (!request || this._drag) {
return undefined;
}
if (request.mode === "position" && !coverSupportsPosition(this.stateObj!)) {
if (!coverSupportsSetValue(this.stateObj!, request.mode)) {
return this._hint(request.value ? "requested_open" : "requested_closed");
}
return this._hint("requested", {
@@ -95,6 +95,23 @@ class DialogStartupProgress extends DialogMixin(LitElement) {
.slice(0, MAX_SLOWEST);
});
}
if (changedProps.has("_progress") || changedProps.has("_setups")) {
this._loadTitles();
}
}
private _loadTitles() {
const progress = this._progress
? this._computeProgress(this._progress, this._config.config.state)
: undefined;
const domains = [
...(progress?.active.map(([domain]) => domain) ?? []),
...(progress?.failed ?? []),
...(this._setups?.map((setup) => setup.domain) ?? []),
];
if (domains.length) {
this._i18n.loadBackendTranslation("title", domains);
}
}
protected render() {
@@ -264,6 +281,13 @@ class DialogStartupProgress extends DialogMixin(LitElement) {
static styles = [
haStyleDialog,
css`
@media (min-width: 451px) and (min-height: 501px) {
ha-dialog {
/* Fixed height so the dialog keeps its size as setups change. */
--ha-dialog-min-height: calc(var(--safe-height) / 2);
--ha-dialog-max-height: var(--ha-dialog-min-height);
}
}
ha-spinner {
display: block;
margin: var(--ha-space-6) auto;
@@ -272,6 +296,15 @@ class DialogStartupProgress extends DialogMixin(LitElement) {
display: flex;
flex-direction: column;
gap: var(--ha-space-1);
/* Keeps the progress in view while the active list scrolls. */
position: sticky;
top: 0;
z-index: 1;
padding-bottom: var(--ha-space-4);
background: var(
--ha-dialog-surface-background,
var(--card-background-color, var(--ha-color-surface-default))
);
}
.phase {
font-weight: var(--ha-font-weight-medium);
@@ -288,6 +321,9 @@ class DialogStartupProgress extends DialogMixin(LitElement) {
font-size: var(--ha-font-size-m);
font-weight: var(--ha-font-weight-medium);
}
.status + h3 {
margin-top: 0;
}
ha-svg-icon {
flex-shrink: 0;
color: var(--error-color);
@@ -44,7 +44,7 @@ export class HaVoiceAssistantSetupStepChangeWakeWord extends LitElement {
@click=${this._wakeWordPicked}
.value=${wakeWord.id}
>
${wakeWord.wake_word}
<div slot="headline">${wakeWord.wake_word}</div>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`
)}
+29 -1
View File
@@ -75,11 +75,39 @@ const clearUrlParams = () => {
}
};
const SERVER_CHECK_TIMEOUT = 10_000;
const checkServer = async () => {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), SERVER_CHECK_TIMEOUT);
try {
const response = await fetch(`${hassUrl}/manifest.json`, {
mode: "no-cors",
cache: "no-store",
signal: controller.signal,
});
if (response.status >= 500) {
throw new Error(`Home Assistant responded with ${response.status}`);
}
} finally {
clearTimeout(timeout);
}
};
// The login page is never cached, so check the server is up before getAuth redirects to it.
const loadTokensOrCheckServer = async () => {
const tokens = loadTokens();
if (!tokens || tokens.hassUrl !== hassUrl) {
await checkServer();
}
return tokens;
};
const authOptions = {
hassUrl,
limitHassInstance: true,
saveTokens,
loadTokens: () => Promise.resolve(loadTokens()),
loadTokens: loadTokensOrCheckServer,
};
const getAuthDroppingStaleCallback = async () => {
@@ -1,13 +1,14 @@
import "@home-assistant/webawesome/dist/components/divider/divider";
import type { ContextType } from "@lit/context";
import {
mdiApplicationImport,
mdiArrowUpBoldCircleOutline,
mdiCheckCircle,
mdiChip,
mdiCursorDefaultClickOutline,
mdiDelete,
mdiDocker,
mdiDotsVertical,
mdiDownload,
mdiExclamationThick,
mdiFlask,
mdiHammer,
@@ -22,7 +23,6 @@ import {
mdiNumeric6,
mdiNumeric7,
mdiNumeric8,
mdiPackageVariantRemove,
mdiPlay,
mdiPound,
mdiRestart,
@@ -637,7 +637,7 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
<ha-progress-button
.disabled=${!this._currentAddon.available}
@click=${this._installClicked}
.iconPath=${mdiApplicationImport}
.iconPath=${mdiDownload}
>
${this.i18n.localize(
"ui.panel.config.apps.dashboard.install"
@@ -714,10 +714,7 @@ class SupervisorAppInfo extends MobileAwareMixin(LitElement) {
this._uninstalling
}
>
<ha-svg-icon
slot="icon"
.path=${mdiPackageVariantRemove}
></ha-svg-icon>
<ha-svg-icon slot="icon" .path=${mdiDelete}></ha-svg-icon>
${this.i18n.localize(
"ui.panel.config.apps.dashboard.uninstall"
)}
@@ -89,7 +89,11 @@ class HaBackupConfigAgents extends LitElement {
const retention = this.agentsConfig?.[agentId]?.retention;
if (retention) {
if (retention && !this._value.includes(agentId)) {
texts.push(
this.hass.localize("ui.panel.config.backup.agents.retention_inactive")
);
} else if (retention) {
if (retention.copies === null && retention.days === null) {
texts.push(
this.hass.localize("ui.panel.config.backup.agents.retention_all")
@@ -120,21 +120,34 @@ class HaConfigBackupDetails extends LitElement {
</p>
</div>
`
: html`<ha-backup-config-retention
location-specific
.headline=${this.hass.localize(
`ui.panel.config.backup.location.retention_for_${isLocalAgent(this.agentId) ? "this_system" : "location"}`,
{ location: agentName }
)}
.hass=${this.hass}
.retention=${
!this.config
? undefined
: this.config.agents[this.agentId]
?.retention || null
}
@value-changed=${this._retentionChanged}
></ha-backup-config-retention>`
: html`${
this.config &&
!this.config.create_backup.agent_ids.includes(
this.agentId
)
? html`<div class="card-content">
<ha-alert alert-type="info">
${this.hass.localize(
"ui.panel.config.backup.location.retention_inactive"
)}
</ha-alert>
</div>`
: nothing
}<ha-backup-config-retention
location-specific
.headline=${this.hass.localize(
`ui.panel.config.backup.location.retention_for_${isLocalAgent(this.agentId) ? "this_system" : "location"}`,
{ location: agentName }
)}
.hass=${this.hass}
.retention=${
!this.config
? undefined
: this.config.agents[this.agentId]
?.retention || null
}
@value-changed=${this._retentionChanged}
></ha-backup-config-retention>`
}
</ha-card>
<ha-card>
+1 -3
View File
@@ -50,9 +50,7 @@ export class CloudStart extends LitElement {
.hass=${this.hass}
.narrow=${this.narrow}
back-path="/config"
.header=${this.hass.localize(
"ui.panel.config.cloud.login.landing_title"
)}
header="Home Assistant Link"
>
<cloud-signed-out-menu
slot="toolbar-icon"
@@ -1,12 +1,14 @@
import { mdiFire, mdiFlash, mdiLightbulbOnOutline, mdiWater } from "@mdi/js";
import type { ContextType } from "@lit/context";
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import type { CSSResultGroup, TemplateResult } from "lit";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { repeat } from "lit/directives/repeat";
import memoizeOne from "memoize-one";
import { consume } from "../../../../common/decorators/consume";
import { fireEvent } from "../../../../common/dom/fire_event";
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
import { consumeEntityStates } from "../../../../common/decorators/consume-context-entry";
import { computeAreaName } from "../../../../common/entity/compute_area_name";
import { getEntityAreaId } from "../../../../common/entity/context/get_entity_context";
@@ -35,6 +37,7 @@ import type {
import {
computeEnergySuggestions,
ENERGY_SUGGESTION_EDITORS,
restoreDismissedSuggestion,
updateDismissedSuggestions,
} from "../../../../data/energy_suggestions";
import {
@@ -55,6 +58,8 @@ const TAB_ICONS: Record<EnergySuggestionTab, string> = {
water: mdiWater,
};
const DISMISS_ALL_THRESHOLD = 3;
@customElement("ha-energy-suggestions")
export class EnergySuggestions extends LitElement {
@property({ attribute: false })
@@ -65,6 +70,8 @@ export class EnergySuggestions extends LitElement {
@property() public tab: EnergySuggestionTab = "electricity";
@property({ type: Boolean, attribute: false }) public showDismissed = false;
@state() private _statistics?: StatisticsMetaData[];
@state() private _dismissed?: string[];
@@ -72,6 +79,11 @@ export class EnergySuggestions extends LitElement {
// Dismissals not yet echoed by the subscription, so an older echo can't drop them
@state() private _pendingDismissed: string[] = [];
// Restores not yet echoed by the subscription
@state() private _pendingRestored: string[] = [];
private _reportedDismissedCount?: number;
@state() private _slots: Record<string, EnergySuggestionSlot> = {};
@state() private _loadFailed = false;
@@ -114,27 +126,46 @@ export class EnergySuggestions extends LitElement {
(
statistics: StatisticsMetaData[],
preferences: EnergyPreferences,
dismissed: string[],
states: HomeAssistant["states"],
tab: EnergySuggestionTab
) =>
computeEnergySuggestions({
statistics,
preferences,
dismissed,
states,
}).filter((suggestion) => suggestion.tab === tab)
computeEnergySuggestions({ statistics, preferences, states }).filter(
(suggestion) => suggestion.tab === tab
)
);
private _allDismissed = memoizeOne((stored: string[], pending: string[]) =>
pending.length
? [...stored, ...pending.filter((id) => !stored.includes(id))]
: stored
private _splitSuggestions = memoizeOne(
(all: EnergyMeterSuggestion[], dismissed: string[]) => ({
suggestions: all.filter(
(suggestion) => !dismissed.includes(suggestion.statisticId)
),
dismissedSuggestions: all.filter((suggestion) =>
dismissed.includes(suggestion.statisticId)
),
})
);
private _allDismissed = memoizeOne(
(stored: string[], pending: string[], restored: string[]) =>
[...stored, ...pending.filter((id) => !stored.includes(id))].filter(
(id) => !restored.includes(id)
)
);
private get _currentDismissed(): string[] {
return this._allDismissed(
this._dismissed!,
this._pendingDismissed,
this._pendingRestored
);
}
// Kept live so a dismiss in another tab isn't overwritten by this one.
private _unsubDismissed?: Promise<UnsubscribeFunc>;
// Each save builds on the list the previous one stored
private _saveQueue: Promise<unknown> = Promise.resolve();
connectedCallback() {
super.connectedCallback();
this._load();
@@ -161,6 +192,9 @@ export class EnergySuggestions extends LitElement {
this._pendingDismissed = this._pendingDismissed.filter(
(id) => !dismissed.includes(id)
);
this._pendingRestored = this._pendingRestored.filter((id) =>
dismissed.includes(id)
);
}
);
try {
@@ -203,14 +237,8 @@ export class EnergySuggestions extends LitElement {
if (!this._statistics || !this._dismissed) {
return nothing;
}
const suggestions = this._computeSuggestions(
this._statistics,
this.preferences,
this._allDismissed(this._dismissed, this._pendingDismissed),
this._states,
this.tab
);
if (!suggestions.length) {
const { suggestions, dismissedSuggestions, showDismissed } = this._view()!;
if (!suggestions.length && !showDismissed) {
return nothing;
}
@@ -218,27 +246,82 @@ export class EnergySuggestions extends LitElement {
<ha-card>
<h1 class="card-header">
<ha-svg-icon .path=${mdiLightbulbOnOutline}></ha-svg-icon>
${this._i18n.localize("ui.panel.config.energy.suggestions.title", {
count: suggestions.length,
})}
${
suggestions.length
? this._i18n.localize(
"ui.panel.config.energy.suggestions.title",
{
count: suggestions.length,
}
)
: this._i18n.localize(
"ui.panel.config.energy.suggestions.dismissed_title"
)
}
</h1>
<div class="card-content">
<p>
${this._i18n.localize("ui.panel.config.energy.suggestions.sub")}
</p>
<div class="items-container">
${repeat(
suggestions,
(suggestion) => suggestion.statisticId,
(suggestion) => this._renderSuggestion(suggestion)
)}
<div class="intro">
<p>
${this._i18n.localize(
suggestions.length
? "ui.panel.config.energy.suggestions.sub"
: "ui.panel.config.energy.suggestions.dismissed_sub"
)}
</p>
${
suggestions.length > DISMISS_ALL_THRESHOLD
? html`<ha-button
size="s"
appearance="plain"
variant="neutral"
@click=${this._dismissAll}
>${this._i18n.localize(
"ui.panel.config.energy.suggestions.dismiss_all"
)}</ha-button
>`
: nothing
}
</div>
${
suggestions.length
? html`<div class="items-container">
${repeat(
suggestions,
(suggestion) => suggestion.statisticId,
(suggestion) => this._renderSuggestion(suggestion, false)
)}
</div>`
: nothing
}
${
showDismissed
? html`${
suggestions.length
? html`<h3>
${this._i18n.localize(
"ui.panel.config.energy.suggestions.dismissed"
)}
</h3>`
: nothing
}
<div class="items-container">
${repeat(
dismissedSuggestions,
(suggestion) => suggestion.statisticId,
(suggestion) => this._renderSuggestion(suggestion, true)
)}
</div>`
: nothing
}
</div>
</ha-card>
`;
}
private _renderSuggestion(suggestion: EnergyMeterSuggestion) {
private _renderSuggestion(
suggestion: EnergyMeterSuggestion,
dismissed: boolean
) {
const slot = this._slotFor(suggestion);
const label = getStatisticLabel(
this._states,
@@ -259,7 +342,13 @@ export class EnergySuggestions extends LitElement {
<div class="suggestion" role="group" aria-label=${label}>
<ha-svg-icon .path=${TAB_ICONS[suggestion.tab]}></ha-svg-icon>
<div class="content">
<span class="label">${label}</span>
<button
class="link label"
.suggestion=${suggestion}
@click=${this._showMoreInfo}
>
${label}
</button>
${
area
? html`<span class="label secondary"
@@ -300,9 +389,11 @@ export class EnergySuggestions extends LitElement {
appearance="plain"
variant="neutral"
.suggestion=${suggestion}
@click=${this._dismiss}
@click=${dismissed ? this._restore : this._dismiss}
>${this._i18n.localize(
"ui.panel.config.energy.suggestions.dismiss"
dismissed
? "ui.panel.config.energy.suggestions.restore"
: "ui.panel.config.energy.suggestions.dismiss"
)}</ha-button
>
</div>
@@ -336,37 +427,132 @@ export class EnergySuggestions extends LitElement {
})}`;
}
private async _dismiss(ev: Event) {
private _showMoreInfo(
ev: HASSDomCurrentTargetEvent<
HTMLButtonElement & { suggestion: EnergyMeterSuggestion }
>
) {
fireEvent(this, "hass-more-info", {
entityId: ev.currentTarget.suggestion.statisticId,
});
}
private _dismiss(ev: Event) {
const suggestion: EnergyMeterSuggestion = (ev.currentTarget as any)
.suggestion;
const statisticId = suggestion.statisticId;
this._pendingDismissed = [...this._pendingDismissed, statisticId];
this._dismissStatistics([suggestion.statisticId], "dismiss_failed");
}
private _dismissAll() {
this._dismissStatistics(
this._view()!.suggestions.map((suggestion) => suggestion.statisticId),
"dismiss_all_failed"
);
}
private async _dismissStatistics(
statisticIds: string[],
failedKey: "dismiss_failed" | "dismiss_all_failed"
) {
this._pendingDismissed = [...this._pendingDismissed, ...statisticIds];
this._pendingRestored = this._pendingRestored.filter(
(id) => !statisticIds.includes(id)
);
try {
await saveFrontendUserData(this._connection.connection, "energy", {
dismissed_suggestions: updateDismissedSuggestions(
this._allDismissed(this._dismissed!, this._pendingDismissed),
statisticId,
this._statistics!
),
});
await this._saveDismissed((dismissed) =>
updateDismissedSuggestions(dismissed, statisticIds, this._statistics!)
);
} catch (err: any) {
this._pendingDismissed = this._pendingDismissed.filter(
(id) => id !== statisticId
(id) => !statisticIds.includes(id)
);
showAlertDialog(this, {
title: this._i18n.localize(
"ui.panel.config.energy.suggestions.dismiss_failed"
`ui.panel.config.energy.suggestions.${failedKey}`
),
text: err.message,
});
}
}
private _view() {
if (this._loadFailed || !this._statistics || !this._dismissed) {
return undefined;
}
const { suggestions, dismissedSuggestions } = this._splitSuggestions(
this._computeSuggestions(
this._statistics,
this.preferences,
this._states,
this.tab
),
this._currentDismissed
);
return {
suggestions,
dismissedSuggestions,
showDismissed: this.showDismissed && dismissedSuggestions.length > 0,
};
}
protected updated(changedProps: PropertyValues): void {
super.updated(changedProps);
const count = this._view()?.dismissedSuggestions.length ?? 0;
if (count !== this._reportedDismissedCount) {
this._reportedDismissedCount = count;
fireEvent(this, "energy-suggestions-dismissed-count", { count });
}
}
private async _restore(ev: Event) {
const suggestion: EnergyMeterSuggestion = (ev.currentTarget as any)
.suggestion;
const statisticId = suggestion.statisticId;
this._pendingRestored = [...this._pendingRestored, statisticId];
this._pendingDismissed = this._pendingDismissed.filter(
(id) => id !== statisticId
);
try {
await this._saveDismissed((dismissed) =>
restoreDismissedSuggestion(dismissed, statisticId)
);
} catch (err: any) {
this._pendingRestored = this._pendingRestored.filter(
(id) => id !== statisticId
);
showAlertDialog(this, {
title: this._i18n.localize(
"ui.panel.config.energy.suggestions.restore_failed"
),
text: err.message,
});
}
}
private _saveDismissed(update: (dismissed: string[]) => string[]) {
const save = this._saveQueue.then(() =>
saveFrontendUserData(this._connection.connection, "energy", {
dismissed_suggestions: update(this._dismissed!),
})
);
this._saveQueue = save.catch(() => undefined);
return save;
}
static get styles(): CSSResultGroup {
return [
haStyle,
energyCardStyles,
css`
.intro {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0 var(--ha-space-4);
}
.intro ha-button {
margin-inline-start: auto;
}
.suggestion {
display: flex;
flex-wrap: wrap;
@@ -384,6 +570,21 @@ export class EnergySuggestions extends LitElement {
flex-direction: column;
min-width: 0;
}
button.link {
align-self: flex-start;
max-width: 100%;
text-align: start;
text-decoration: none;
overflow-wrap: anywhere;
}
button.link:hover {
text-decoration: underline;
}
button.link:focus-visible {
outline: 2px solid var(--primary-color);
outline-offset: 2px;
border-radius: var(--ha-border-radius-sm);
}
.secondary {
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
@@ -407,4 +608,8 @@ declare global {
interface HTMLElementTagNameMap {
"ha-energy-suggestions": EnergySuggestions;
}
interface HASSDomEvents {
"energy-suggestions-dismissed-count": { count: number };
}
}
@@ -1,6 +1,9 @@
import "../../../layouts/hass-error-screen";
import {
mdiDotsVertical,
mdiDownload,
mdiEye,
mdiEyeOff,
mdiFire,
mdiLightningBolt,
mdiViewDashboardEdit,
@@ -10,6 +13,7 @@ import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { cache } from "lit/directives/cache";
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { navigate } from "../../../common/navigate";
import type {
EnergyPreferencesValidation,
@@ -38,6 +42,9 @@ import "./components/ha-energy-battery-settings";
import "./components/ha-energy-gas-settings";
import "./components/ha-energy-water-settings";
import "./components/ha-energy-suggestions";
import "../../../components/ha-dropdown";
import "../../../components/ha-dropdown-item";
import "../../../components/ha-svg-icon";
import { fileDownload } from "../../../util/file_download";
import { showToast } from "../../../util/toast";
import type { PageNavigation } from "../../../layouts/hass-tabs-subpage";
@@ -98,6 +105,11 @@ class HaConfigEnergy extends LitElement {
@state() private _statsMetadata?: Record<string, StatisticsMetaData>;
// Dismissed meters on the current tab, as counted by the suggestions card
@state() private _dismissedSuggestions = 0;
@state() private _showDismissedSuggestions = false;
private get _currTab(): string {
return this.route.path.split("/")[1] || "electricity";
}
@@ -105,6 +117,10 @@ class HaConfigEnergy extends LitElement {
protected willUpdate(changedProperties: PropertyValues<this>) {
if (changedProperties.has("route")) {
const [, tab, kind, ...key] = this.route.path.split("/");
const oldTab = changedProperties.get("route")?.path.split("/")[1];
if (oldTab !== undefined && oldTab !== tab) {
this._showDismissedSuggestions = false;
}
if (!tab || !TABS.some((t) => t.path.endsWith(`/${tab}`))) {
navigate(`${this.route.prefix}/electricity${location.search}`, {
replace: true,
@@ -175,6 +191,35 @@ class HaConfigEnergy extends LitElement {
)}
@click=${this._downloadDiagnostics}
></ha-icon-button>
${
this._dismissedSuggestions
? html`<ha-dropdown
@wa-select=${this._toggleDismissedSuggestions}
>
<ha-icon-button
slot="trigger"
.label=${this.hass.localize("ui.common.menu")}
.path=${mdiDotsVertical}
></ha-icon-button>
<ha-dropdown-item value="toggle_dismissed">
<ha-svg-icon
slot="icon"
.path=${this._showDismissedSuggestions ? mdiEyeOff : mdiEye}
></ha-svg-icon>
${
this._showDismissedSuggestions
? this.hass.localize(
"ui.panel.config.energy.suggestions.hide_dismissed"
)
: this.hass.localize(
"ui.panel.config.energy.suggestions.show_dismissed",
{ count: this._dismissedSuggestions }
)
}
</ha-dropdown-item>
</ha-dropdown>`
: nothing
}
</div>
<ha-alert>
${this.hass.localize("ui.panel.config.energy.new_device_info")}
@@ -184,6 +229,8 @@ class HaConfigEnergy extends LitElement {
.preferences=${this._preferences!}
.listPath=${`${this.route.prefix}/${this._currTab}`}
.tab=${this._currTab}
.showDismissed=${this._showDismissedSuggestions}
@energy-suggestions-dismissed-count=${this._dismissedSuggestionsChanged}
></ha-energy-suggestions>
${cache(this._renderTabContent())}
</div>
@@ -446,6 +493,19 @@ class HaConfigEnergy extends LitElement {
this._statsMetadata = statsMetadata;
}
private _dismissedSuggestionsChanged(
ev: HASSDomEvent<HASSDomEvents["energy-suggestions-dismissed-count"]>
) {
this._dismissedSuggestions = ev.detail.count;
if (!this._dismissedSuggestions) {
this._showDismissedSuggestions = false;
}
}
private _toggleDismissedSuggestions() {
this._showDismissedSuggestions = !this._showDismissedSuggestions;
}
private _customise() {
if (!this._preferences) {
return;
@@ -514,8 +514,16 @@ class AddIntegrationDialog extends LitElement {
return [...integrations]
.filter((item) => !brand || item.domain === brand)
.sort(byName)
.flatMap((item) => this._brandRows(item))
.filter((row) => !brand || !row.is_header);
.flatMap((item) =>
this._brandRows(item)
.filter((row) => !row.is_header)
// The brand on the second line, so its entries read as a group
.map((row) =>
brand || !this._isBrand(item)
? row
: { ...row, description: item.name }
)
);
}
// A brand shows its integrations here, not itself, like the website
if (category) {
@@ -1207,17 +1215,11 @@ class AddIntegrationDialog extends LitElement {
})}
>
${
!this._stickyBrand
? nothing
: this._filter
? html`<ha-section-title class="sticky">
${this._stickyBrand}
</ha-section-title>`
: html`<ha-integration-list-title
class="sticky raised"
>
${this._stickyBrand}
</ha-integration-list-title>`
this._stickyBrand
? html`<ha-section-title class="sticky">
${this._stickyBrand}
</ha-section-title>`
: nothing
}
<ha-list-virtualized
.rows=${this._filter ? rows : this._withEndSpace(rows)}
@@ -1771,7 +1773,7 @@ class AddIntegrationDialog extends LitElement {
);
}
// The virtualizer positions rows, so CSS sticky can't hold the brand
// The virtualizer positions rows, so CSS sticky can't hold the section title
@eventOptions({ passive: true })
private _visibilityChanged(ev: HASSDomEvent<HaListVisibilityChangedDetail>) {
const rows = this._getRows();
@@ -1794,11 +1796,7 @@ class AddIntegrationDialog extends LitElement {
return html`<div style="height: var(--ha-space-2)"></div>`;
}
if (integration.is_header) {
return this._filter
? html`<ha-section-title>${integration.name}</ha-section-title>`
: html`<ha-integration-list-title>
${integration.name}
</ha-integration-list-title>`;
return html`<ha-section-title>${integration.name}</ha-section-title>`;
}
return html`
<ha-integration-list-item
@@ -16,12 +16,14 @@ import "../../../../../components/item/ha-list-item-base";
import "../../../../../components/item/ha-list-item-button";
import "../../../../../components/list/ha-list-base";
import type {
BluetoothAdapterDevice,
BluetoothAllocationsData,
BluetoothScannerState,
BluetoothScannersDetails,
HaScannerType,
} from "../../../../../data/bluetooth";
import {
getBluetoothAdapters,
isScannerStateMismatch,
subscribeBluetoothConnectionAllocations,
subscribeBluetoothScannerState,
@@ -176,52 +178,11 @@ export class BluetoothAdapterInfoPage extends LitElement {
}
}
private _getBluetoothDevices = memoizeOne(
(devices: HomeAssistant["devices"], configEntries: ConfigEntry[]) => {
const entryMap = new Map(configEntries.map((e) => [e.entry_id, e]));
const enabledDevices: {
device: DeviceRegistryEntry;
entry: ConfigEntry;
}[] = [];
const disabledDevices: {
device: DeviceRegistryEntry;
entry: ConfigEntry;
}[] = [];
const matchedEntryIds = new Set<string>();
for (const device of Object.values(devices)) {
const btConnection = device.connections.find(
(c) => c[0] === "bluetooth"
);
if (!btConnection) {
continue;
}
const entry = device.config_entries
.map((id) => entryMap.get(id))
.find((e) => e !== undefined);
if (!entry) {
continue;
}
matchedEntryIds.add(entry.entry_id);
if (entry.disabled_by !== null) {
disabledDevices.push({ device, entry });
} else {
enabledDevices.push({ device, entry });
}
}
const disabledEntriesWithoutDevice = configEntries.filter(
(e) => e.disabled_by !== null && !matchedEntryIds.has(e.entry_id)
);
return { enabledDevices, disabledDevices, disabledEntriesWithoutDevice };
}
);
private _getBluetoothAdapters = memoizeOne(getBluetoothAdapters);
protected render(): TemplateResult {
const { enabledDevices, disabledDevices, disabledEntriesWithoutDevice } =
this._getBluetoothDevices(this.hass.devices, this._configEntries);
this._getBluetoothAdapters(this.hass.devices, this._configEntries);
return html`
<hass-subpage
@@ -301,9 +262,7 @@ export class BluetoothAdapterInfoPage extends LitElement {
`;
}
private _renderAdaptersList(
devices: { device: DeviceRegistryEntry; entry: ConfigEntry }[]
) {
private _renderAdaptersList(devices: BluetoothAdapterDevice[]) {
if (devices.length === 0) {
return html`<ha-list-item-base>
<div slot="headline">
@@ -11,18 +11,24 @@ import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import type { CSSResultGroup, TemplateResult } from "lit";
import { LitElement, css, html } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import "../../../../../components/animation/ha-fade-in";
import "../../../../../components/ha-alert";
import "../../../../../components/ha-button";
import "../../../../../components/ha-card";
import "../../../../../components/ha-icon-next";
import "../../../../../components/ha-svg-icon";
import "../../../../../components/item/ha-list-item-button";
import "../../../../../components/list/ha-list-nav";
import "../../../../../components/skeleton/ha-skeleton";
import "../../../../../components/skeleton/ha-skeleton-text";
import type {
BluetoothAllocationsData,
BluetoothDeviceData,
BluetoothScannerState,
} from "../../../../../data/bluetooth";
import {
getBluetoothAdapters,
isScannerStateMismatch,
subscribeBluetoothAdvertisements,
subscribeBluetoothConnectionAllocations,
@@ -34,6 +40,7 @@ import "../../../../../layouts/hass-subpage";
import { haStyle } from "../../../../../resources/styles";
import type { HomeAssistant, Route } from "../../../../../types";
import { brandsUrl } from "../../../../../util/brands-url";
import { getWsErrorMessage } from "../../../../../util/ws-error";
@customElement("bluetooth-config-dashboard")
export class BluetoothConfigDashboard extends LitElement {
@@ -45,7 +52,9 @@ export class BluetoothConfigDashboard extends LitElement {
@property({ attribute: "is-wide", type: Boolean }) public isWide = false;
@state() private _configEntries: ConfigEntry[] = [];
@state() private _configEntries?: ConfigEntry[];
@state() private _configEntriesError?: string;
@state() private _connectionAllocationData: BluetoothAllocationsData[] = [];
@@ -69,11 +78,17 @@ export class BluetoothConfigDashboard extends LitElement {
}
}
private async _loadConfigEntries(): Promise<void> {
this._configEntries = await getConfigEntries(this.hass, {
domain: "bluetooth",
});
}
private _loadConfigEntries = async (): Promise<void> => {
this._configEntriesError = undefined;
try {
this._configEntries = await getConfigEntries(this.hass, {
domain: "bluetooth",
});
} catch (err: unknown) {
this._configEntriesError =
getWsErrorMessage(err) || this.hass.localize("ui.common.unknown_error");
}
};
private async _subscribeBluetoothConnectionAllocations(): Promise<void> {
if (this._unsubConnectionAllocations) {
@@ -131,11 +146,17 @@ export class BluetoothConfigDashboard extends LitElement {
}
}
private _getBluetoothAdapters = memoizeOne(getBluetoothAdapters);
protected render(): TemplateResult {
const enabledEntries = this._configEntries.filter(
(e) => e.disabled_by === null
);
const adapterCount = enabledEntries.length;
// The device registry is null until it has loaded.
const adapterCount =
this._configEntries && this.hass.devices
? this._getBluetoothAdapters(this.hass.devices, this._configEntries)
.enabledDevices.length
: undefined;
const error = this._configEntriesError;
const loading = adapterCount === undefined && !error;
const totalSlots = this._connectionAllocationData.reduce(
(sum, a) => sum + a.slots,
0
@@ -163,40 +184,67 @@ export class BluetoothConfigDashboard extends LitElement {
back-path="/config/connectivity"
>
<div class="container">
<ha-card class="content network-status">
<div class="card-content">
<div class="heading">
<div class="icon ${status}">
<ha-svg-icon .path=${statusIcon}></ha-svg-icon>
</div>
<div class="details">
${this.hass.localize(
`ui.panel.config.bluetooth.status_${status}`
)}<br />
<small>
${this.hass.localize(
"ui.panel.config.bluetooth.connections_summary",
{ used: usedSlots, total: totalSlots }
)}
</small>
</div>
<img
class="logo"
alt="Bluetooth"
crossorigin="anonymous"
referrerpolicy="no-referrer"
src=${brandsUrl(
{
domain: "bluetooth",
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
/>
</div>
</div>
</ha-card>
${
error
? html`<ha-alert alert-type="error" class="content">
${error}
<ha-button
slot="action"
appearance="plain"
@click=${this._loadConfigEntries}
>
${this.hass.localize("ui.common.retry")}
</ha-button>
</ha-alert>`
: html`<ha-card class="content network-status">
<div class="card-content">
<div class="heading">
${
loading
? html`<ha-fade-in .duration=${300} easing="ease-in">
<ha-skeleton
class="status-icon"
role="progressbar"
aria-label=${this.hass.localize("ui.common.loading")}
></ha-skeleton>
</ha-fade-in>`
: html`<div class="icon ${status}">
<ha-svg-icon .path=${statusIcon}></ha-svg-icon>
</div>`
}
<div class="details">
${
loading
? this._renderTextSkeleton()
: this.hass.localize(
`ui.panel.config.bluetooth.status_${status}`
)
}<br />
<small>
${this.hass.localize(
"ui.panel.config.bluetooth.connections_summary",
{ used: usedSlots, total: totalSlots }
)}
</small>
</div>
<img
class="logo"
alt="Bluetooth"
crossorigin="anonymous"
referrerpolicy="no-referrer"
src=${brandsUrl(
{
domain: "bluetooth",
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
/>
</div>
</div>
</ha-card>`
}
<ha-card class="network-card">
<div class="card-header">
@@ -224,10 +272,17 @@ export class BluetoothConfigDashboard extends LitElement {
.path=${mdiAccessPoint}
></ha-svg-icon>
<div slot="headline">
${this.hass.localize(
"ui.panel.config.bluetooth.adapters_count",
{ count: adapterCount }
)}
${
// A link needs its name, so no skeleton while loading
adapterCount === undefined
? this.hass.localize(
"ui.panel.config.bluetooth.adapter_info_title"
)
: this.hass.localize(
"ui.panel.config.bluetooth.adapters_count",
{ count: adapterCount }
)
}
</div>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
@@ -268,6 +323,15 @@ export class BluetoothConfigDashboard extends LitElement {
`;
}
private _renderTextSkeleton() {
return html`<ha-fade-in .duration=${300} easing="ease-in">
<ha-skeleton-text
role="progressbar"
aria-label=${this.hass.localize("ui.common.loading")}
></ha-skeleton-text>
</ha-fade-in>`;
}
static get styles(): CSSResultGroup {
return [
haStyle,
@@ -276,7 +340,9 @@ export class BluetoothConfigDashboard extends LitElement {
padding: var(--ha-space-2) var(--ha-content-gutter) var(--ha-space-4);
}
ha-card {
ha-card,
ha-alert {
display: block;
margin: 0px auto var(--ha-space-4);
max-width: var(--ha-content-width-narrow);
}
@@ -326,6 +392,13 @@ export class BluetoothConfigDashboard extends LitElement {
--icon-color: var(--primary-color);
}
.network-status div.heading .status-icon {
display: block;
width: var(--ha-space-10);
height: var(--ha-space-10);
--ha-skeleton-border-radius: var(--ha-border-radius-2xl);
}
.network-status div.heading .icon.online {
--icon-color: var(--success-color);
}
@@ -14,6 +14,7 @@ import { consume } from "../../../../common/decorators/consume";
import { formatNumberWithUnit } from "../../../../common/number/format_number";
import "../../../../components/chart/ha-chart-base";
import "../../../../components/chart/ha-chart-tooltip-marker";
import { wrapLitTooltipFormatter } from "../../../../components/chart/lit-tooltip-formatter";
import {
formattersContext,
internationalizationContext,
@@ -251,6 +252,23 @@ export class HuiEnergyDevicesGraphCard
<div style="direction:ltr; display: inline;">${value}</div>`;
};
private _renderLabelTooltip = wrapLitTooltipFormatter(
(params: { value: string }) => {
const series = this._chartData[0];
const item = (series?.data as any[] | undefined)?.find(
(d) => d.id === params.value
);
return item
? this._renderTooltip({
name: item.name,
value: item.value,
color: item.itemStyle.color,
seriesName: series.name,
})
: nothing;
}
);
private _createOptions = memoizeOne(
(
data: (BarSeriesOption | PieSeriesOption)[],
@@ -287,6 +305,12 @@ export class HuiEnergyDevicesGraphCard
type: "category",
inverse: true,
triggerEvent: true,
// ECharts types only list `show`, but the label tooltip takes the
// formatter too
tooltip: {
show: true,
formatter: this._renderLabelTooltip,
} as { show: boolean },
// take order from data
data: data[0]?.data?.map((d: any) => d.name),
axisLabel: {
@@ -846,10 +846,8 @@ export class HuiMediaControlCard extends LitElement implements LovelaceCard {
.narrow ha-icon-button[action="media_play"],
.narrow ha-icon-button[action="media_play_pause"],
.narrow
ha-icon-button[action="media_pause"]
.narrow
ha-icon-button[action="media_stop"] {
.narrow ha-icon-button[action="media_pause"],
.narrow ha-icon-button[action="media_stop"] {
--ha-icon-button-size: 50px;
--mdc-icon-size: 36px;
}
+90 -63
View File
@@ -11,6 +11,7 @@ import type {
} from "../../../common/dom/fire_event";
import { computeDomain } from "../../../common/entity/compute_domain";
import parseAspectRatio from "../../../common/util/parse-aspect-ratio";
import "../../../components/camera/ha-camera-placeholder";
import "../../../components/ha-camera-stream";
import type { HaCameraStream } from "../../../components/ha-camera-stream";
import "../../../components/ha-spinner";
@@ -135,6 +136,12 @@ export class HuiImage extends LitElement {
if (this._shouldStartCameraUpdates(oldHass)) {
this._startIntersectionObserver();
} else if (
this._cameraBecameAvailable(oldHass) &&
this._imageVisible &&
this.cameraView !== "live"
) {
this._updateCameraImageSrc();
} else if (!this.hass!.connected) {
this._stopUpdateCameraInterval();
this._stopIntersectionObserver();
@@ -264,6 +271,13 @@ export class HuiImage extends LitElement {
// Snapshots load only once the card is on screen; skip the spinner until then.
const showSpinner = !this.cameraImage || this._imageVisible;
const cameraUnavailable = this._cameraUnavailable();
const placeholderHeight = !useRatio
? this._lastImageHeight
? `${this._lastImageHeight}px`
: "100%"
: undefined;
return html`
<div
style=${styleMap({
@@ -288,71 +302,66 @@ export class HuiImage extends LitElement {
})}"
>
${
this.cameraImage && this.cameraView === "live"
? html`
<ha-camera-stream
muted
.stateObj=${cameraObj}
.fitMode=${this.fitMode}
.aspectRatio=${
this._ratio ? this._ratio.w / this._ratio.h : undefined
}
@load=${this._onVideoLoad}
></ha-camera-stream>
`
: imageSrc === undefined
? nothing
: html`
<img
id="image"
src=${this._reconnectImg ? nothing : live(imageSrc)}
alt=${this.entity || ""}
@error=${this._onImageError}
@load=${this._onImageLoad}
style=${styleMap({
display:
useRatio || this._loadState === LoadState.Loaded
? "block"
: "none",
})}
/>
cameraUnavailable
? nothing
: this.cameraImage && this.cameraView === "live"
? html`
<ha-camera-stream
muted
.stateObj=${cameraObj}
.fitMode=${this.fitMode}
.aspectRatio=${
this._ratio ? this._ratio.w / this._ratio.h : undefined
}
@load=${this._onVideoLoad}
></ha-camera-stream>
`
: imageSrc === undefined
? nothing
: html`
<img
id="image"
src=${this._reconnectImg ? nothing : live(imageSrc)}
alt=${this.entity || ""}
@error=${this._onImageError}
@load=${this._onImageLoad}
style=${styleMap({
display:
useRatio || this._loadState === LoadState.Loaded
? "block"
: "none",
})}
/>
`
}
${
this._loadState === LoadState.Error
? html`<div
id="brokenImage"
style=${styleMap({
height: !useRatio
? this._lastImageHeight
? `${this._lastImageHeight}px`
: "100%"
: undefined,
})}
></div>`
: this.cameraView !== "live" &&
(imageSrc === undefined ||
this._loadState === LoadState.Loading)
this.cameraImage &&
(cameraUnavailable || this._loadState === LoadState.Error)
? html`<ha-camera-placeholder
style=${styleMap({ height: placeholderHeight })}
></ha-camera-placeholder>`
: this._loadState === LoadState.Error
? html`<div
class="progress-container"
style=${styleMap({
height: !useRatio
? this._lastImageHeight
? `${this._lastImageHeight}px`
: "100%"
: undefined,
})}
>
${
showSpinner
? html`<ha-spinner
class="render-spinner"
size="small"
></ha-spinner>`
: nothing
}
</div>`
: ""
id="brokenImage"
style=${styleMap({ height: placeholderHeight })}
></div>`
: this.cameraView !== "live" &&
(imageSrc === undefined ||
this._loadState === LoadState.Loading)
? html`<div
class="progress-container"
style=${styleMap({ height: placeholderHeight })}
>
${
showSpinner
? html`<ha-spinner
class="render-spinner"
size="small"
></ha-spinner>`
: nothing
}
</div>`
: ""
}
</div>
`;
@@ -366,6 +375,18 @@ export class HuiImage extends LitElement {
);
}
private _cameraUnavailable(hass = this.hass): boolean {
return Boolean(
this.cameraImage && hass?.states[this.cameraImage]?.state === UNAVAILABLE
);
}
private _cameraBecameAvailable(oldHass?: HomeAssistant): boolean {
return Boolean(
oldHass && this._cameraUnavailable(oldHass) && !this._cameraUnavailable()
);
}
private _startIntersectionObserver(): void {
if (!this._intersectionObserver) {
this._intersectionObserver = new IntersectionObserver(
@@ -434,7 +455,8 @@ export class HuiImage extends LitElement {
}
private async _updateCameraImageSrc(): Promise<void> {
if (!this.hass || !this.cameraImage) {
// Its picture can't load, a placeholder shows instead
if (!this.hass || !this.cameraImage || this._cameraUnavailable()) {
return;
}
@@ -525,7 +547,8 @@ export class HuiImage extends LitElement {
}
.ratio img,
.ratio div {
.ratio div,
.ratio ha-camera-placeholder {
position: absolute;
top: 0;
left: 0;
@@ -537,6 +560,10 @@ export class HuiImage extends LitElement {
visibility: hidden;
}
ha-camera-placeholder {
background-color: var(--ha-color-fill-neutral-normal-resting);
}
#brokenImage {
background: grey url("/static/images/image-broken.svg") center/36px
no-repeat;
@@ -504,7 +504,7 @@ export class HaGridLayoutSlider extends LitElement {
left 180ms ease-in-out,
bottom 180ms ease-in-out;
--handle-spacing: calc(2 * var(--handle-margin) + var(--handle-size));
--slider-tooltip-margin: 0px;
--slider-tooltip-margin: var(--ha-space-1);
--slider-tooltip-range: 100%;
--slider-tooltip-offset: 0px;
--slider-tooltip-position: calc(
@@ -420,7 +420,7 @@ export class HuiCardLayoutEditor extends LitElement {
}
ha-grid-size-picker {
display: block;
margin: 16px auto;
margin: var(--ha-space-4) auto;
direction: ltr;
}
`,
@@ -138,10 +138,13 @@ export const statusesOfTab = (
tab === "installed" ? INSTALLED_STATUS_ORDER : STATUS_ORDER;
// The filters are kept for every tab. A status picked on another tab that this
// one can't list is left out here, instead of leaving the table empty.
// one can't list is left out here, instead of leaving the table empty. So is
// an integration category nothing on this tab is in, when the ones it lists
// are given. Before the repositories load it lists none, so the URL keeps them.
export const filtersOfTab = (
filters: RepositoryFilters,
tab: MarketplaceTab
tab: MarketplaceTab,
integrationCategories?: readonly string[]
): RepositoryFilters => {
const statuses: readonly string[] = statusesOfTab(tab);
@@ -150,25 +153,31 @@ export const filtersOfTab = (
[STATUS_FILTER]: filters[STATUS_FILTER]?.filter((status) =>
statuses.includes(status)
),
[INTEGRATION_CATEGORY_FILTER]: integrationCategories
? filters[INTEGRATION_CATEGORY_FILTER]?.filter((slug) =>
integrationCategories.includes(slug)
)
: filters[INTEGRATION_CATEGORY_FILTER],
};
};
// The status pane only sends what this tab lists, so statuses picked on another
// tab that this one can't list are kept for when that tab is opened again
// A pane only sends what it lists, so what was picked on another tab that this
// one can't list is kept for when that tab is opened again
export const paneFilterOfTab = (
previous: string[] | undefined,
listed: readonly string[],
picked: string[] = []
): string[] => [
...(previous?.filter((value) => !listed.includes(value)) ?? []),
...picked,
];
export const statusFilterOfTab = (
filters: RepositoryFilters,
tab: MarketplaceTab,
picked: string[] = []
): string[] => {
const statuses: readonly string[] = statusesOfTab(tab);
return [
...(filters[STATUS_FILTER]?.filter(
(status) => !statuses.includes(status)
) ?? []),
...picked,
];
};
picked?: string[]
): string[] =>
paneFilterOfTab(filters[STATUS_FILTER], statusesOfTab(tab), picked);
const matchesFilters = (
repository: RepositoryBase,
@@ -100,6 +100,7 @@ import {
filterRepositories,
filtersOfTab,
marketplaceUpdateEntityIds,
paneFilterOfTab,
skippedUpdateRepositories,
SOURCE_FILTER,
SOURCE_ORDER,
@@ -345,15 +346,7 @@ export class HaMarketplaceDashboard extends LitElement {
}
protected render(): TemplateResult {
const marketplaceRepositories = this._applySkippedUpdates(
this.marketplace.repositories,
this._skippedUpdateRepositories(
this._marketplaceUpdateEntityIds,
this._entities,
this._devices,
this._states ?? {}
)
);
const marketplaceRepositories = this._marketplaceRepositories();
const tabs = this._tabs(
this._i18n.localize,
marketplaceRepositories.filter((repository) => repository.pending_upgrade)
@@ -374,19 +367,22 @@ export class HaMarketplaceDashboard extends LitElement {
</hass-tabs-subpage>`;
}
const filters = this._filtersOfTab(this._filters, this.tab);
const tabRepositories = this._repositoriesOfTab(
marketplaceRepositories,
this.tab
);
const integrationCategoryStates = this._tabIntegrationCategoryStates();
const filters = this._filtersOfTab(
this._filters,
this.tab,
this._stateValues(integrationCategoryStates)
);
const repositories = this._filterRepositories(
this._repositoriesOfTab(marketplaceRepositories, this.tab),
tabRepositories,
this._i18n.localize,
filters
);
const integrationCategoryStates = this._integrationCategoryStates(
this.marketplace.repositories,
this._i18n.localize,
this._integrationCategoryIcons
);
return html`<hass-tabs-subpage-data-table
.tabs=${tabs}
.columns=${this._columns(
@@ -506,7 +502,7 @@ export class HaMarketplaceDashboard extends LitElement {
.label=${this._i18n.localize(
"ui.panel.marketplace.filters.integration_category"
)}
.value=${this._filters[INTEGRATION_CATEGORY_FILTER]}
.value=${filters[INTEGRATION_CATEGORY_FILTER]}
.states=${integrationCategoryStates}
.narrow=${this.narrow}
@data-table-filter-changed=${this._integrationCategoryFilterChanged}
@@ -591,6 +587,18 @@ export class HaMarketplaceDashboard extends LitElement {
private _tabs = memoize(marketplaceTabs);
private _marketplaceRepositories(): MarketplaceRepository[] {
return this._applySkippedUpdates(
this.marketplace.repositories,
this._skippedUpdateRepositories(
this._marketplaceUpdateEntityIds,
this._entities,
this._devices,
this._states ?? {}
)
);
}
private _repositoriesOfTab = memoize(repositoriesOfTab);
private _skippedUpdateRepositories = memoize(skippedUpdateRepositories);
@@ -607,6 +615,10 @@ export class HaMarketplaceDashboard extends LitElement {
private _filtersOfTab = memoize(filtersOfTab);
private _stateValues = memoize((options: { value: string }[]) =>
options.map((option) => option.value)
);
private _columns = memoize(
(
localizeFunc: LocalizeFunc,
@@ -1123,6 +1135,14 @@ export class HaMarketplaceDashboard extends LitElement {
}
);
private _tabIntegrationCategoryStates() {
return this._integrationCategoryStates(
this._repositoriesOfTab(this._marketplaceRepositories(), this.tab),
this._i18n.localize,
this._integrationCategoryIcons
);
}
private _sourceStates = memoize((localize: LocalizeFunc) =>
SOURCE_ORDER.map((source) => ({
value: source,
@@ -1219,15 +1239,24 @@ export class HaMarketplaceDashboard extends LitElement {
private _integrationCategoryFilterChanged(
ev: CustomEvent<{ value: string[] }>
) {
const listed = this._stateValues(this._tabIntegrationCategoryStates());
const filters = {
...this._filters,
[INTEGRATION_CATEGORY_FILTER]: ev.detail.value,
[INTEGRATION_CATEGORY_FILTER]: paneFilterOfTab(
this._filters[INTEGRATION_CATEGORY_FILTER],
listed,
ev.detail.value
),
};
if (this._isUserChange(filters)) {
this._storageFilters = {
...this._storageFilters,
[INTEGRATION_CATEGORY_FILTER]: ev.detail.value,
[INTEGRATION_CATEGORY_FILTER]: paneFilterOfTab(
this._storageFilters[INTEGRATION_CATEGORY_FILTER],
listed,
ev.detail.value
),
};
}
@@ -197,13 +197,12 @@ export class HaMarketplaceRepositoryDashboard extends LitElement {
private _settingPreReleases = new Set<string>();
private _loadingIntegrationCategoryIcons = false;
protected async firstUpdated(
changedProperties: PropertyValues<this>
): Promise<void> {
super.firstUpdated(changedProperties);
getIntegrationCategoryIcons(this._connection.connection).then((icons) => {
this._integrationCategoryIcons = icons;
});
await this._loadRepository();
}
@@ -324,24 +323,29 @@ export class HaMarketplaceRepositoryDashboard extends LitElement {
this._fetchRepository(existing.id);
}
protected willUpdate(changedProps: PropertyValues<this>): void {
protected willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
// The router reuses this element when going from one repository to
// another, the first one is loaded by firstUpdated.
const previousRoute = changedProps.get("route");
const previousRoute = changedProps.get("route") as Route | undefined;
if (
!this.hasUpdated ||
!previousRoute ||
repositoryIdFromRoute(previousRoute) === repositoryIdFromRoute(this.route)
this.hasUpdated &&
previousRoute &&
repositoryIdFromRoute(previousRoute) !== repositoryIdFromRoute(this.route)
) {
return;
this._repository = undefined;
this._error = undefined;
this._refreshError = undefined;
this._loadRepositoryFromRoute();
}
this._repository = undefined;
this._error = undefined;
this._refreshError = undefined;
this._loadRepositoryFromRoute();
if (
changedProps.has("_repository") &&
this._repository?.integration_categories?.length
) {
this._loadIntegrationCategoryIcons();
}
}
protected updated(changedProps: PropertyValues<this>): void {
@@ -396,6 +400,24 @@ export class HaMarketplaceRepositoryDashboard extends LitElement {
}
}
// Only integrations have categories, other repositories don't need them
private async _loadIntegrationCategoryIcons(): Promise<void> {
if (
this._integrationCategoryIcons ||
this._loadingIntegrationCategoryIcons
) {
return;
}
this._loadingIntegrationCategoryIcons = true;
try {
this._integrationCategoryIcons = await getIntegrationCategoryIcons(
this._connection.connection
);
} finally {
this._loadingIntegrationCategoryIcons = false;
}
}
private _loadRepositoryFromRoute(): void {
const repositoryId = repositoryIdFromRoute(this.route);
if (!repositoryId) {
@@ -27,7 +27,6 @@ import {
coverCurrentValue,
coverHasTiltControls,
coverModeAttribute,
coverSupportsPosition,
coverSupportsSetValue,
coverSupportsTiltPosition,
coverTiltOpenness,
@@ -78,6 +77,17 @@ const pillHandle = (cx: number, cy: number, vertical: boolean) =>
const swipeResistance = (distance: number) =>
SWIPE_RESISTANCE * (1 - Math.exp(-Math.max(0, distance) / 30));
const OPEN_CLOSE_FEATURES: Record<
CoverControlMode,
Record<CoverSwipe["action"], CoverEntityFeature>
> = {
position: { open: CoverEntityFeature.OPEN, close: CoverEntityFeature.CLOSE },
tilt: {
open: CoverEntityFeature.OPEN_TILT,
close: CoverEntityFeature.CLOSE_TILT,
},
};
const modeSprings = (): ModeSprings => ({
position: new PercentSpring(),
tilt: new PercentSpring(),
@@ -190,11 +200,11 @@ export class HaStateControlCover extends LitElement {
}
private get _openCloseOnly(): boolean {
const features = OPEN_CLOSE_FEATURES[this.mode];
return (
this.mode === "position" &&
!coverSupportsPosition(this.stateObj) &&
(supportsFeature(this.stateObj, CoverEntityFeature.OPEN) ||
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE))
!this._canSetValue &&
(supportsFeature(this.stateObj, features.open) ||
supportsFeature(this.stateObj, features.close))
);
}
@@ -208,7 +218,9 @@ export class HaStateControlCover extends LitElement {
private get _interactive(): boolean {
return (
this.stateObj.state !== UNAVAILABLE &&
(this._canSetValue || (this._openCloseOnly && !this._valueUnknown))
(this._canSetValue ||
(this._openCloseOnly &&
coverCurrentValue(this.stateObj, this.mode) !== undefined))
);
}
@@ -412,11 +424,7 @@ export class HaStateControlCover extends LitElement {
}
private _swipeAction(): CoverSwipe["action"] {
const end =
this.request?.mode === "position"
? this.request.value
: this._drawingGoal("position");
return end >= 50 ? "close" : "open";
return this._handleGoal(this.mode) >= 50 ? "close" : "open";
}
private _startSwipe(
@@ -424,14 +432,10 @@ export class HaStateControlCover extends LitElement {
shape: CoverShape,
startPointer: number
) {
const mode = this.mode;
const action = this._swipeAction();
const closing = action === "close";
if (
!supportsFeature(
this.stateObj,
closing ? CoverEntityFeature.CLOSE : CoverEntityFeature.OPEN
)
) {
if (!supportsFeature(this.stateObj, OPEN_CLOSE_FEATURES[mode][action])) {
return;
}
const direction = closing ? -1 : 1;
@@ -462,13 +466,13 @@ export class HaStateControlCover extends LitElement {
const passedHalfway = Boolean(this._drag?.swipe?.passedHalfway);
this._setDrag(undefined);
if (passedHalfway) {
fireEvent(this, "cover-command", { mode: "position", action });
fireEvent(this, "cover-command", { mode, action });
}
},
tap: (e) => {
const pointer = this._pointerValue(e, shape);
if (pointer !== undefined && pointer >= 50 !== closing) {
fireEvent(this, "cover-command", { mode: "position", action });
fireEvent(this, "cover-command", { mode, action });
}
},
cancel: () => this._setDrag(undefined),
+21 -3
View File
@@ -28,12 +28,20 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
private _startupToastKey?: string;
private _startupDetailsOpen = false;
private _disconnectedTimeout?: number;
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
// Need to load in advance because when disconnected, can't dynamically load code.
setTimeout(() => import("../managers/notification-manager"), 5000);
this.addEventListener("dialog-closed", (ev) => {
if (ev.detail.dialog === "dialog-startup-progress") {
this._startupDetailsOpen = false;
this._updateStartupProgress();
}
});
}
updated(changedProperties: PropertyValues<this>) {
@@ -135,6 +143,7 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
// Wait until the translations are available.
if (
!this._startupProgressVisible ||
this._startupDetailsOpen ||
!this.hass!.localize("ui.startup_progress.starting")
) {
return;
@@ -163,13 +172,19 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
? {
text: { translationKey: "ui.startup_progress.details" },
icon: mdiInformationOutline,
keepOpen: true,
action: () => showStartupProgressDialog(this),
action: () => this._showStartupDetails(),
}
: undefined,
});
}
// Toasts always show above dialogs, so the toast is hidden while the details are open.
private _showStartupDetails() {
this._startupDetailsOpen = true;
this._startupToastKey = undefined;
showStartupProgressDialog(this);
}
// Keeps the subscription, so the completion toast still reflects late failures.
private _hideStartupProgress() {
this._startupProgressVisible = false;
@@ -193,6 +208,9 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
);
this._hideStartupProgress();
this._unsubscribeBootstrapProgress();
if (this._startupDetailsOpen) {
return;
}
const issues = failed.length;
showToast(this, {
id: SERVER_STARTUP_TOAST_ID,
@@ -205,7 +223,7 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
action: this.hass!.user?.is_admin
? {
text: this.hass!.localize("ui.notification_toast.details"),
action: () => showStartupProgressDialog(this),
action: () => this._showStartupDetails(),
}
: undefined,
});
+23 -6
View File
@@ -1394,9 +1394,10 @@
"reset_zoom": "Reset zoom",
"zoom_hint": "Use {modifier} + scroll to zoom",
"connecting": "Connecting",
"stream_info": "Streaming with {type}. Show connection details",
"stream_info_connecting": "Connecting to the camera. Show connection details",
"stream_info_upgrading": "Streaming with {type}, connecting with {upgrading} in the background. Show connection details"
"live": "Live",
"unavailable": "[%key:state::default::unavailable%]",
"disconnected": "Disconnected",
"show_details": "Show connection details"
},
"web-rtc-player": {
"not_supported": "WebRTC is not supported in this browser.",
@@ -2854,9 +2855,15 @@
"intro": "Home Assistant starts with the connection that works most reliably and switches to a faster one as soon as it is ready.",
"still_images_only": "This camera has no video stream, so it shows a series of still images.",
"fallback_in_use": "The video streams of this camera could not be started, so still images are shown instead.",
"unavailable": "The camera is unavailable, so no stream can start. It connects again as soon as the camera is back.",
"disconnected": {
"home_assistant": "The connection to Home Assistant was lost, so the stream stopped. It starts again as soon as Home Assistant is reachable.",
"stream_failed": "WebRTC could not connect, and this camera has no other stream to fall back to. The player shows what went wrong."
},
"in_use": "In use",
"connecting": "Connecting",
"not_supported_count": "Not supported by this camera ({count})",
"enhanced_by_cloud": "Enhanced by Home Assistant Link",
"description": {
"web_rtc": "Real-time video with the lowest delay, usually below a second. The video takes the most direct way from the camera to your device, which can need extra network setup when you are away from home. Needed to talk to the camera.",
"hls": "The video is sent in short pieces through Home Assistant. It works on almost every network and device, but is a few seconds behind. Used while WebRTC connects, or when WebRTC is not available.",
@@ -3993,7 +4000,8 @@
"location_settings": "Location settings",
"retention_all": "Keep all backups",
"retention_backups": "Keep {count} {count, plural,\n one {backup}\n other {backups}\n}",
"retention_days": "Keep {count} {count, plural,\n one {day}\n other {days}\n}"
"retention_days": "Keep {count} {count, plural,\n one {day}\n other {days}\n}",
"retention_inactive": "Retention paused"
},
"data": {
"ha_settings": "Home Assistant settings",
@@ -4049,7 +4057,7 @@
"retention": "Retention",
"custom_retention": "Custom retention",
"custom_retention_label": "Keep only",
"retention_description": "Based on the maximum number of backups or how many days they should be kept.",
"retention_description": "Based on the maximum number of backups or how many days they should be kept. Only applies to automatic backups, in the locations they are stored in.",
"retention_presets": {
"global": "Use global settings",
"copies_3": "3 backups",
@@ -4324,6 +4332,7 @@
"save_error": "Error saving configuration: {error}",
"retention_for_this_system": "Retention for this system",
"retention_for_location": "Retention for {location}",
"retention_inactive": "Automatic backups aren't stored in this location, so its retention settings are paused. Backups already in this location are kept until you delete them. Retention applies again when you turn the location back on for automatic backups.",
"not_found": "Not found",
"not_found_description": "Location matching ''{backupId}'' not found",
"error": "Could not fetch location details",
@@ -4793,6 +4802,15 @@
"add": "Add",
"dismiss": "Dismiss",
"dismiss_failed": "Couldn't dismiss this meter",
"dismiss_all": "Dismiss all",
"dismiss_all_failed": "Couldn't dismiss these meters",
"show_dismissed": "Show dismissed meters ({count})",
"hide_dismissed": "Hide dismissed meters",
"dismissed": "Dismissed",
"dismissed_title": "Dismissed meters",
"dismissed_sub": "Restore a meter to have it suggested again, or add it right away.",
"restore": "Restore",
"restore_failed": "Couldn't restore this meter",
"load_failed": "Couldn't check for meters that aren't in your energy dashboard yet.",
"slots": {
"grid_import": "Grid consumption",
@@ -7346,7 +7364,6 @@
"description_features": "Access your system away from home. Control your home with Google Home and Alexa.",
"login": {
"title": "Home Assistant Link login",
"landing_title": "[%key:ui::panel::config::cloud::account::onboarding::ha_cloud_title%]",
"hero_title": "Tools for your home, support for the Open Home",
"hero_lead": "The easy, secure, and private way to get more out of Home Assistant, and the simplest way to fund its development.",
"trial_note": "Try free for a month. No payment information required up front.",
+77
View File
@@ -0,0 +1,77 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { HaDialog } from "../../src/components/ha-dialog";
import "../../src/components/ha-dialog";
vi.mock("@home-assistant/webawesome/dist/components/dialog/dialog", () => {
customElements.define("wa-dialog", class extends HTMLElement {});
return {};
});
vi.mock("../../src/components/ha-dialog-header", () => {
customElements.define("ha-dialog-header", class extends HTMLElement {});
return {};
});
vi.mock("../../src/components/ha-icon-button", () => {
customElements.define("ha-icon-button", class extends HTMLElement {});
return {};
});
// Lit counts the test run as a server, so this never gets an observer
vi.mock("@lit-labs/observers/resize-controller", () => ({
ResizeController: class {
observe = vi.fn();
unobserve = vi.fn();
},
}));
let host: HTMLElement | undefined;
afterEach(() => {
host?.remove();
host = undefined;
});
// Shows the dialog the way wa-dialog announces it opened
const showDialog = async (dialog: HaDialog) => {
await dialog.updateComplete;
dialog
.shadowRoot!.querySelector("wa-dialog")!
.dispatchEvent(new Event("wa-show"));
};
describe("ha-dialog", () => {
it("focuses its own autofocus child", async () => {
host = document.createElement("ha-dialog");
host.innerHTML = "<input /><input autofocus />";
document.body.append(host);
await showDialog(host as HaDialog);
await vi.waitFor(() =>
expect(document.activeElement).toBe(host!.querySelector("[autofocus]"))
);
});
it.each([
["slotted in by a wrapper", "<input /><input autofocus />"],
[
"nested in content a wrapper slots in",
"<input /><div><input autofocus /></div>",
],
])("focuses an autofocus element %s", async (_, content) => {
// A wrapper like ha-adaptive-dialog passes its content through a slot
host = document.createElement("div");
host.attachShadow({ mode: "open" }).innerHTML =
"<ha-dialog><slot></slot></ha-dialog>";
host.innerHTML = content;
document.body.append(host);
await showDialog(host.shadowRoot!.querySelector("ha-dialog")!);
await vi.waitFor(() =>
expect(document.activeElement).toBe(host!.querySelector("[autofocus]"))
);
});
});
+57 -1
View File
@@ -1,7 +1,12 @@
import { describe, expect, it } from "vitest";
import type { BluetoothScannerState } from "../../src/data/bluetooth";
import { isScannerStateMismatch } from "../../src/data/bluetooth";
import {
getBluetoothAdapters,
isScannerStateMismatch,
} from "../../src/data/bluetooth";
import type { ConfigEntry } from "../../src/data/config_entries";
import type { DeviceRegistryEntry } from "../../src/data/device/device_registry";
const state = (
overrides: Partial<BluetoothScannerState>
@@ -63,3 +68,54 @@ describe("isScannerStateMismatch", () => {
).toBe(false);
});
});
describe("getBluetoothAdapters", () => {
const entry = (
entry_id: string,
overrides: Partial<ConfigEntry> = {}
): ConfigEntry =>
({
entry_id,
domain: "bluetooth",
source: "user",
disabled_by: null,
...overrides,
}) as ConfigEntry;
const device = (
id: string,
configEntries: string[],
connections: [string, string][] = [["bluetooth", id]]
): DeviceRegistryEntry =>
({
id,
config_entries: configEntries,
connections,
}) as DeviceRegistryEntry;
it("only counts entries with a Bluetooth device as adapters", () => {
const entries = [
entry("proxy"),
entry("ignored", { source: "ignore" }),
entry("removed"),
entry("disabled", { disabled_by: "user" }),
entry("disabled-without-device", { disabled_by: "user" }),
];
const devices = {
proxy: device("proxy", ["esphome", "proxy"]),
disabled: device("disabled", ["disabled"]),
"no-bluetooth": device("no-bluetooth", ["proxy"], [["mac", "x"]]),
other: device("other", ["other-integration"]),
};
const result = getBluetoothAdapters(devices, entries);
expect(result.enabledDevices.map((a) => a.device.id)).toEqual(["proxy"]);
expect(result.disabledDevices.map((a) => a.device.id)).toEqual([
"disabled",
]);
expect(result.disabledEntriesWithoutDevice.map((e) => e.entry_id)).toEqual([
"disabled-without-device",
]);
});
});
+66
View File
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import type { CoverEntity } from "../../src/data/cover";
import { CoverEntityFeature, coverCurrentValue } from "../../src/data/cover";
const TILT_FEATURES =
CoverEntityFeature.OPEN_TILT +
CoverEntityFeature.CLOSE_TILT +
CoverEntityFeature.STOP_TILT;
const cover = (
state: string,
supportedFeatures: number,
attributes: Partial<CoverEntity["attributes"]> = {}
): CoverEntity =>
({
entity_id: "cover.blind",
state,
attributes: { supported_features: supportedFeatures, ...attributes },
}) as CoverEntity;
describe("coverCurrentValue", () => {
it("uses the state for the tilt of a tilt-only cover without a tilt position", () => {
expect(coverCurrentValue(cover("closed", TILT_FEATURES), "tilt")).toBe(0);
expect(coverCurrentValue(cover("opening", TILT_FEATURES), "tilt")).toBe(0);
expect(coverCurrentValue(cover("open", TILT_FEATURES), "tilt")).toBe(100);
expect(coverCurrentValue(cover("closing", TILT_FEATURES), "tilt")).toBe(
100
);
});
it("has no tilt when the state of a tilt-only cover is unknown", () => {
expect(
coverCurrentValue(cover("unknown", TILT_FEATURES), "tilt")
).toBeUndefined();
expect(
coverCurrentValue(cover("unavailable", TILT_FEATURES), "tilt")
).toBeUndefined();
});
it("prefers the reported tilt position", () => {
expect(
coverCurrentValue(
cover("closed", TILT_FEATURES, { current_tilt_position: 30 }),
"tilt"
)
).toBe(30);
});
it("does not use the state for the tilt when the cover also moves up and down", () => {
expect(
coverCurrentValue(
cover("closed", TILT_FEATURES + CoverEntityFeature.OPEN),
"tilt"
)
).toBeUndefined();
});
it("does not use the state for the tilt when the cover can set its tilt position", () => {
expect(
coverCurrentValue(
cover("closed", TILT_FEATURES + CoverEntityFeature.SET_TILT_POSITION),
"tilt"
)
).toBeUndefined();
});
});
+105
View File
@@ -2839,6 +2839,111 @@ describe("computeEnergyDeviceLabels", () => {
);
});
});
describe("devices that share a name", () => {
const LIGHT_STATES = {
"sensor.hall_light_energy": createMockEntityState(
"sensor.hall_light_energy",
"1",
{ friendly_name: "Ceiling light Energy" }
),
"sensor.stairs_light_energy": createMockEntityState(
"sensor.stairs_light_energy",
"1",
{ friendly_name: "Ceiling light Energy" }
),
"sensor.hall_light_total": createMockEntityState(
"sensor.hall_light_total",
"1",
{ friendly_name: "Ceiling light Total energy" }
),
};
const lightHass = createMockHass(LIGHT_STATES, {
entities: {
"sensor.hall_light_energy": {
entity_id: "sensor.hall_light_energy",
labels: [],
name: "Energy",
device_id: "hall",
},
"sensor.stairs_light_energy": {
entity_id: "sensor.stairs_light_energy",
labels: [],
name: "Energy",
device_id: "stairs",
},
"sensor.hall_light_total": {
entity_id: "sensor.hall_light_total",
labels: [],
name: "Total energy",
device_id: "hall",
},
} as unknown as Record<string, EntityRegistryDisplayEntry>,
devices: {
hall: { id: "hall", name: "Ceiling light", name_by_user: null },
stairs: { id: "stairs", name: "Ceiling light", name_by_user: null },
} as unknown as Record<string, DeviceRegistryEntry>,
});
it("leaves devices that only share a name alone", () => {
assert.deepEqual(
computeEnergyDeviceLabels(
lightHass.states,
lightHass.formatEntityName,
[
{ stat_consumption: "sensor.hall_light_energy" },
{ stat_consumption: "sensor.stairs_light_energy" },
]
),
{
"sensor.hall_light_energy": "Ceiling light",
"sensor.stairs_light_energy": "Ceiling light",
}
);
});
it("adds the entity names when one of them has several meters", () => {
assert.deepEqual(
computeEnergyDeviceLabels(
lightHass.states,
lightHass.formatEntityName,
[
{ stat_consumption: "sensor.hall_light_energy" },
{ stat_consumption: "sensor.stairs_light_energy" },
{ stat_consumption: "sensor.hall_light_total" },
]
),
{
"sensor.hall_light_energy": "Ceiling light Energy",
"sensor.stairs_light_energy": "Ceiling light Energy",
"sensor.hall_light_total": "Ceiling light Total energy",
}
);
});
it("adds the entity names when a custom name takes the same label", () => {
assert.deepEqual(
computeEnergyDeviceLabels(
lightHass.states,
lightHass.formatEntityName,
[
{ stat_consumption: "sensor.hall_light_energy" },
{ stat_consumption: "sensor.stairs_light_energy" },
{
stat_consumption: "sensor.hall_light_total",
name: "Ceiling light",
},
]
),
{
"sensor.hall_light_energy": "Ceiling light Energy",
"sensor.stairs_light_energy": "Ceiling light Energy",
"sensor.hall_light_total": "Ceiling light",
}
);
});
});
});
describe("computeConsumptionData with a home meter", () => {
+12 -3
View File
@@ -10,6 +10,7 @@ import {
import type { EnergySuggestionInput } from "../../src/data/energy_suggestions";
import {
computeEnergySuggestions,
restoreDismissedSuggestion,
updateDismissedSuggestions,
} from "../../src/data/energy_suggestions";
import type { StatisticsMetaData } from "../../src/data/recorder";
@@ -216,17 +217,25 @@ describe("computeEnergySuggestions", () => {
});
describe("updateDismissedSuggestions", () => {
it("adds the statistic and drops statistics that no longer exist", () => {
it("adds the statistics and drops statistics that no longer exist", () => {
expect(
updateDismissedSuggestions(
["sensor.removed", "sensor.kept", "sensor.new"],
"sensor.new",
["sensor.new", "sensor.other"],
[
statistic("sensor.kept"),
statistic("sensor.new"),
statistic("sensor.other"),
]
)
).toEqual(["sensor.kept", "sensor.new"]);
).toEqual(["sensor.kept", "sensor.new", "sensor.other"]);
});
});
describe("restoreDismissedSuggestion", () => {
it("removes only the restored statistic", () => {
expect(
restoreDismissedSuggestion(["sensor.a", "sensor.b"], "sensor.a")
).toEqual(["sensor.b"]);
});
});
@@ -10,6 +10,7 @@ import {
browseUrl,
filterRepositories,
filtersOfTab,
paneFilterOfTab,
marketplaceUpdateEntityIds,
skippedUpdateRepositories,
statusesOfTab,
@@ -284,13 +285,6 @@ describe("browseLinkFromUrl", () => {
});
});
it("filters on no integration category for an empty one", () => {
expect(
browseLinkFromUrl("?integration_category=")?.filters
.integration_category ?? []
).toEqual([]);
});
it("keeps what was picked for a link that says nothing about browsing", () => {
expect(
browseLinkFromUrl("?owner=hacs&repository=integration")
@@ -299,11 +293,31 @@ describe("browseLinkFromUrl", () => {
});
describe("filtersOfTab", () => {
it("keeps the integration category on every tab", () => {
it("leaves out an integration category nothing on the tab is in", () => {
const filters = { integration_category: ["energy", "energy.solar"] };
expect(
filtersOfTab({ integration_category: ["energy"] }, "installed")
.integration_category
filtersOfTab(filters, "installed", ["energy"]).integration_category
).toEqual(["energy"]);
expect(filtersOfTab(filters, "installed", []).integration_category).toEqual(
[]
);
// Without the ones the tab lists, as before the repositories load
expect(filtersOfTab(filters, "installed").integration_category).toEqual(
filters.integration_category
);
});
it("keeps an integration category picked on browse when the installed pane changes", () => {
const picked = ["energy.solar", "climate"];
expect(
paneFilterOfTab(picked, ["climate", "lighting"], ["lighting"])
).toEqual(["energy.solar", "lighting"]);
// The pane's clear button sends no value
expect(paneFilterOfTab(picked, ["climate"], undefined)).toEqual([
"energy.solar",
]);
});
it("only offers statuses something installed can have on the installed tab", () => {
+55
View File
@@ -274,6 +274,61 @@ it("shows what to discover on the discover tab, not the table", async () => {
).not.toBeNull();
});
it("offers the integration categories of the tab, leaving out one picked on another", async () => {
window.history.replaceState(
null,
"",
"/marketplace/browse?integration_category=energy"
);
const dashboard = await openDashboard([
{
id: "1",
name: "One",
category: "integration",
installed: true,
integration_categories: ["climate"],
},
{
id: "2",
name: "Two",
category: "integration",
installed: false,
integration_categories: ["energy"],
},
]);
window.history.replaceState(null, "", "/");
const table = () =>
dashboard.shadowRoot!.querySelector(
"hass-tabs-subpage-data-table"
) as unknown as { data: { id: string }[]; filters: number };
const categoryFilter = () =>
dashboard.shadowRoot!.querySelectorAll(
"ha-filter-states"
)[3] as unknown as {
value?: string[];
states: { value: string }[];
};
expect(table().data.map((repository) => repository.id)).toEqual(["2"]);
dashboard.tab = "installed";
await dashboard.updateComplete;
expect(categoryFilter().states.map((state) => state.value)).toEqual([
"climate",
]);
expect(categoryFilter().value).toEqual([]);
expect(table().filters).toBe(0);
expect(table().data.map((repository) => repository.id)).toEqual(["1"]);
dashboard.tab = "browse";
await dashboard.updateComplete;
expect(categoryFilter().value).toEqual(["energy"]);
dashboard.remove();
sessionStorage.clear();
});
it("browses the way the link says", async () => {
window.history.replaceState(
null,
@@ -11,6 +11,8 @@ import { provideHass } from "../../../src/fake_data/provide_hass";
import { deferred } from "./dialog-host";
import { markdownWithRepositoryContext } from "../../../src/panels/marketplace/tools/markdown";
import type * as MarkdownModule from "../../../src/panels/marketplace/tools/markdown";
import { getIntegrationCategoryIcons } from "../../../src/data/icons";
import type * as IconsModule from "../../../src/data/icons";
// The real components need more browser than jsdom has, the page only hands
// them properties.
@@ -39,6 +41,10 @@ vi.mock(
};
}
);
vi.mock("../../../src/data/icons", async (importOriginal) => ({
...(await importOriginal<typeof IconsModule>()),
getIntegrationCategoryIcons: vi.fn(async () => ({})),
}));
vi.mock("../../../src/components/chips/ha-assist-chip", () =>
stubElement("ha-assist-chip")
);
@@ -212,6 +218,30 @@ describe("ha-marketplace-repository-dashboard", () => {
expect(getInternals(page)._repository.id).toBe("2");
});
it("loads the category icons once, only for repositories with categories", async () => {
const { page } = await openRepositoryPage(
async (repositoryId) =>
repositoryInfo(
repositoryId,
repositoryId === "theme"
? { category: "theme" }
: { category: "integration", integration_categories: ["energy"] }
),
repositoryRoute("theme")
);
await settle(page);
expect(getIntegrationCategoryIcons).not.toHaveBeenCalled();
page.route = repositoryRoute("1");
await settle(page);
page.route = repositoryRoute("2");
await settle(page);
page.reloadRepository();
await settle(page);
expect(getIntegrationCategoryIcons).toHaveBeenCalledTimes(1);
});
it("clears the error of the previous repository", async () => {
const { page } = await openRepositoryPage(async (repositoryId) => {
if (repositoryId === "1") {