mirror of
https://github.com/home-assistant/frontend.git
synced 2026-12-02 17:50:19 +00:00
Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff8790b796 | ||
|
|
0512959140 | ||
|
|
cab8a642eb | ||
|
|
11122efc45 | ||
|
|
1d81e9db8b | ||
|
|
f46d7815f3 | ||
|
|
5d138d57a6 | ||
|
|
cc2c29f647 | ||
|
|
b088c25052 | ||
|
|
78aaa5849a | ||
|
|
ec2aa13888 | ||
|
|
d27dee64f7 | ||
|
|
4fbaf8c0a8 | ||
|
|
e8d660029d | ||
|
|
67598310a6 | ||
|
|
e6f71722b0 | ||
|
|
f22a17046c | ||
|
|
12cfde2aef | ||
|
|
1285f9c908 | ||
|
|
cc650ec6ba | ||
|
|
1a755e7f53 | ||
|
|
7715ab71fd | ||
|
|
5303f30323 | ||
|
|
35124e73cf | ||
|
|
7ded8288a2 | ||
|
|
583900211b | ||
|
|
80451833b0 | ||
|
|
7350465df1 | ||
|
|
304020eb5b | ||
|
|
57d73d236f | ||
|
|
336259f6d2 | ||
|
|
1882e154fe | ||
|
|
baa067caf0 | ||
|
|
07b5d9e98c | ||
|
|
f2b2c92bdd | ||
|
|
33ef19dac1 | ||
|
|
1e797c345c | ||
|
|
9083641ae7 | ||
|
|
5fc4ad4e0c | ||
|
|
ba33d2897b | ||
|
|
9484d51694 | ||
|
|
55739f2666 | ||
|
|
483b8d1c76 |
No files matched your search
@@ -198,10 +198,7 @@ async function fetchTranslations(currentArtifact: Artifact | null) {
|
||||
console.log("Unpacking downloaded translations...");
|
||||
const zip = await jszip.loadAsync(downloadResponse.data as ArrayBuffer);
|
||||
await deleteCurrent;
|
||||
const extractStream = zip.file(/.*/)[0].nodeStream().pipe(extract());
|
||||
await new Promise((resolve, reject) => {
|
||||
extractStream.on("close", resolve).on("error", reject);
|
||||
});
|
||||
await extract({ input: await zip.file(/.*/)[0].async("uint8array") });
|
||||
|
||||
// Record the artifact only after successful extraction, so a failed fetch
|
||||
// is retried by the next build instead of being considered current.
|
||||
|
||||
@@ -69,10 +69,6 @@ async function copyMapPanel(staticDir) {
|
||||
npmPath("leaflet/dist/leaflet.css"),
|
||||
staticPath("images/leaflet/")
|
||||
);
|
||||
copyFileDir(
|
||||
npmPath("leaflet.markercluster/dist/MarkerCluster.css"),
|
||||
staticPath("images/leaflet/")
|
||||
);
|
||||
fs.copySync(
|
||||
npmPath("leaflet/dist/images"),
|
||||
staticPath("images/leaflet/images/")
|
||||
|
||||
@@ -462,6 +462,14 @@ const SCHEMAS: {
|
||||
},
|
||||
},
|
||||
},
|
||||
select_search: {
|
||||
name: "Select (more than 12 options)",
|
||||
selector: {
|
||||
select: {
|
||||
options: Array.from({ length: 20 }, (_, i) => `Option ${i + 1}`),
|
||||
},
|
||||
},
|
||||
},
|
||||
select_disabled_list: {
|
||||
name: "Select disabled option",
|
||||
selector: {
|
||||
@@ -632,6 +640,10 @@ const SCHEMAS: {
|
||||
},
|
||||
language: { name: "Language", selector: { language: {} } },
|
||||
navigation: { name: "Navigation", selector: { navigation: {} } },
|
||||
ui_condition: {
|
||||
name: "Dashboard conditions",
|
||||
selector: { ui_condition: {} },
|
||||
},
|
||||
numeric_threshold: {
|
||||
name: "Numeric threshold",
|
||||
selector: { numeric_threshold: {} },
|
||||
|
||||
+9
-10
@@ -40,7 +40,7 @@
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "8.1.3",
|
||||
"@babel/runtime": "8.1.4",
|
||||
"@braintree/sanitize-url": "7.1.2",
|
||||
"@codemirror/autocomplete": "6.20.4",
|
||||
"@codemirror/commands": "6.11.2",
|
||||
@@ -105,7 +105,7 @@
|
||||
"intl-messageformat": "12.2.1",
|
||||
"js-yaml": "5.5.0",
|
||||
"leaflet": "1.9.4",
|
||||
"leaflet.markercluster": "1.5.3",
|
||||
"leaflet.markercluster": "2.0.0",
|
||||
"lit": "3.3.3",
|
||||
"lit-html": "3.3.3",
|
||||
"maplibre-gl": "6.20.0",
|
||||
@@ -136,13 +136,13 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ampproject/remapping": "2.3.0",
|
||||
"@babel/core": "8.1.3",
|
||||
"@babel/core": "8.1.4",
|
||||
"@babel/helper-compilation-targets": "8.0.7",
|
||||
"@babel/helper-define-polyfill-provider": "1.0.0",
|
||||
"@babel/plugin-transform-class-properties": "8.0.1",
|
||||
"@babel/plugin-transform-private-methods": "8.0.1",
|
||||
"@babel/plugin-transform-runtime": "8.1.2",
|
||||
"@babel/preset-env": "8.0.7",
|
||||
"@babel/preset-env": "8.1.4",
|
||||
"@bundle-stats/plugin-webpack-filter": "4.23.1",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@gfx/zopfli": "1.0.15",
|
||||
@@ -154,7 +154,7 @@
|
||||
"@playwright/test": "1.65.1",
|
||||
"@rsdoctor/rspack-plugin": "1.6.5",
|
||||
"@rspack/core": "2.3.4",
|
||||
"@rspack/dev-server": "2.2.2",
|
||||
"@rspack/dev-server": "2.2.3",
|
||||
"@types/babel__plugin-transform-runtime": "7.9.5",
|
||||
"@types/chromecast-caf-receiver": "7.0.1",
|
||||
"@types/chromecast-caf-sender": "1.0.11",
|
||||
@@ -168,7 +168,6 @@
|
||||
"@types/node": "24.19.4",
|
||||
"@types/qrcode": "1.5.6",
|
||||
"@types/sortablejs": "1.15.9",
|
||||
"@types/tar": "7.0.87",
|
||||
"@typescript/native": "npm:[email protected]",
|
||||
"@vitest/coverage-v8": "5.1.2",
|
||||
"babel-loader": "10.1.1",
|
||||
@@ -177,7 +176,7 @@
|
||||
"browserslist-useragent-regexp": "4.1.4",
|
||||
"core-js-compat": "3.51.0",
|
||||
"del": "9.0.1",
|
||||
"eslint": "10.15.0",
|
||||
"eslint": "10.16.0",
|
||||
"eslint-config-prettier": "10.1.9",
|
||||
"eslint-import-resolver-webpack": "0.13.11",
|
||||
"eslint-plugin-import-x": "4.18.1",
|
||||
@@ -199,7 +198,7 @@
|
||||
"jszip": "3.10.2",
|
||||
"license-checker-rseidelsohn": "5.0.1",
|
||||
"lightningcss": "1.33.0",
|
||||
"lint-staged": "17.6.2",
|
||||
"lint-staged": "17.6.3",
|
||||
"lit-analyzer": "2.0.3",
|
||||
"lodash.merge": "4.6.2",
|
||||
"lodash.template": "4.18.1",
|
||||
@@ -210,7 +209,7 @@
|
||||
"rspack-manifest-plugin": "5.2.2",
|
||||
"serve": "14.2.8",
|
||||
"sinon": "22.1.0",
|
||||
"tar": "7.5.24",
|
||||
"tar": "8.0.2",
|
||||
"terser-webpack-plugin": "5.6.1",
|
||||
"ts-lit-plugin": "2.0.2",
|
||||
"typescript": "6.0.3",
|
||||
@@ -222,7 +221,7 @@
|
||||
"webpackbar": "7.0.0",
|
||||
"workbox-build": "7.4.1"
|
||||
},
|
||||
"packageManager": "[email protected]3.0",
|
||||
"packageManager": "[email protected]4.0",
|
||||
"volta": {
|
||||
"node": "24.22.3"
|
||||
}
|
||||
|
||||
Generated
+550
-560
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,74 @@
|
||||
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
|
||||
import type {
|
||||
ConditionContext,
|
||||
VisibilityCondition,
|
||||
} from "../../panels/lovelace/common/validate-condition";
|
||||
import { addEntityToCondition } from "../../panels/lovelace/common/validate-condition";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import type { ConditionEvaluation } from "../controllers/condition-evaluator-controller";
|
||||
import { ConditionEvaluatorController } from "../controllers/condition-evaluator-controller";
|
||||
import { dropInvalidConditions } from "./sanitize";
|
||||
|
||||
export interface VisibilitySubscription {
|
||||
/** Pass each new hass object so client-side conditions check again. */
|
||||
update(hass: HomeAssistant): void;
|
||||
/** Close the subscriptions. `onChange` is not called again. */
|
||||
unsubscribe(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live visibility of a list of dashboard visibility conditions, for code
|
||||
* without a Lit host, such as custom cards and plugins. Conditions core
|
||||
* evaluates are subscribed to; the rest are checked locally. Reports
|
||||
* `unknown` until core replies.
|
||||
*/
|
||||
export const subscribeVisibility = (
|
||||
hass: HomeAssistant,
|
||||
conditions: VisibilityCondition[],
|
||||
onChange: (result: ConditionEvaluation, error?: string) => void,
|
||||
context: ConditionContext = {}
|
||||
): VisibilitySubscription => {
|
||||
// The controller only needs a host to register with and to re-render.
|
||||
const host: ReactiveControllerHost = {
|
||||
addController: () => undefined,
|
||||
removeController: () => undefined,
|
||||
requestUpdate: () => undefined,
|
||||
updateComplete: Promise.resolve(true),
|
||||
};
|
||||
|
||||
let active = true;
|
||||
|
||||
const controller = new ConditionEvaluatorController(host, {
|
||||
resubscribeDelay: 0,
|
||||
onResult: (result, error) => {
|
||||
if (active) {
|
||||
onChange(result, error);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const sanitized = dropInvalidConditions(conditions);
|
||||
const { entity_id: entityId } = context;
|
||||
|
||||
// Core-evaluated conditions never see the context, so fold its entity in
|
||||
// first, as the dashboard mixin does.
|
||||
const validConditions = entityId
|
||||
? sanitized.map((condition) => addEntityToCondition(condition, entityId))
|
||||
: sanitized;
|
||||
const getContext = () => context;
|
||||
|
||||
controller.hostConnected();
|
||||
controller.observe(validConditions, hass, getContext);
|
||||
|
||||
return {
|
||||
update: (newHass) => {
|
||||
if (active) {
|
||||
controller.observe(validConditions, newHass, getContext);
|
||||
}
|
||||
},
|
||||
unsubscribe: () => {
|
||||
active = false;
|
||||
controller.hostDisconnected();
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* How long after the full screen button the companion apps hide the page for
|
||||
* the change, and after that how long they keep it hidden. A later hide ends
|
||||
* streams as usual.
|
||||
*/
|
||||
export const FULLSCREEN_ENTER_TIME = 1000;
|
||||
|
||||
let enterStart = 0;
|
||||
|
||||
let enterId = 0;
|
||||
|
||||
// The last entering each stream let a hidden page through for
|
||||
const claimedEnters = new WeakMap<object, number>();
|
||||
|
||||
/**
|
||||
* Marks that the full screen button was pressed to enter full screen. The
|
||||
* companion apps hide the page for a moment then, which shouldn't end a
|
||||
* stream. Leaving full screen isn't marked, so locking the phone or leaving
|
||||
* the app right after it always ends the streams.
|
||||
*/
|
||||
export const startEnteringFullscreen = () => {
|
||||
enterId++;
|
||||
enterStart = Date.now();
|
||||
};
|
||||
|
||||
/** Ends it early, like when the browser denies full screen. */
|
||||
export const cancelEnteringFullscreen = () => {
|
||||
enterStart = 0;
|
||||
};
|
||||
|
||||
export const isEnteringFullscreen = () =>
|
||||
Date.now() - enterStart < FULLSCREEN_ENTER_TIME;
|
||||
|
||||
/**
|
||||
* Whether the page is hidden by entering full screen, which hides it only
|
||||
* once. Any later hiding is the user leaving, so each stream gets true only
|
||||
* once per entering.
|
||||
*/
|
||||
export const claimFullscreenEnterHide = (stream: object): boolean => {
|
||||
if (!isEnteringFullscreen() || claimedEnters.get(stream) === enterId) {
|
||||
return false;
|
||||
}
|
||||
claimedEnters.set(stream, enterId);
|
||||
// Counts from here, so the video still plays on when the page shows again
|
||||
enterStart = Date.now();
|
||||
return true;
|
||||
};
|
||||
@@ -31,8 +31,6 @@ export const setupLeafletMap = async (
|
||||
const Leaflet = (await import("leaflet")).default as LeafletModuleType;
|
||||
Leaflet.Icon.Default.imagePath = "/static/images/leaflet/images/";
|
||||
|
||||
await import("leaflet.markercluster");
|
||||
|
||||
const map = Leaflet.map(mapElement, {
|
||||
minZoom: MAP_MIN_ZOOM,
|
||||
maxZoom: MAP_MAX_ZOOM,
|
||||
@@ -43,14 +41,6 @@ export const setupLeafletMap = async (
|
||||
style.setAttribute("rel", "stylesheet");
|
||||
mapElement.parentNode.appendChild(style);
|
||||
|
||||
const markerClusterStyle = document.createElement("link");
|
||||
markerClusterStyle.setAttribute(
|
||||
"href",
|
||||
"/static/images/leaflet/MarkerCluster.css"
|
||||
);
|
||||
markerClusterStyle.setAttribute("rel", "stylesheet");
|
||||
mapElement.parentNode.appendChild(markerClusterStyle);
|
||||
|
||||
if (initialView) {
|
||||
map.setView(
|
||||
[initialView.latitude, initialView.longitude],
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
/// <reference types="leaflet.markercluster" />
|
||||
import type {
|
||||
CircleMarker,
|
||||
Control,
|
||||
DivIcon,
|
||||
Map,
|
||||
MarkerCluster,
|
||||
MarkerClusterGroup,
|
||||
MarkerClusterGroupOptions,
|
||||
Polyline,
|
||||
} from "leaflet";
|
||||
import type { LeafletModuleType } from "../../dom/setup-leaflet-map";
|
||||
@@ -36,8 +39,18 @@ interface HandledMarker extends DecoratedMarker {
|
||||
|
||||
interface LeafletMarkerHandle extends MapMarkerHandle {
|
||||
marker: HandledMarker;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
// v2 option the 1.x types don't know yet
|
||||
interface ClusterGroupOptions extends MarkerClusterGroupOptions {
|
||||
clusterLabel?(cluster: MarkerCluster): string;
|
||||
}
|
||||
|
||||
// Stands in for getAnimations on browsers without it (Chrome before 84),
|
||||
// which markercluster calls whenever the map zooms
|
||||
const noAnimations = (): Animation[] => [];
|
||||
|
||||
/** The Leaflet engine: raster viewing fallback without WebGL2, no editing */
|
||||
export class LeafletMapEngine implements MapEngine {
|
||||
/** For the ha-map jsdom tests only */
|
||||
@@ -49,10 +62,14 @@ export class LeafletMapEngine implements MapEngine {
|
||||
|
||||
private _clusterable: HandledMarker[] = [];
|
||||
|
||||
private _MarkerClusterGroup?: typeof MarkerClusterGroup;
|
||||
|
||||
private _cluster?: MarkerClusterGroup;
|
||||
|
||||
private _clusterOptions: MapClusterOptions | null = null;
|
||||
|
||||
private _animateClusters = true;
|
||||
|
||||
private _scaleControl?: Control.Scale;
|
||||
|
||||
public async init(
|
||||
@@ -66,22 +83,26 @@ export class LeafletMapEngine implements MapEngine {
|
||||
// eslint-disable-next-line
|
||||
const Leaflet = (await import("leaflet")).default as LeafletModuleType;
|
||||
Leaflet.Icon.Default.imagePath = "/static/images/leaflet/images/";
|
||||
await import("leaflet.markercluster");
|
||||
// The package's own types are for Leaflet 2; on our Leaflet 1.9,
|
||||
// @types/leaflet.markercluster describes it
|
||||
this._MarkerClusterGroup = (await import("leaflet.markercluster"))
|
||||
.MarkerClusterGroup as unknown as typeof MarkerClusterGroup;
|
||||
// Without a native getAnimations, markercluster can't cancel the
|
||||
// animations a zoom interrupts, so clusters don't animate there
|
||||
this._animateClusters =
|
||||
"getAnimations" in Element.prototype &&
|
||||
Element.prototype.getAnimations !== noAnimations;
|
||||
Element.prototype.getAnimations ??= noAnimations;
|
||||
|
||||
const map = Leaflet.map(container, {
|
||||
minZoom: MAP_MIN_ZOOM,
|
||||
maxZoom: MAP_MAX_ZOOM,
|
||||
});
|
||||
map.attributionControl.setPrefix("");
|
||||
for (const href of [
|
||||
"/static/images/leaflet/leaflet.css",
|
||||
"/static/images/leaflet/MarkerCluster.css",
|
||||
]) {
|
||||
const style = document.createElement("link");
|
||||
style.setAttribute("href", href);
|
||||
style.setAttribute("rel", "stylesheet");
|
||||
root.appendChild(style);
|
||||
}
|
||||
const style = document.createElement("link");
|
||||
style.setAttribute("href", "/static/images/leaflet/leaflet.css");
|
||||
style.setAttribute("rel", "stylesheet");
|
||||
root.appendChild(style);
|
||||
map.setView(options.center, options.zoom);
|
||||
|
||||
// The base layer adds itself; a vector layer may still fall back to raster
|
||||
@@ -257,6 +278,7 @@ export class LeafletMapEngine implements MapEngine {
|
||||
const handle: LeafletMarkerHandle = {
|
||||
marker,
|
||||
location,
|
||||
title: options.title,
|
||||
clusterData: options.clusterData,
|
||||
remove: () => {
|
||||
this._cluster?.removeLayer(marker);
|
||||
@@ -345,18 +367,27 @@ export class LeafletMapEngine implements MapEngine {
|
||||
this._cluster = undefined;
|
||||
}
|
||||
this._clusterOptions = options;
|
||||
if (!this.leafletMap || !this.Leaflet) {
|
||||
|
||||
if (!this.leafletMap || !this.Leaflet || !this._MarkerClusterGroup) {
|
||||
return;
|
||||
}
|
||||
if (!options) {
|
||||
this._clusterable.forEach((marker) => marker.addTo(this.leafletMap!));
|
||||
return;
|
||||
}
|
||||
|
||||
// markercluster groups by proximity only; groupKey is not supported here
|
||||
this._cluster = this.Leaflet.markerClusterGroup({
|
||||
const clusterOptions: ClusterGroupOptions = {
|
||||
showCoverageOnHover: false,
|
||||
removeOutsideVisibleBounds: false,
|
||||
animate: this._animateClusters,
|
||||
maxClusterRadius: options.radius,
|
||||
// The members' names, as the MapLibre engine labels its clusters
|
||||
clusterLabel: (cluster) =>
|
||||
(cluster.getAllChildMarkers() as HandledMarker[])
|
||||
.map((marker) => marker.engineHandle?.title)
|
||||
.filter(Boolean)
|
||||
.join(", "),
|
||||
iconCreateFunction: (cluster) => {
|
||||
const build = () => {
|
||||
const members = (cluster.getAllChildMarkers() as HandledMarker[]).map(
|
||||
@@ -397,7 +428,9 @@ export class LeafletMapEngine implements MapEngine {
|
||||
createShadow: () => null,
|
||||
} as unknown as DivIcon;
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
this._cluster = new this._MarkerClusterGroup(clusterOptions);
|
||||
this._cluster.addLayers(this._clusterable);
|
||||
this.leafletMap!.addLayer(this._cluster!);
|
||||
}
|
||||
|
||||
@@ -108,9 +108,32 @@ const addAtmosphere = (style: StyleSpecification): StyleSpecification => ({
|
||||
sky: { ...style.sky, "atmosphere-blend": ATMOSPHERE_BLEND },
|
||||
});
|
||||
|
||||
// MapLibre keeps the globe until it blends into mercator between zoom 11 and
|
||||
// 12, but unbuffered ocean polygons leave hairline gaps between tiles on it
|
||||
// from about zoom 6. Flatten it earlier, between zoom 5 and 6.
|
||||
const GLOBE_FLATTEN_ZOOM = 5;
|
||||
|
||||
const flattenGlobeEarly = (style: StyleSpecification): StyleSpecification =>
|
||||
style.projection?.type === "globe"
|
||||
? {
|
||||
...style,
|
||||
projection: {
|
||||
type: [
|
||||
"interpolate",
|
||||
["linear"],
|
||||
["zoom"],
|
||||
GLOBE_FLATTEN_ZOOM,
|
||||
"vertical-perspective",
|
||||
GLOBE_FLATTEN_ZOOM + 1,
|
||||
"mercator",
|
||||
],
|
||||
},
|
||||
}
|
||||
: style;
|
||||
|
||||
/** Everything a freshly built style needs before it is handed to MapLibre */
|
||||
export const finalizeMapStyle = (
|
||||
name: string,
|
||||
style: StyleSpecification
|
||||
): StyleSpecification =>
|
||||
addAtmosphere(addLatinLabels(useTileJson(name, style)));
|
||||
flattenGlobeEarly(addAtmosphere(addLatinLabels(useTileJson(name, style))));
|
||||
@@ -17,12 +17,21 @@ import { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
import { storage } from "../../common/decorators/storage";
|
||||
import { deepActiveElement } from "../../common/dom/deep-active-element";
|
||||
import { fireEvent, type HASSDomEvent } from "../../common/dom/fire_event";
|
||||
import {
|
||||
cancelEnteringFullscreen,
|
||||
isEnteringFullscreen,
|
||||
startEnteringFullscreen,
|
||||
} from "../../common/dom/entering-fullscreen";
|
||||
import { ctrlOrCmdLabel } from "../../common/keyboard/ctrl-or-cmd";
|
||||
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 { isExternal } from "../../data/external";
|
||||
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";
|
||||
@@ -108,6 +117,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;
|
||||
@@ -137,6 +148,10 @@ export class HaCameraPlayer extends LitElement {
|
||||
// full screen player
|
||||
@state() private _paused = false;
|
||||
|
||||
// Playing when its button entered full screen, so a pause meanwhile is the
|
||||
// companion app's
|
||||
private _playingBeforeFullscreen = false;
|
||||
|
||||
@query("ha-camera-stream") private _stream?: HaCameraStream;
|
||||
|
||||
@query(".player") private _player?: HTMLElement;
|
||||
@@ -163,6 +178,16 @@ export class HaCameraPlayer extends LitElement {
|
||||
|
||||
private _controlsTimeout?: number;
|
||||
|
||||
// A pointer type or "keyboard", as hover sticks after a tap on touch
|
||||
// screens and focus moved by a script can look like keyboard focus
|
||||
private _lastInput?: string;
|
||||
|
||||
// Captured, as dialogs stop the propagation of their key presses
|
||||
private _inputChanged = (ev: KeyboardEvent | PointerEvent) => {
|
||||
this._lastInput =
|
||||
ev.type === "keydown" ? "keyboard" : (ev as PointerEvent).pointerType;
|
||||
};
|
||||
|
||||
private _wheelHintTimeout?: number;
|
||||
|
||||
private _videoRequest = 0;
|
||||
@@ -190,7 +215,7 @@ export class HaCameraPlayer extends LitElement {
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
document.addEventListener("visibilitychange", this._requestWakeLock);
|
||||
document.addEventListener("visibilitychange", this._visibilityChanged);
|
||||
// The first update requests it, once keep-awake is set
|
||||
if (this.hasUpdated) {
|
||||
this._requestWakeLock();
|
||||
@@ -200,19 +225,28 @@ export class HaCameraPlayer extends LitElement {
|
||||
"webkitfullscreenchange",
|
||||
this._fullscreenChanged
|
||||
);
|
||||
const inputOptions = { capture: true, passive: true };
|
||||
document.addEventListener("keydown", this._inputChanged, inputOptions);
|
||||
document.addEventListener("pointerdown", this._inputChanged, inputOptions);
|
||||
if (this._controlsVisible) {
|
||||
this._scheduleHideControls();
|
||||
}
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
document.removeEventListener("visibilitychange", this._requestWakeLock);
|
||||
document.removeEventListener("visibilitychange", this._visibilityChanged);
|
||||
this._releaseWakeLock();
|
||||
document.removeEventListener("fullscreenchange", this._fullscreenChanged);
|
||||
document.removeEventListener(
|
||||
"webkitfullscreenchange",
|
||||
this._fullscreenChanged
|
||||
);
|
||||
document.removeEventListener("keydown", this._inputChanged, true);
|
||||
document.removeEventListener("pointerdown", this._inputChanged, true);
|
||||
clearTimeout(this._controlsTimeout);
|
||||
clearTimeout(this._wheelHintTimeout);
|
||||
this._streamInfoCallbacks.clear();
|
||||
this._unbindVideo(this._video);
|
||||
this._video = undefined;
|
||||
this._pointers.clear();
|
||||
@@ -252,6 +286,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() {
|
||||
@@ -475,6 +513,11 @@ export class HaCameraPlayer extends LitElement {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private _visibilityChanged = () => {
|
||||
this._requestWakeLock();
|
||||
this._resumeAfterEnteringFullscreen();
|
||||
};
|
||||
|
||||
/**
|
||||
* Browsers release the lock when the page is hidden, so it is requested
|
||||
* again whenever the page shows.
|
||||
@@ -523,9 +566,10 @@ export class HaCameraPlayer extends LitElement {
|
||||
this._controlsTimeout = window.setTimeout(() => {
|
||||
this._controlsTimeout = undefined;
|
||||
if (
|
||||
this._overlay?.querySelector(
|
||||
".control:hover, ha-camera-stream-badge:hover"
|
||||
) ||
|
||||
(this._lastInput === "mouse" &&
|
||||
this._overlay?.querySelector(
|
||||
".control:hover, ha-camera-stream-badge:hover"
|
||||
)) ||
|
||||
this._hasKeyboardFocus()
|
||||
) {
|
||||
this._scheduleHideControls();
|
||||
@@ -537,6 +581,7 @@ export class HaCameraPlayer extends LitElement {
|
||||
|
||||
private _hasKeyboardFocus(): boolean {
|
||||
return Boolean(
|
||||
this._lastInput === "keyboard" &&
|
||||
this.shadowRoot &&
|
||||
deepActiveElement(this.shadowRoot)?.matches(":focus-visible")
|
||||
);
|
||||
@@ -602,10 +647,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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -694,6 +755,7 @@ export class HaCameraPlayer extends LitElement {
|
||||
this._paused = Boolean(
|
||||
video?.paused && (video.srcObject || video.currentSrc)
|
||||
);
|
||||
this._resumeAfterEnteringFullscreen();
|
||||
};
|
||||
|
||||
private _toggleMute() {
|
||||
@@ -745,16 +807,27 @@ export class HaCameraPlayer extends LitElement {
|
||||
("webkitFullscreenElement" in document
|
||||
? (document.webkitFullscreenElement as Element | null)
|
||||
: null);
|
||||
const fullscreen = Boolean(
|
||||
this._fullscreen = Boolean(
|
||||
this._player && fullscreenElement === this._player
|
||||
);
|
||||
if (fullscreen !== this._fullscreen) {
|
||||
this._fullscreen = fullscreen;
|
||||
// The size changes, so the zoomed in area would be off
|
||||
this._zoom = ZOOM_PAN_IDENTITY;
|
||||
}
|
||||
this._resumeAfterEnteringFullscreen();
|
||||
};
|
||||
|
||||
// The companion apps pause the video while entering full screen
|
||||
private _resumeAfterEnteringFullscreen() {
|
||||
if (
|
||||
isExternal &&
|
||||
this._playingBeforeFullscreen &&
|
||||
this._paused &&
|
||||
document.visibilityState === "visible" &&
|
||||
isEnteringFullscreen()
|
||||
) {
|
||||
// Only once, so a pause in the iPhone's own full screen controls stays
|
||||
this._playingBeforeFullscreen = false;
|
||||
this._ensurePlaying();
|
||||
}
|
||||
}
|
||||
|
||||
private async _toggleFullscreen() {
|
||||
const player = this._player;
|
||||
if (!player) {
|
||||
@@ -769,6 +842,10 @@ export class HaCameraPlayer extends LitElement {
|
||||
}
|
||||
return;
|
||||
}
|
||||
this._playingBeforeFullscreen = Boolean(
|
||||
this._video && !this._video.paused
|
||||
);
|
||||
startEnteringFullscreen();
|
||||
if (player.requestFullscreen) {
|
||||
await player.requestFullscreen();
|
||||
} else if ("webkitRequestFullscreen" in player) {
|
||||
@@ -782,6 +859,7 @@ export class HaCameraPlayer extends LitElement {
|
||||
}
|
||||
} catch (_err: unknown) {
|
||||
// Denied by the browser
|
||||
cancelEnteringFullscreen();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -930,6 +1008,10 @@ export class HaCameraPlayer extends LitElement {
|
||||
|
||||
private _pointerMove(ev: PointerEvent) {
|
||||
if (ev.pointerType === "mouse" && !this._pointers.size) {
|
||||
// A click changes it, so the control focused with the keyboard stays
|
||||
if (!this._hasKeyboardFocus()) {
|
||||
this._lastInput = "mouse";
|
||||
}
|
||||
this._showControls();
|
||||
}
|
||||
const pointer = this._pointers.get(ev.pointerId);
|
||||
|
||||
@@ -327,7 +327,7 @@ export class HaCodeEditor extends ReactiveElement {
|
||||
transactions.push({
|
||||
effects: [
|
||||
this._loadedCodeMirror!.readonlyCompartment!.reconfigure(
|
||||
this._loadedCodeMirror!.EditorView!.editable.of(!this.readOnly)
|
||||
this._readOnlyExtensions()
|
||||
),
|
||||
this._loadedCodeMirror!.yamlLintCompartment!.reconfigure(
|
||||
this.lint && !this.readOnly
|
||||
@@ -452,9 +452,7 @@ export class HaCodeEditor extends ReactiveElement {
|
||||
this._loadedCodeMirror.haSyntaxHighlighting,
|
||||
this._loadedCodeMirror.yamlScalarHighlighter,
|
||||
this._loadedCodeMirror.yamlScalarHighlightStyle,
|
||||
this._loadedCodeMirror.readonlyCompartment.of(
|
||||
this._loadedCodeMirror.EditorView.editable.of(!this.readOnly)
|
||||
),
|
||||
this._loadedCodeMirror.readonlyCompartment.of(this._readOnlyExtensions()),
|
||||
this._loadedCodeMirror.linewrapCompartment.of(
|
||||
this.linewrap ? this._loadedCodeMirror.EditorView.lineWrapping : []
|
||||
),
|
||||
@@ -523,6 +521,20 @@ export class HaCodeEditor extends ReactiveElement {
|
||||
}
|
||||
}
|
||||
|
||||
private _readOnlyExtensions(): Extension {
|
||||
const cm = this._loadedCodeMirror!;
|
||||
if (!this.readOnly) {
|
||||
return cm.EditorView.editable.of(true);
|
||||
}
|
||||
return [
|
||||
cm.EditorView.editable.of(false),
|
||||
// Keeps commands like Tab from changing the content once it has focus
|
||||
cm.EditorState.readOnly.of(true),
|
||||
// Focusable, so the content can be scrolled with the keyboard
|
||||
cm.EditorView.contentAttributes.of({ tabindex: "0" }),
|
||||
];
|
||||
}
|
||||
|
||||
private _fullscreenLabel(): string {
|
||||
if (this._isFullscreen) {
|
||||
return (
|
||||
@@ -1939,6 +1951,10 @@ export class HaCodeEditor extends ReactiveElement {
|
||||
padding-top: var(--code-editor-toolbar-height);
|
||||
}
|
||||
|
||||
:host(.fullscreen) {
|
||||
--code-mirror-min-height: 100%;
|
||||
}
|
||||
|
||||
:host(.fullscreen) .cm-editor {
|
||||
height: 100% !important;
|
||||
max-height: 100% !important;
|
||||
|
||||
@@ -73,6 +73,15 @@ export class HaDropdown extends Dropdown {
|
||||
// @ts-ignore
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
private override async showMenu() {
|
||||
// Flip away from the safe areas instead of opening into them, where the
|
||||
// max-height below would squeeze the menu.
|
||||
const styles = getComputedStyle(this);
|
||||
// @ts-ignore flipPadding is typed as a number, floating-ui accepts sides
|
||||
this.popup.flipPadding = {
|
||||
top: parseFloat(styles.getPropertyValue("--safe-area-inset-top")) || 0,
|
||||
bottom:
|
||||
parseFloat(styles.getPropertyValue("--safe-area-inset-bottom")) || 0,
|
||||
};
|
||||
// @ts-ignore
|
||||
await super.showMenu();
|
||||
const triggerElement = this.getTrigger();
|
||||
|
||||
@@ -82,7 +82,9 @@ const SELECTOR_FALLBACK_VALUES = {
|
||||
},
|
||||
ui_action: undefined,
|
||||
ui_clock_date_format: undefined,
|
||||
ui_clock_time_format: undefined,
|
||||
ui_color: undefined,
|
||||
ui_condition: undefined,
|
||||
ui_state_content: undefined,
|
||||
ui_time_format: undefined,
|
||||
unit_of_measurement: undefined,
|
||||
|
||||
@@ -117,7 +117,9 @@ const SELECTOR_INITIAL_VALUES = {
|
||||
},
|
||||
ui_action: undefined,
|
||||
ui_clock_date_format: undefined,
|
||||
ui_clock_time_format: undefined,
|
||||
ui_color: undefined,
|
||||
ui_condition: () => [],
|
||||
ui_state_content: undefined,
|
||||
ui_time_format: undefined,
|
||||
unit_of_measurement: undefined,
|
||||
|
||||
@@ -9,6 +9,10 @@ import { consume } from "../common/decorators/consume";
|
||||
import { isComponentLoaded } from "../common/config/is_component_loaded";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import {
|
||||
claimFullscreenEnterHide,
|
||||
FULLSCREEN_ENTER_TIME,
|
||||
} from "../common/dom/entering-fullscreen";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { nextRender } from "../common/util/render-status";
|
||||
import { fetchStreamUrl } from "../data/camera";
|
||||
@@ -101,16 +105,19 @@ export class HaHLSPlayer extends LitElement {
|
||||
return;
|
||||
}
|
||||
if (document.hidden) {
|
||||
if (isExternal) {
|
||||
if (isExternal && !claimFullscreenEnterHide(this)) {
|
||||
// The companion apps pause JavaScript timers while in the background,
|
||||
// so a delayed clean up would not run until the app is opened again
|
||||
this._cleanUp();
|
||||
return;
|
||||
}
|
||||
this._hiddenCleanupTimeout = window.setTimeout(() => {
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
this._cleanUp();
|
||||
}, HIDDEN_CLEANUP_DELAY);
|
||||
this._hiddenCleanupTimeout = window.setTimeout(
|
||||
() => {
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
this._cleanUp();
|
||||
},
|
||||
isExternal ? FULLSCREEN_ENTER_TIME : HIDDEN_CLEANUP_DELAY
|
||||
);
|
||||
} else if (this._hiddenCleanupTimeout) {
|
||||
// stream was not cleaned up yet, just cancel the cleanup
|
||||
clearTimeout(this._hiddenCleanupTimeout);
|
||||
|
||||
@@ -26,6 +26,20 @@ import "../ha-svg-icon";
|
||||
import "../radio/ha-radio-group";
|
||||
import "../radio/ha-radio-option";
|
||||
|
||||
const SEARCH_MIN_OPTIONS = 12;
|
||||
|
||||
const SEARCH_KEYS = [{ name: "primary", weight: 1 }];
|
||||
|
||||
// Every value gets the prefix, so "" has a non-empty ID and no value can
|
||||
// collide with another value's ID.
|
||||
const PICKER_ID_PREFIX = "option:";
|
||||
|
||||
export const toPickerId = (value: string | number) =>
|
||||
`${PICKER_ID_PREFIX}${value}`;
|
||||
|
||||
export const findPickerOption = (options: SelectOption[], id?: string) =>
|
||||
options.find((option) => toPickerId(option.value) === id);
|
||||
|
||||
@customElement("ha-selector-select")
|
||||
export class HaSelectSelector extends LitElement {
|
||||
@state()
|
||||
@@ -256,6 +270,23 @@ export class HaSelectSelector extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
if (options.length > SEARCH_MIN_OPTIONS) {
|
||||
return html`
|
||||
<ha-generic-picker
|
||||
no-sort
|
||||
.label=${this.label}
|
||||
.helper=${this.helper}
|
||||
.disabled=${this.disabled}
|
||||
.required=${this.required}
|
||||
.getItems=${this._getSearchItems(options)}
|
||||
.value=${this._pickerValue(options)}
|
||||
.valueRenderer=${this._valueRenderer(options)}
|
||||
.searchKeys=${SEARCH_KEYS}
|
||||
@value-changed=${this._searchPickerChanged}
|
||||
></ha-generic-picker>
|
||||
`;
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-select
|
||||
.label=${this.label ?? ""}
|
||||
@@ -310,6 +341,37 @@ export class HaSelectSelector extends LitElement {
|
||||
}
|
||||
);
|
||||
|
||||
private _getSearchItems = memoizeOne(
|
||||
(options: SelectOption[]) => () =>
|
||||
options.map((option) => ({
|
||||
id: toPickerId(option.value),
|
||||
primary: option.label,
|
||||
sorting_label: option.label,
|
||||
disabled: option.disabled,
|
||||
}))
|
||||
);
|
||||
|
||||
private _pickerValue(options: SelectOption[]): string | undefined {
|
||||
const value = this.value as string | number | undefined;
|
||||
if (typeof value !== "string" && typeof value !== "number") {
|
||||
return undefined;
|
||||
}
|
||||
if (value === "" && !options.some((option) => option.value === "")) {
|
||||
return undefined;
|
||||
}
|
||||
return toPickerId(value);
|
||||
}
|
||||
|
||||
private _valueRenderer = memoizeOne(
|
||||
(options: SelectOption[]) => (id: string) =>
|
||||
html`<span slot="headline"
|
||||
>${
|
||||
findPickerOption(options, id)?.label ??
|
||||
id.slice(PICKER_ID_PREFIX.length)
|
||||
}</span
|
||||
>`
|
||||
);
|
||||
|
||||
private get _mode(): "list" | "dropdown" | "box" {
|
||||
return (
|
||||
this.selector.select?.mode ||
|
||||
@@ -384,6 +446,36 @@ export class HaSelectSelector extends LitElement {
|
||||
});
|
||||
}
|
||||
|
||||
private _searchPickerChanged(ev: CustomEvent): void {
|
||||
ev.stopPropagation();
|
||||
|
||||
if (this.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const id: string | undefined = ev.detail.value;
|
||||
|
||||
if (id === undefined) {
|
||||
if (this.value !== undefined) {
|
||||
fireEvent(this, "value-changed", { value: undefined });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Look the pick up in the current options: the open list can be older.
|
||||
const option = findPickerOption(this._getOptions(this.selector), id);
|
||||
|
||||
if (
|
||||
!option ||
|
||||
option.disabled ||
|
||||
(this.value != null && String(option.value) === String(this.value))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
fireEvent(this, "value-changed", { value: option.value });
|
||||
}
|
||||
|
||||
private _comboBoxValueChanged(ev: CustomEvent): void {
|
||||
ev.stopPropagation();
|
||||
const newValue = ev.detail.value;
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import { useAmPm } from "../../common/datetime/use_am_pm";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { internationalizationContext } from "../../data/context";
|
||||
import type { UiClockTimeFormatSelector } from "../../data/selector";
|
||||
import type { FrontendLocaleData } from "../../data/translation";
|
||||
import { TimeFormat } from "../../data/translation";
|
||||
import "../ha-select";
|
||||
import type { HaSelectOption, HaSelectSelectEvent } from "../ha-select";
|
||||
|
||||
type ClockTimeFormatOption = TimeFormat | "auto";
|
||||
|
||||
const CLOCK_TIME_FORMAT_OPTIONS: ClockTimeFormatOption[] = [
|
||||
"auto",
|
||||
...Object.values(TimeFormat),
|
||||
];
|
||||
|
||||
// 9:30 PM or 21:30, to show what each format looks like
|
||||
const EXAMPLE_TIME = new Date(2000, 0, 1, 21, 30);
|
||||
|
||||
const formatExample = (locale: FrontendLocaleData, timeFormat?: TimeFormat) => {
|
||||
const formatLocale = timeFormat
|
||||
? { ...locale, time_format: timeFormat }
|
||||
: locale;
|
||||
|
||||
return new Intl.DateTimeFormat(locale.language, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
hourCycle: useAmPm(formatLocale) ? "h12" : "h23",
|
||||
}).format(EXAMPLE_TIME);
|
||||
};
|
||||
|
||||
@customElement("ha-selector-ui_clock_time_format")
|
||||
export class HaSelectorUiClockTimeFormat extends LitElement {
|
||||
@property({ attribute: false }) public selector!: UiClockTimeFormatSelector;
|
||||
|
||||
@property() public value?: TimeFormat;
|
||||
|
||||
@property() public label?: string;
|
||||
|
||||
@property() public helper?: string;
|
||||
|
||||
@property({ type: Boolean }) public disabled = false;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: ContextType<typeof internationalizationContext>;
|
||||
|
||||
private _options = memoizeOne(
|
||||
(i18n: ContextType<typeof internationalizationContext>): HaSelectOption[] =>
|
||||
CLOCK_TIME_FORMAT_OPTIONS.map((value) => ({
|
||||
value,
|
||||
label:
|
||||
value === "auto"
|
||||
? i18n.localize("ui.components.clock-time-format-picker.auto")
|
||||
: i18n.localize(
|
||||
`ui.components.clock-time-format-picker.formats.${value}`
|
||||
),
|
||||
secondary: formatExample(
|
||||
i18n.locale,
|
||||
value === "auto" ? undefined : value
|
||||
),
|
||||
}))
|
||||
);
|
||||
|
||||
protected render() {
|
||||
return html`
|
||||
<ha-select
|
||||
.label=${this.label}
|
||||
.helper=${this.helper}
|
||||
.value=${this.value ?? "auto"}
|
||||
.options=${this._options(this._i18n)}
|
||||
.disabled=${this.disabled}
|
||||
@selected=${this._selected}
|
||||
></ha-select>
|
||||
`;
|
||||
}
|
||||
|
||||
private _selected(ev: HaSelectSelectEvent<ClockTimeFormatOption>): void {
|
||||
ev.stopPropagation();
|
||||
|
||||
const value = ev.detail.value;
|
||||
|
||||
fireEvent(this, "value-changed", {
|
||||
value: value === "auto" ? undefined : value,
|
||||
});
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
ha-select {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-selector-ui_clock_time_format": HaSelectorUiClockTimeFormat;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import type { UiConditionSelector } from "../../data/selector";
|
||||
import "../../panels/lovelace/editor/conditions/ha-card-conditions-editor";
|
||||
import type { VisibilityCondition } from "../../panels/lovelace/common/validate-condition";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
|
||||
@customElement("ha-selector-ui_condition")
|
||||
export class HaUiConditionSelector extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false })
|
||||
public selector!: UiConditionSelector;
|
||||
|
||||
@property({ attribute: false }) public value?: VisibilityCondition[];
|
||||
|
||||
@property() public label?: string;
|
||||
|
||||
@property({ type: Boolean }) public disabled = false;
|
||||
|
||||
protected firstUpdated() {
|
||||
// The editor's labels come from the dashboard translations, which only
|
||||
// load with a dashboard; this selector can show anywhere.
|
||||
this.hass.loadFragmentTranslation("lovelace");
|
||||
}
|
||||
|
||||
protected render() {
|
||||
return html`
|
||||
${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
<ha-card-conditions-editor
|
||||
.hass=${this.hass}
|
||||
.conditions=${this.value ?? []}
|
||||
.disabled=${this.disabled}
|
||||
></ha-card-conditions-editor>
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: var(--ha-space-1);
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-selector-ui_condition": HaUiConditionSelector;
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,9 @@ const LOAD_ELEMENTS = {
|
||||
color_temp: () => import("./ha-selector-color-temp"),
|
||||
ui_action: () => import("./ha-selector-ui-action"),
|
||||
ui_clock_date_format: () => import("./ha-selector-ui-clock-date-format"),
|
||||
ui_clock_time_format: () => import("./ha-selector-ui-clock-time-format"),
|
||||
ui_color: () => import("./ha-selector-ui-color"),
|
||||
ui_condition: () => import("./ha-selector-ui-condition"),
|
||||
ui_state_content: () => import("./ha-selector-ui-state-content"),
|
||||
ui_time_format: () => import("./ha-selector-ui-time-format"),
|
||||
unit_of_measurement: () => import("./ha-selector-unit-of-measurement"),
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
getPanelIcon,
|
||||
getPanelIconPath,
|
||||
getPanelTitle,
|
||||
getSelectedPanelUrlPath,
|
||||
} from "../data/panel";
|
||||
import type { PersistentNotification } from "../data/persistent_notification";
|
||||
import { subscribeNotifications } from "../data/persistent_notification";
|
||||
@@ -231,12 +232,36 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const selectedPanel = this.hass.panelUrl;
|
||||
|
||||
// prettier-ignore
|
||||
return html`
|
||||
${this._renderHeader()}
|
||||
${this._renderAllPanels(selectedPanel)}`;
|
||||
${this._renderAllPanels()}`;
|
||||
}
|
||||
|
||||
private _computeSidebarPanels(): [PanelInfo[], PanelInfo[]] | undefined {
|
||||
if (!this._panelOrder || !this._hiddenPanels) {
|
||||
return undefined;
|
||||
}
|
||||
return computePanels(
|
||||
this.hass.panels,
|
||||
getDefaultPanelUrlPath(this.hass),
|
||||
this._panelOrder,
|
||||
this._hiddenPanels,
|
||||
this.hass.locale
|
||||
);
|
||||
}
|
||||
|
||||
private _computeSelectedPanel(
|
||||
sidebarPanels: [PanelInfo[], PanelInfo[]] | undefined,
|
||||
route: Route | undefined
|
||||
): string {
|
||||
if (!route) {
|
||||
return this.hass.panelUrl;
|
||||
}
|
||||
const urlPaths = (sidebarPanels ?? [[], []])
|
||||
.flat()
|
||||
.map((panel) => panel.url_path);
|
||||
return getSelectedPanelUrlPath(urlPaths, route.path);
|
||||
}
|
||||
|
||||
protected shouldUpdate(changedProps: PropertyValues): boolean {
|
||||
@@ -254,7 +279,20 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (!this.hass || !changedProps.has("hass")) {
|
||||
if (!this.hass) {
|
||||
return false;
|
||||
}
|
||||
if (changedProps.has("route")) {
|
||||
const sidebarPanels = this._computeSidebarPanels();
|
||||
const oldRoute = changedProps.get("route") as Route | undefined;
|
||||
if (
|
||||
this._computeSelectedPanel(sidebarPanels, oldRoute) !==
|
||||
this._computeSelectedPanel(sidebarPanels, this.route)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (!changedProps.has("hass")) {
|
||||
return false;
|
||||
}
|
||||
const oldHass = changedProps.get("hass") as HomeAssistant;
|
||||
@@ -355,7 +393,9 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private _renderAllPanels(selectedPanel: string) {
|
||||
private _renderAllPanels() {
|
||||
const sidebarPanels = this._computeSidebarPanels();
|
||||
const selectedPanel = this._computeSelectedPanel(sidebarPanels, this.route);
|
||||
const renderList = (content, cls: string, scrollable: boolean) =>
|
||||
html`<ha-list-nav
|
||||
class=${classMap({
|
||||
@@ -365,7 +405,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
>${content}</ha-list-nav
|
||||
>`;
|
||||
|
||||
if (!this._panelOrder || !this._hiddenPanels) {
|
||||
if (!sidebarPanels) {
|
||||
return html`<div class="panels-list">
|
||||
<div class="wrapper">
|
||||
${renderList(
|
||||
@@ -390,15 +430,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
const defaultPanel = getDefaultPanelUrlPath(this.hass);
|
||||
|
||||
const [beforeSpacer, afterSpacer] = computePanels(
|
||||
this.hass.panels,
|
||||
defaultPanel,
|
||||
this._panelOrder,
|
||||
this._hiddenPanels,
|
||||
this.hass.locale
|
||||
);
|
||||
const [beforeSpacer, afterSpacer] = sidebarPanels;
|
||||
|
||||
// prettier-ignore
|
||||
return html`<div class="panels-list">
|
||||
|
||||
@@ -8,6 +8,10 @@ import { styleMap } from "lit/directives/style-map";
|
||||
import { consume } from "../common/decorators/consume";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import {
|
||||
claimFullscreenEnterHide,
|
||||
FULLSCREEN_ENTER_TIME,
|
||||
} from "../common/dom/entering-fullscreen";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import {
|
||||
addWebRtcCandidate,
|
||||
@@ -242,16 +246,19 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
return;
|
||||
}
|
||||
if (document.hidden) {
|
||||
if (isExternal) {
|
||||
if (isExternal && !claimFullscreenEnterHide(this)) {
|
||||
// The companion apps pause JavaScript timers while in the background,
|
||||
// so a delayed clean up would not run until the app is opened again
|
||||
this._cleanUp();
|
||||
return;
|
||||
}
|
||||
this._hiddenCleanupTimeout = window.setTimeout(() => {
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
this._cleanUp();
|
||||
}, HIDDEN_CLEANUP_DELAY);
|
||||
this._hiddenCleanupTimeout = window.setTimeout(
|
||||
() => {
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
this._cleanUp();
|
||||
},
|
||||
isExternal ? FULLSCREEN_ENTER_TIME : HIDDEN_CLEANUP_DELAY
|
||||
);
|
||||
} else if (this._hiddenCleanupTimeout) {
|
||||
// stream was not cleaned up yet, just cancel the cleanup
|
||||
clearTimeout(this._hiddenCleanupTimeout);
|
||||
|
||||
@@ -4,9 +4,8 @@ export const setDateTimeValue = (
|
||||
callService: HomeAssistantApi["callService"],
|
||||
entityId: string,
|
||||
datetime: Date
|
||||
) => {
|
||||
) =>
|
||||
callService("datetime", "set_value", {
|
||||
entity_id: entityId,
|
||||
datetime: datetime.toISOString(),
|
||||
});
|
||||
};
|
||||
@@ -2591,6 +2591,9 @@ export const formatFlowRateShort = (
|
||||
|
||||
export type WaterGasResource = "water" | "gas";
|
||||
|
||||
/** The device categories the device graphs can show. */
|
||||
export type DeviceConsumptionResource = "electricity" | "gas";
|
||||
|
||||
export const getWaterGasDevicesKey = (resource: WaterGasResource) =>
|
||||
`device_consumption_${resource}` as const;
|
||||
|
||||
|
||||
@@ -38,7 +38,8 @@ export const setInputDateTimeValue = (
|
||||
date: string | undefined = undefined
|
||||
) => {
|
||||
const param = { entity_id: entityId, time, date };
|
||||
callService("input_datetime", "set_datetime", param);
|
||||
|
||||
return callService("input_datetime", "set_datetime", param);
|
||||
};
|
||||
|
||||
export const fetchInputDateTime = (hass: HomeAssistant) =>
|
||||
|
||||
@@ -196,6 +196,21 @@ export const getPanelIconPath = (panel: PanelInfo): string | undefined => {
|
||||
|
||||
export const FIXED_PANELS = [PROFILE_PANEL, "config", NOT_FOUND_PANEL];
|
||||
|
||||
// A panel's url_path can span several segments (e.g. "config/logs"), so the
|
||||
// most specific url_path matching the path wins over its first segment.
|
||||
export const getSelectedPanelUrlPath = (
|
||||
urlPaths: string[],
|
||||
path: string
|
||||
): string =>
|
||||
urlPaths.reduce(
|
||||
(selected, urlPath) =>
|
||||
urlPath.length > selected.length &&
|
||||
(path === `/${urlPath}` || path.startsWith(`/${urlPath}/`))
|
||||
? urlPath
|
||||
: selected,
|
||||
path.split("/")[1] ?? ""
|
||||
);
|
||||
|
||||
export interface PanelMutableParams {
|
||||
title?: string | null;
|
||||
icon?: string | null;
|
||||
|
||||
@@ -88,7 +88,9 @@ export type Selector =
|
||||
| SerialPortSelector
|
||||
| UiActionSelector
|
||||
| UiClockDateFormatSelector
|
||||
| UiClockTimeFormatSelector
|
||||
| UiColorSelector
|
||||
| UiConditionSelector
|
||||
| UiStateContentSelector
|
||||
| UiTimeFormatSelector
|
||||
| UnitOfMeasurementSelector
|
||||
@@ -203,6 +205,11 @@ export interface ConditionSelector {
|
||||
} | null;
|
||||
}
|
||||
|
||||
/** Dashboard conditions, edited like a card's visibility tab. */
|
||||
export interface UiConditionSelector {
|
||||
ui_condition: {} | null;
|
||||
}
|
||||
|
||||
export interface ConversationAgentSelector {
|
||||
conversation_agent: { language?: string } | null;
|
||||
}
|
||||
@@ -307,6 +314,7 @@ export interface EntitySelectorFilter {
|
||||
device_class?: string | readonly string[];
|
||||
supported_features?: number | [number];
|
||||
unit_of_measurement?: string | readonly string[];
|
||||
capabilities?: Record<string, readonly (string | readonly string[])[]>;
|
||||
}
|
||||
|
||||
interface EntitySelectorEntityFilter extends EntitySelectorFilter {
|
||||
@@ -662,6 +670,11 @@ export interface UiClockDateFormatSelector {
|
||||
ui_clock_date_format: {} | null;
|
||||
}
|
||||
|
||||
// 12 or 24 hour clock, as a TimeFormat. Undefined follows the user's setting.
|
||||
export interface UiClockTimeFormatSelector {
|
||||
ui_clock_time_format: {} | null;
|
||||
}
|
||||
|
||||
export interface UiColorExtraOption {
|
||||
value: string;
|
||||
label: string;
|
||||
@@ -1112,6 +1125,26 @@ export const filterSelectorDevices = (
|
||||
return true;
|
||||
};
|
||||
|
||||
const matchesCapabilities = (
|
||||
entity: HassEntity,
|
||||
capabilities: NonNullable<EntitySelectorFilter["capabilities"]>
|
||||
): boolean => {
|
||||
for (const [capability, alternatives] of Object.entries(capabilities)) {
|
||||
const value = entity.attributes[capability];
|
||||
if (value == null) {
|
||||
return false;
|
||||
}
|
||||
const entityValues: unknown[] = Array.isArray(value) ? value : [value];
|
||||
const matches = alternatives.some((required) =>
|
||||
ensureArray(required).every((item) => entityValues.includes(item))
|
||||
);
|
||||
if (!matches) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
export const filterSelectorEntities = (
|
||||
filterEntity: EntitySelectorEntityFilter,
|
||||
entity: HassEntity,
|
||||
@@ -1125,6 +1158,7 @@ export const filterSelectorEntities = (
|
||||
device_class: filterDeviceClass,
|
||||
supported_features: filterSupportedFeature,
|
||||
unit_of_measurement: filterUnitOfMeasurement,
|
||||
capabilities: filterCapabilities,
|
||||
integration: filterIntegration,
|
||||
device: filterDevice,
|
||||
} = filterEntity;
|
||||
@@ -1173,6 +1207,10 @@ export const filterSelectorEntities = (
|
||||
}
|
||||
}
|
||||
|
||||
if (filterCapabilities && !matchesCapabilities(entity, filterCapabilities)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (filterDevice) {
|
||||
if (!entityRegistry || !devices) {
|
||||
return false;
|
||||
@@ -1279,6 +1317,7 @@ export const computeCreateDomains = (
|
||||
!entityFilter.integration &&
|
||||
!entityFilter.device_class &&
|
||||
!entityFilter.supported_features &&
|
||||
!entityFilter.capabilities &&
|
||||
!entityFilter.device &&
|
||||
entityFilter.domain
|
||||
? ensureArray(entityFilter.domain).filter((domain) =>
|
||||
|
||||
+2
-1
@@ -6,5 +6,6 @@ export const setTimeValue = (
|
||||
time: string | undefined = undefined
|
||||
) => {
|
||||
const param = { entity_id: entityId, time: time };
|
||||
callService("time", "set_value", param);
|
||||
|
||||
return callService("time", "set_value", param);
|
||||
};
|
||||
@@ -28,7 +28,10 @@ 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 }[] = [
|
||||
@@ -53,6 +56,23 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
|
||||
|
||||
@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();
|
||||
}
|
||||
@@ -74,10 +94,10 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
|
||||
}
|
||||
|
||||
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
|
||||
@@ -161,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`
|
||||
|
||||
@@ -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,5 +1,6 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { HassConfig, UnsubscribeFunc } from "home-assistant-js-websocket";
|
||||
import { ERR_CONNECTION_LOST } from "home-assistant-js-websocket";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
@@ -456,6 +457,11 @@ class MoreInfoUpdate extends LitElement {
|
||||
false
|
||||
);
|
||||
} catch (err: any) {
|
||||
// The update keeps running when the connection drops during a long install.
|
||||
if (err?.error?.code === ERR_CONNECTION_LOST) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = await this._localizeInstallError(err);
|
||||
|
||||
if (this._isShown()) {
|
||||
|
||||
@@ -620,15 +620,14 @@ class MoreInfoWeather extends LitElement {
|
||||
}
|
||||
|
||||
.temp-attribute .temp {
|
||||
position: relative;
|
||||
margin-right: var(--ha-space-6);
|
||||
direction: ltr;
|
||||
}
|
||||
|
||||
.temp-attribute .temp span {
|
||||
position: absolute;
|
||||
position: relative;
|
||||
font-size: var(--ha-font-size-2xl);
|
||||
top: 1px;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.state,
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
mdiCogOutline,
|
||||
mdiContentDuplicate,
|
||||
mdiDevices,
|
||||
mdiDirections,
|
||||
mdiDotsVertical,
|
||||
mdiDownload,
|
||||
mdiInformationOutline,
|
||||
@@ -37,6 +38,8 @@ import {
|
||||
computeEntityNameParts,
|
||||
type EntityNameType,
|
||||
} from "../../common/entity/compute_entity_name_display";
|
||||
import { getEntityLocation } from "../../common/entity/get_entity_location";
|
||||
import { navigationUrl } from "../../common/map/navigation-url";
|
||||
import {
|
||||
getHistoryState,
|
||||
navigate,
|
||||
@@ -504,11 +507,29 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
case "download_snapshot":
|
||||
this._downloadSnapshot();
|
||||
break;
|
||||
case "directions":
|
||||
this._openDirections();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private _openDirections() {
|
||||
const stateObj = this._entityId
|
||||
? (this.hass.states[this._entityId] as HassEntity | undefined)
|
||||
: undefined;
|
||||
const location = stateObj && getEntityLocation(stateObj, this.hass.states);
|
||||
if (!location) {
|
||||
return;
|
||||
}
|
||||
window.open(
|
||||
navigationUrl(location.latitude, location.longitude),
|
||||
"_blank",
|
||||
"noreferrer"
|
||||
);
|
||||
}
|
||||
|
||||
private async _resetFavorites() {
|
||||
const favoritesContext = this._getFavoritesContext();
|
||||
|
||||
@@ -632,6 +653,16 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
</ha-dropdown-item>
|
||||
`
|
||||
: nothing;
|
||||
const hasLocation =
|
||||
!!stateObj && !!getEntityLocation(stateObj, this.hass.states);
|
||||
const directionsMenuItem = hasLocation
|
||||
? html`
|
||||
<ha-dropdown-item value="directions">
|
||||
<ha-svg-icon slot="icon" .path=${mdiDirections}></ha-svg-icon>
|
||||
${this.hass.localize("ui.dialogs.more_info_control.directions")}
|
||||
</ha-dropdown-item>
|
||||
`
|
||||
: nothing;
|
||||
const viewTitle = this._computeViewTitle();
|
||||
const defaultTitle = breadcrumb[breadcrumb.length - 1] || entityId;
|
||||
if (!viewTitle) {
|
||||
@@ -801,9 +832,10 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
></ha-icon-button>
|
||||
|
||||
${
|
||||
domain === "camera"
|
||||
domain === "camera" || hasLocation
|
||||
? html`
|
||||
${downloadSnapshotMenuItem}
|
||||
${directionsMenuItem}
|
||||
<wa-divider></wa-divider>
|
||||
`
|
||||
: nothing
|
||||
@@ -940,7 +972,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
domain === "camera"
|
||||
domain === "camera" || hasLocation
|
||||
? html`
|
||||
<ha-dropdown
|
||||
slot="headerActionItems"
|
||||
@@ -956,6 +988,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
.path=${mdiDotsVertical}
|
||||
></ha-icon-button>
|
||||
${downloadSnapshotMenuItem}
|
||||
${directionsMenuItem}
|
||||
</ha-dropdown>
|
||||
`
|
||||
: nothing
|
||||
|
||||
@@ -2,4 +2,10 @@ import "@webcomponents/scoped-custom-element-registry/scoped-custom-element-regi
|
||||
import "../resources/scoped-registry-ready";
|
||||
import "../layouts/home-assistant";
|
||||
|
||||
// Custom cards and plugins can reach the helpers on any page, not only once a
|
||||
// dashboard has loaded.
|
||||
Object.assign(window, {
|
||||
loadCardHelpers: () => import("../panels/lovelace/custom-card-helpers"),
|
||||
});
|
||||
|
||||
import("../resources/append-ha-style");
|
||||
@@ -0,0 +1,63 @@
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-code-editor";
|
||||
import "../../../components/ha-dialog";
|
||||
import { DialogMixin } from "../../../dialogs/dialog-mixin";
|
||||
import type { BlueprintContentDialogParams } from "./show-dialog-blueprint-content";
|
||||
|
||||
@customElement("dialog-blueprint-content")
|
||||
class DialogBlueprintContent extends DialogMixin<BlueprintContentDialogParams>(
|
||||
LitElement
|
||||
) {
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
protected render() {
|
||||
if (!this.params) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-dialog
|
||||
open
|
||||
width="full"
|
||||
flexcontent
|
||||
header-title=${this._localize(
|
||||
"ui.panel.config.blueprint.add.raw_blueprint"
|
||||
)}
|
||||
header-subtitle=${this.params.name}
|
||||
>
|
||||
<ha-code-editor
|
||||
mode="yaml"
|
||||
.value=${this.params.content}
|
||||
read-only
|
||||
in-dialog
|
||||
dir="ltr"
|
||||
></ha-code-editor>
|
||||
</ha-dialog>
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
ha-dialog {
|
||||
--dialog-content-padding: 0;
|
||||
}
|
||||
/* A grid, so that the editor fills the height and scrolls inside */
|
||||
ha-code-editor {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"dialog-blueprint-content": DialogBlueprintContent;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,14 @@
|
||||
import { mdiClose, mdiOpenInNew } from "@mdi/js";
|
||||
import "@home-assistant/components/card";
|
||||
import { mdiClose, mdiCodeBraces, mdiOpenInNew } from "@mdi/js";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import type { HASSDomTargetEvent } from "../../../common/dom/fire_event";
|
||||
import { withViewTransition } from "../../../common/util/view-transition";
|
||||
import "../../../components/ha-alert";
|
||||
import "../../../components/ha-button";
|
||||
import "../../../components/ha-code-editor";
|
||||
import "../../../components/ha-dialog";
|
||||
import "../../../components/ha-dialog-footer";
|
||||
import "../../../components/ha-dialog-header";
|
||||
import "../../../components/ha-expansion-panel";
|
||||
import "../../../components/ha-markdown";
|
||||
import "../../../components/ha-spinner";
|
||||
import "../../../components/input/ha-input";
|
||||
@@ -21,6 +19,7 @@ import { DirtyStateProviderMixin } from "../../../mixins/dirty-state-provider-mi
|
||||
import { haStyleDialog } from "../../../resources/styles";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
import { documentationUrl } from "../../../util/documentation-url";
|
||||
import { showBlueprintContentDialog } from "./show-dialog-blueprint-content";
|
||||
|
||||
interface BlueprintImportState {
|
||||
value: string;
|
||||
@@ -33,8 +32,6 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
) {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ type: Boolean, reflect: true }) public large = false;
|
||||
|
||||
@state() private _params?;
|
||||
|
||||
@state() private _open = false;
|
||||
@@ -58,7 +55,6 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
this._error = undefined;
|
||||
this._url = this._params.url;
|
||||
this._sourceUrlWarning = !this._isTrustedBlueprintUrl(this._url);
|
||||
this.large = false;
|
||||
this._open = true;
|
||||
this._initDirtyTracking(
|
||||
{ type: "shallow" },
|
||||
@@ -88,7 +84,6 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
<ha-dialog
|
||||
.open=${this._open}
|
||||
.accessibleLabel=${heading}
|
||||
width=${this.large ? "full" : "medium"}
|
||||
.preventScrimClose=${this.isDirtyState}
|
||||
@closed=${this._dialogClosed}
|
||||
>
|
||||
@@ -99,9 +94,7 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
.label=${this.hass.localize("ui.common.close")}
|
||||
.path=${mdiClose}
|
||||
></ha-icon-button>
|
||||
<span slot="title" class="title-enlargeable" @click=${this._enlarge}>
|
||||
${heading}
|
||||
</span>
|
||||
<span slot="title">${heading}</span>
|
||||
</ha-dialog-header>
|
||||
<div>
|
||||
${
|
||||
@@ -164,18 +157,37 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
></ha-input>
|
||||
`
|
||||
}
|
||||
<ha-expansion-panel
|
||||
.header=${this.hass.localize(
|
||||
"ui.panel.config.blueprint.add.raw_blueprint"
|
||||
)}
|
||||
>
|
||||
<ha-code-editor
|
||||
mode="yaml"
|
||||
.value=${this._result.raw_data}
|
||||
read-only
|
||||
dir="ltr"
|
||||
></ha-code-editor>
|
||||
</ha-expansion-panel>
|
||||
<hac-card class="content-card">
|
||||
<div class="content-row">
|
||||
<div class="content-text">
|
||||
<span>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.blueprint.add.raw_blueprint"
|
||||
)}
|
||||
</span>
|
||||
<span class="content-description">
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.blueprint.add.raw_blueprint_description"
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<ha-button
|
||||
appearance="filled"
|
||||
.accessibleLabel=${this.hass.localize(
|
||||
"ui.panel.config.blueprint.add.view_raw_blueprint_label"
|
||||
)}
|
||||
@click=${this._showContent}
|
||||
>
|
||||
<ha-svg-icon
|
||||
slot="start"
|
||||
.path=${mdiCodeBraces}
|
||||
></ha-svg-icon>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.blueprint.add.view_raw_blueprint"
|
||||
)}
|
||||
</ha-button>
|
||||
</div>
|
||||
</hac-card>
|
||||
${
|
||||
this._result?.exists
|
||||
? html`
|
||||
@@ -275,9 +287,10 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
`;
|
||||
}
|
||||
|
||||
private _enlarge() {
|
||||
withViewTransition(() => {
|
||||
this.large = !this.large;
|
||||
private _showContent() {
|
||||
showBlueprintContentDialog(this, {
|
||||
name: this._result!.blueprint.metadata.name,
|
||||
content: this._result!.raw_data,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -384,11 +397,23 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
a ha-svg-icon {
|
||||
--mdc-icon-size: 16px;
|
||||
}
|
||||
ha-expansion-panel {
|
||||
--expansion-panel-content-padding: 0px;
|
||||
.content-card {
|
||||
margin: var(--ha-space-6) 0 var(--ha-space-2);
|
||||
}
|
||||
.title-enlargeable {
|
||||
display: block;
|
||||
.content-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-4);
|
||||
}
|
||||
.content-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.content-description {
|
||||
font-size: var(--ha-font-size-s);
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
|
||||
export interface BlueprintContentDialogParams {
|
||||
name: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export const loadBlueprintContentDialog = () =>
|
||||
import("./dialog-blueprint-content");
|
||||
|
||||
export const showBlueprintContentDialog = (
|
||||
element: HTMLElement,
|
||||
dialogParams: BlueprintContentDialogParams
|
||||
): void => {
|
||||
fireEvent(element, "show-dialog", {
|
||||
dialogTag: "dialog-blueprint-content",
|
||||
dialogImport: loadBlueprintContentDialog,
|
||||
dialogParams,
|
||||
});
|
||||
};
|
||||
@@ -93,13 +93,13 @@ export class CloudRemotePref extends LitElement {
|
||||
<ha-card
|
||||
outlined
|
||||
header=${this.hass.localize(
|
||||
"ui.panel.config.cloud.account.remote.card_title"
|
||||
"ui.panel.config.cloud.account.remote.title"
|
||||
)}
|
||||
>
|
||||
<div class="header-actions">
|
||||
<ha-switch
|
||||
.accessibleLabel=${this.hass.localize(
|
||||
"ui.panel.config.cloud.account.remote.card_title"
|
||||
"ui.panel.config.cloud.account.remote.title"
|
||||
)}
|
||||
.checked=${remote_enabled}
|
||||
@change=${this._toggleChanged}
|
||||
|
||||
@@ -104,7 +104,7 @@ export class CloudWebhooks extends LitElement {
|
||||
<div class="card-actions">
|
||||
<ha-button
|
||||
appearance="plain"
|
||||
href="https://www.nabucasa.com/config/webhooks"
|
||||
href="https://www.nabucasa.com/config/webhooks/"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
} from "../../../common/integrations/protocolIntegrationPicked";
|
||||
import { navigate } from "../../../common/navigate";
|
||||
import { caseInsensitiveStringCompare } from "../../../common/string/compare";
|
||||
import { nextRender } from "../../../common/util/render-status";
|
||||
import type {
|
||||
LocalizeFunc,
|
||||
LocalizeKeys,
|
||||
@@ -109,6 +110,7 @@ import {
|
||||
} from "./add-integration-list";
|
||||
import "./ha-integration-list-item";
|
||||
import "./ha-integration-list-title";
|
||||
import type { HaDomainIntegrations } from "./ha-domain-integrations";
|
||||
import type { HaIntegrationListItem } from "./ha-integration-list-item";
|
||||
import type { AddIntegrationDialogParams } from "./show-add-integration-dialog";
|
||||
import { showYamlIntegrationDialog } from "./show-add-integration-dialog";
|
||||
@@ -169,6 +171,9 @@ class AddIntegrationDialog extends LitElement {
|
||||
|
||||
@state() private _showDiscovered = false;
|
||||
|
||||
// The discovered devices of one integration
|
||||
@state() private _discoveredDomain?: string;
|
||||
|
||||
@state() private _openedDirectly = false;
|
||||
|
||||
@state() private _navigateToResult = false;
|
||||
@@ -186,6 +191,9 @@ class AddIntegrationDialog extends LitElement {
|
||||
|
||||
@query("ha-input-search") private _searchInput?: HaInputSearch;
|
||||
|
||||
@query("ha-domain-integrations")
|
||||
private _domainIntegrations?: HaDomainIntegrations;
|
||||
|
||||
// The focused row is gone after drilling
|
||||
private _focusAfterDrill?: "in" | "out";
|
||||
|
||||
@@ -274,6 +282,7 @@ class AddIntegrationDialog extends LitElement {
|
||||
this._prevPickedBrand = undefined;
|
||||
this._flowsInProgress = undefined;
|
||||
this._showDiscovered = false;
|
||||
this._discoveredDomain = undefined;
|
||||
this._openedDirectly = false;
|
||||
this._navigateToResult = false;
|
||||
this._filter = undefined;
|
||||
@@ -514,8 +523,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) {
|
||||
@@ -892,24 +909,47 @@ class AddIntegrationDialog extends LitElement {
|
||||
findIntegration(this._integrations, this._pickedBrand)
|
||||
: undefined;
|
||||
|
||||
const showingPickedBrand = Boolean(
|
||||
this._pickedBrand && (!this._integrations || pickedIntegration)
|
||||
);
|
||||
const showingDiscoveredGroup =
|
||||
!showingPickedBrand && !!this._discoveredDomain;
|
||||
const showingBrandView =
|
||||
(this._pickedBrand && (!this._integrations || pickedIntegration)) ||
|
||||
this._showDiscovered;
|
||||
showingPickedBrand || showingDiscoveredGroup || this._showDiscovered;
|
||||
|
||||
const flowsInProgress = showingBrandView
|
||||
? this._getFlowsForCurrentView(pickedIntegration)
|
||||
: [];
|
||||
const brandDomain = showingPickedBrand
|
||||
? this._pickedBrand
|
||||
: showingDiscoveredGroup
|
||||
? this._discoveredDomain
|
||||
: undefined;
|
||||
const brandIntegration = showingPickedBrand
|
||||
? pickedIntegration
|
||||
: showingDiscoveredGroup
|
||||
? findIntegration(this._integrations, this._discoveredDomain!)
|
||||
: undefined;
|
||||
|
||||
const headerTitle = showingBrandView
|
||||
? this._getBrandHeading(pickedIntegration, flowsInProgress)
|
||||
: this._narrow && this._drilled
|
||||
? this._browsingTitle()
|
||||
: this.hass.localize(
|
||||
"ui.panel.config.integrations.add_device_or_integration"
|
||||
);
|
||||
const flowsInProgress = showingPickedBrand
|
||||
? this._getFlowsForBrand(pickedIntegration)
|
||||
: showingDiscoveredGroup
|
||||
? this._getFlowsForDiscoveredGroup(this._discoveredDomain!)
|
||||
: this._showDiscovered
|
||||
? this._flowsInProgress || []
|
||||
: [];
|
||||
|
||||
const headerSubtitle =
|
||||
!showingBrandView && this._narrow && this._drilled
|
||||
const headerTitle = showingDiscoveredGroup
|
||||
? brandIntegration?.name ||
|
||||
domainToName(this.hass.localize, this._discoveredDomain!)
|
||||
: showingBrandView
|
||||
? this._getBrandHeading(pickedIntegration, flowsInProgress)
|
||||
: this._narrow && this._drilled
|
||||
? this._browsingTitle()
|
||||
: this.hass.localize(
|
||||
"ui.panel.config.integrations.add_device_or_integration"
|
||||
);
|
||||
|
||||
const headerSubtitle = showingDiscoveredGroup
|
||||
? this.hass.localize("ui.panel.config.integrations.discovered")
|
||||
: !showingBrandView && this._narrow && this._drilled
|
||||
? this._subcategory
|
||||
? integrationCategoryName(this.hass.localize, this._category!)
|
||||
: this.hass.localize(
|
||||
@@ -930,7 +970,7 @@ class AddIntegrationDialog extends LitElement {
|
||||
showingBrandView
|
||||
? html`
|
||||
${
|
||||
!this._openedDirectly
|
||||
!this._openedDirectly || this._discoveredDomain
|
||||
? html`
|
||||
<ha-icon-button-prev
|
||||
slot="headerNavigationIcon"
|
||||
@@ -939,7 +979,12 @@ class AddIntegrationDialog extends LitElement {
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
${this._renderBrandView(pickedIntegration, flowsInProgress)}
|
||||
${this._renderBrandView(
|
||||
brandDomain,
|
||||
brandIntegration,
|
||||
flowsInProgress,
|
||||
!showingPickedBrand && !showingDiscoveredGroup
|
||||
)}
|
||||
`
|
||||
: html`
|
||||
${
|
||||
@@ -983,13 +1028,15 @@ class AddIntegrationDialog extends LitElement {
|
||||
);
|
||||
}
|
||||
|
||||
private _getFlowsForCurrentView(
|
||||
private _getFlowsForDiscoveredGroup(domain: string) {
|
||||
return (this._flowsInProgress || []).filter(
|
||||
(flow) => flow.handler === domain
|
||||
);
|
||||
}
|
||||
|
||||
private _getFlowsForBrand(
|
||||
integration: Brand | Integration | undefined
|
||||
): DataEntryFlowProgress[] {
|
||||
if (this._showDiscovered) {
|
||||
// Show all discovered flows
|
||||
return this._flowsInProgress || [];
|
||||
}
|
||||
if (!this._pickedBrand || !integration) {
|
||||
return [];
|
||||
}
|
||||
@@ -1036,23 +1083,39 @@ class AddIntegrationDialog extends LitElement {
|
||||
}
|
||||
|
||||
private _renderBrandView(
|
||||
domain: string | undefined,
|
||||
integration: Brand | Integration | undefined,
|
||||
flowsInProgress: DataEntryFlowProgress[]
|
||||
flowsInProgress: DataEntryFlowProgress[],
|
||||
groupFlows: boolean
|
||||
): TemplateResult {
|
||||
return html`<ha-domain-integrations
|
||||
.hass=${this.hass}
|
||||
.domain=${this._pickedBrand}
|
||||
.domain=${domain}
|
||||
.integration=${integration}
|
||||
.flowsInProgress=${flowsInProgress}
|
||||
.navigateToResult=${this._navigateToResult}
|
||||
.showManageLink=${this._showDiscovered || this._showDiscoveredView}
|
||||
.boxed=${!integration}
|
||||
.groupFlows=${groupFlows}
|
||||
.brands=${this._integrations}
|
||||
@close-dialog=${this.closeDialog}
|
||||
@supported-by=${this._handleSupportedByEvent}
|
||||
@select-brand=${this._handleSelectBrandEvent}
|
||||
@discovered-group-picked=${this._handleDiscoveredGroupPicked}
|
||||
></ha-domain-integrations>`;
|
||||
}
|
||||
|
||||
private async _handleDiscoveredGroupPicked(
|
||||
ev: HASSDomEvent<HASSDomEvents["discovered-group-picked"]>
|
||||
) {
|
||||
this._discoveredDomain = ev.detail.domain;
|
||||
// The picked row is gone, and the back button renders after this element
|
||||
await nextRender();
|
||||
if (this._discoveredDomain) {
|
||||
this._backButton?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
private _handleSelectBrandEvent(ev: CustomEvent) {
|
||||
this._prevPickedBrand = this._pickedBrand;
|
||||
this._pickedBrand = ev.detail.brand;
|
||||
@@ -1170,7 +1233,12 @@ class AddIntegrationDialog extends LitElement {
|
||||
${
|
||||
this._showDiscoveredView && !this._filter
|
||||
? html`<div class="discovered">
|
||||
${this._renderBrandView(undefined, this._flowsInProgress || [])}
|
||||
${this._renderBrandView(
|
||||
undefined,
|
||||
undefined,
|
||||
this._flowsInProgress || [],
|
||||
true
|
||||
)}
|
||||
</div>`
|
||||
: rows
|
||||
? html`${
|
||||
@@ -1207,17 +1275,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 +1833,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 +1856,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
|
||||
@@ -2065,12 +2123,25 @@ class AddIntegrationDialog extends LitElement {
|
||||
}
|
||||
|
||||
private _prevClicked() {
|
||||
if (this._showDiscovered) {
|
||||
this._showDiscovered = false;
|
||||
if (this._pickedBrand) {
|
||||
this._pickedBrand = this._prevPickedBrand;
|
||||
this._prevPickedBrand = undefined;
|
||||
return;
|
||||
}
|
||||
this._pickedBrand = this._prevPickedBrand;
|
||||
this._prevPickedBrand = undefined;
|
||||
if (this._discoveredDomain) {
|
||||
const domain = this._discoveredDomain;
|
||||
this._discoveredDomain = undefined;
|
||||
this._focusFlowGroupAfterBack(domain);
|
||||
return;
|
||||
}
|
||||
this._showDiscovered = false;
|
||||
}
|
||||
|
||||
private async _focusFlowGroupAfterBack(domain: string) {
|
||||
await nextRender();
|
||||
if (this._open && !this._discoveredDomain) {
|
||||
this._domainIntegrations?.focusFlowGroup(domain);
|
||||
}
|
||||
}
|
||||
|
||||
static styles = [
|
||||
|
||||
@@ -26,6 +26,7 @@ import { customElement, property, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { navigate } from "../../../common/navigate";
|
||||
import { formatListWithAnds } from "../../../common/string/format-list";
|
||||
import { copyToClipboard } from "../../../common/util/copy-clipboard";
|
||||
import "../../../components/ha-dropdown";
|
||||
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
|
||||
@@ -95,6 +96,9 @@ export class HaConfigEntryRow extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public data!: ConfigEntryData;
|
||||
|
||||
/** The loaded integrations that lose this integration with this entry. */
|
||||
@property({ attribute: false }) public dependents?: IntegrationManifest[];
|
||||
|
||||
@state() private _expanded = true;
|
||||
|
||||
@state() private _devicesExpanded = true;
|
||||
@@ -812,14 +816,33 @@ export class HaConfigEntryRow extends LitElement {
|
||||
const applicationCredentialsId =
|
||||
await this._applicationCredentialForRemove(entryId);
|
||||
|
||||
const text = this.hass.localize(
|
||||
"ui.panel.config.integrations.config_entry.delete_confirm_text"
|
||||
);
|
||||
const confirmed = await showConfirmationDialog(this, {
|
||||
title: this.hass.localize(
|
||||
"ui.panel.config.integrations.config_entry.delete_confirm_title",
|
||||
{ title: this.data.entry.title }
|
||||
),
|
||||
text: this.hass.localize(
|
||||
"ui.panel.config.integrations.config_entry.delete_confirm_text"
|
||||
),
|
||||
text: this.dependents?.length
|
||||
? html`${text}<br /><br />${this.hass.localize(
|
||||
"ui.panel.config.integrations.config_entry.delete_confirm_dependents",
|
||||
{
|
||||
count: this.dependents.length,
|
||||
integrations: formatListWithAnds(
|
||||
this.hass.locale,
|
||||
this.dependents.map((manifest) =>
|
||||
domainToName(this.hass.localize, manifest.domain, manifest)
|
||||
)
|
||||
),
|
||||
name: domainToName(
|
||||
this.hass.localize,
|
||||
this.data.entry.domain,
|
||||
this.manifest
|
||||
),
|
||||
}
|
||||
)}`
|
||||
: text,
|
||||
confirmText: this.hass!.localize("ui.common.delete"),
|
||||
dismissText: this.hass!.localize("ui.common.cancel"),
|
||||
destructive: true,
|
||||
|
||||
@@ -21,7 +21,7 @@ import memoizeOne from "memoize-one";
|
||||
import { ensureArray } from "../../../common/array/ensure-array";
|
||||
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
|
||||
import { QueryParamsController } from "../../../common/controllers/query-params-controller";
|
||||
import { ContextSubscriptionController } from "../../../common/decorators/consume";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import type { HASSDomTargetEvent } from "../../../common/dom/fire_event";
|
||||
import { computeDeviceNameDisplay } from "../../../common/entity/compute_device_name";
|
||||
import {
|
||||
@@ -176,9 +176,9 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
@state() private _manifest?: IntegrationManifest;
|
||||
|
||||
/** The manifests of all loaded integrations, to find the dependents. */
|
||||
@state() private _loadedManifests?: DomainManifestLookup;
|
||||
|
||||
private _manifestsConsumer?: ContextSubscriptionController<DomainManifestLookup>;
|
||||
@consume({ context: manifestsContext, subscribe: true })
|
||||
@state()
|
||||
private _loadedManifests?: DomainManifestLookup;
|
||||
|
||||
@state() private _extraConfigEntries?: ConfigEntry[];
|
||||
|
||||
@@ -432,17 +432,23 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
this.domain
|
||||
);
|
||||
|
||||
const dependents = this._getDependents(
|
||||
this.domain,
|
||||
this._loadedManifests,
|
||||
this.hass.localize,
|
||||
this.hass.locale.language
|
||||
);
|
||||
// Without the dependents, a dependency looks like a YAML integration.
|
||||
const dependents =
|
||||
this._manifest && !this._manifest.config_flow
|
||||
? this._getDependents(
|
||||
this.domain,
|
||||
this._loadedManifests,
|
||||
this.hass.localize,
|
||||
this.hass.locale.language
|
||||
)
|
||||
: [];
|
||||
const showDependents = normalEntries.length === 0 && dependents.length > 0;
|
||||
const dependencyOnly =
|
||||
normalEntries.length === 0 &&
|
||||
dependents.length > 0 &&
|
||||
!this._manifest?.config_flow;
|
||||
// Deleting the last entry in use leaves the dependents without it.
|
||||
const entriesInUse = configEntries.filter(
|
||||
(entry) => entry.source !== "ignore" && !entry.disabled_by
|
||||
);
|
||||
const lastEntryId =
|
||||
entriesInUse.length === 1 ? entriesInUse[0].entry_id : undefined;
|
||||
// Hold back the YAML texts and "Add entry" until the manifest and the
|
||||
// dependents are known. Entries do not wait, so a failed request cannot
|
||||
// hide them.
|
||||
@@ -461,7 +467,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
|
||||
const showAddEntry =
|
||||
this._manifest?.integration_type !== "hardware" &&
|
||||
!showDependents &&
|
||||
!dependencyOnly &&
|
||||
!dependentsLoading &&
|
||||
!setUpInPanel &&
|
||||
(!this._manifest?.single_config_entry ||
|
||||
@@ -653,7 +659,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
}
|
||||
${
|
||||
normalEntries.length === 0 &&
|
||||
!showDependents &&
|
||||
!dependencyOnly &&
|
||||
!dependentsLoading &&
|
||||
!setUpInPanel &&
|
||||
this._manifest &&
|
||||
@@ -1010,6 +1016,11 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
.diagnosticHandler=${this._diagnosticHandler}
|
||||
.entities=${this._entities}
|
||||
.data=${data}
|
||||
.dependents=${
|
||||
data.entry.entry_id === lastEntryId
|
||||
? dependents
|
||||
: undefined
|
||||
}
|
||||
data-entry-id=${data.entry.entry_id}
|
||||
></ha-config-entry-row>`
|
||||
)}
|
||||
@@ -1018,19 +1029,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
showDependents
|
||||
? html`<div class="section">
|
||||
<h3 class="section-header">
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.integrations.integration_page.used_by"
|
||||
)}
|
||||
</h3>
|
||||
${this._renderDependents(dependents)}
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
showDependents ||
|
||||
dependencyOnly ||
|
||||
dependentsLoading ||
|
||||
(setUpInPanel && normalEntries.length === 0)
|
||||
? nothing
|
||||
@@ -1077,6 +1076,11 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
.diagnosticHandler=${this._diagnosticHandler}
|
||||
.entities=${this._entities}
|
||||
.data=${data}
|
||||
.dependents=${
|
||||
data.entry.entry_id === lastEntryId
|
||||
? dependents
|
||||
: undefined
|
||||
}
|
||||
data-entry-id=${data.entry.entry_id}
|
||||
></ha-config-entry-row>`
|
||||
)}
|
||||
@@ -1084,26 +1088,23 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
}
|
||||
</div>`
|
||||
}
|
||||
${
|
||||
dependents.length
|
||||
? html`<div class="section">
|
||||
<h3 class="section-header">
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.integrations.integration_page.used_by"
|
||||
)}
|
||||
</h3>
|
||||
${this._renderDependents(dependents)}
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
</hass-subpage>
|
||||
`;
|
||||
}
|
||||
|
||||
// Only an integration without a config flow needs the loaded manifests, so
|
||||
// other integration pages do not make the context fetch them.
|
||||
private _watchLoadedManifests(): void {
|
||||
if (this._manifestsConsumer) {
|
||||
return;
|
||||
}
|
||||
this._manifestsConsumer = new ContextSubscriptionController(
|
||||
this,
|
||||
manifestsContext,
|
||||
(manifests) => {
|
||||
this._loadedManifests = manifests;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private _getDependents = memoizeOne(
|
||||
(
|
||||
domain: string,
|
||||
@@ -1199,9 +1200,6 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
return;
|
||||
}
|
||||
this._manifest = await fetchIntegrationManifest(this.hass, this.domain);
|
||||
if (!this._manifest.config_flow) {
|
||||
this._watchLoadedManifests();
|
||||
}
|
||||
if (
|
||||
this._manifest.integration_type &&
|
||||
!["device", "hub", "service"].includes(this._manifest.integration_type)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import "@home-assistant/webawesome/dist/components/divider/divider";
|
||||
import { mdiPlus } from "@mdi/js";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, queryAll } from "lit/decorators";
|
||||
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
@@ -13,8 +14,10 @@ import {
|
||||
import { navigate } from "../../../common/navigate";
|
||||
import { caseInsensitiveStringCompare } from "../../../common/string/compare";
|
||||
import "../../../components/ha-button";
|
||||
import "../../../components/ha-icon-next";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import "../../../components/item/ha-list-item-button";
|
||||
import type { HaListItemButton } from "../../../components/item/ha-list-item-button";
|
||||
import "../../../components/list/ha-list-base";
|
||||
import { localizeConfigFlowTitle } from "../../../data/config_flow";
|
||||
import type { DataEntryFlowProgress } from "../../../data/data_entry_flow";
|
||||
@@ -22,7 +25,8 @@ import {
|
||||
domainToName,
|
||||
fetchIntegrationManifest,
|
||||
} from "../../../data/integration";
|
||||
import type { Brand, Integration } from "../../../data/integrations";
|
||||
import type { Brand, Brands, Integration } from "../../../data/integrations";
|
||||
import { findIntegration } from "../../../data/integrations";
|
||||
import { showConfigFlowDialog } from "../../../dialogs/config-flow/show-dialog-config-flow";
|
||||
import { haStyle } from "../../../resources/styles";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
@@ -33,7 +37,7 @@ import { showYamlIntegrationDialog } from "./show-add-integration-dialog";
|
||||
export const standardToDomain = { zigbee: "zha", zwave: "zwave_js" } as const;
|
||||
|
||||
@customElement("ha-domain-integrations")
|
||||
class HaDomainIntegrations extends LitElement {
|
||||
export class HaDomainIntegrations extends LitElement {
|
||||
public hass!: HomeAssistant;
|
||||
|
||||
@property() public domain!: string;
|
||||
@@ -51,6 +55,15 @@ class HaDomainIntegrations extends LitElement {
|
||||
|
||||
@property({ type: Boolean, reflect: true }) public boxed = false;
|
||||
|
||||
/** An integration with more than one discovered device gets one row. */
|
||||
@property({ attribute: false }) public groupFlows = false;
|
||||
|
||||
/** Names integrations that have no translated title, like most that aren't set up. */
|
||||
@property({ attribute: false }) public brands?: Brands;
|
||||
|
||||
@queryAll("ha-list-item-button.flow-group")
|
||||
private _flowGroups!: NodeListOf<HaListItemButton & { domain: string }>;
|
||||
|
||||
protected render() {
|
||||
// Only show manage link if not already on the integrations dashboard
|
||||
const manage =
|
||||
@@ -63,36 +76,11 @@ class HaDomainIntegrations extends LitElement {
|
||||
? html`<h3>
|
||||
${this.hass.localize("ui.panel.config.integrations.discovered")}
|
||||
</h3>
|
||||
${this.flowsInProgress.map(
|
||||
(flow) =>
|
||||
html`<ha-list-item-button
|
||||
.flow=${flow}
|
||||
@click=${this._flowInProgressPicked}
|
||||
>
|
||||
<img
|
||||
alt=""
|
||||
slot="start"
|
||||
loading="lazy"
|
||||
src=${brandsUrl(
|
||||
{
|
||||
domain: flow.handler,
|
||||
type: "icon",
|
||||
darkOptimized: this.hass.themes?.darkMode,
|
||||
},
|
||||
this.hass.auth.data.hassUrl
|
||||
)}
|
||||
crossorigin="anonymous"
|
||||
referrerpolicy="no-referrer"
|
||||
/>
|
||||
<span slot="headline"
|
||||
>${localizeConfigFlowTitle(this.hass.localize, flow)}</span
|
||||
>
|
||||
<span slot="supporting-text"
|
||||
>${domainToName(this.hass.localize, flow.handler)}</span
|
||||
>
|
||||
<ha-svg-icon slot="end" .path=${mdiPlus}></ha-svg-icon>
|
||||
</ha-list-item-button>`
|
||||
)}
|
||||
${
|
||||
this.groupFlows
|
||||
? this._renderFlowGroups(this.flowsInProgress)
|
||||
: this.flowsInProgress.map((flow) => this._renderFlow(flow))
|
||||
}
|
||||
<wa-divider></wa-divider>
|
||||
${
|
||||
this.integration &&
|
||||
@@ -303,6 +291,87 @@ class HaDomainIntegrations extends LitElement {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
public async focusFlowGroup(domain: string) {
|
||||
await this.updateComplete;
|
||||
[...this._flowGroups].find((row) => row.domain === domain)?.focus();
|
||||
}
|
||||
|
||||
private _renderFlowGroups(flows: DataEntryFlowProgress[]) {
|
||||
const groups = new Map<string, DataEntryFlowProgress[]>();
|
||||
flows.forEach((flow) => {
|
||||
groups.set(flow.handler, [...(groups.get(flow.handler) || []), flow]);
|
||||
});
|
||||
if (groups.size === 1) {
|
||||
return flows.map((flow) => this._renderFlow(flow));
|
||||
}
|
||||
return [...groups.entries()].map(([domain, group]) =>
|
||||
group.length === 1
|
||||
? this._renderFlow(group[0])
|
||||
: html`<ha-list-item-button
|
||||
class="flow-group"
|
||||
.domain=${domain}
|
||||
@click=${this._flowGroupPicked}
|
||||
>
|
||||
${this._renderIcon(domain)}
|
||||
<span slot="headline">${this._domainName(domain)}</span>
|
||||
<span slot="supporting-text"
|
||||
>${this.hass.localize(
|
||||
"ui.panel.config.integrations.discovered_devices",
|
||||
{ count: group.length }
|
||||
)}</span
|
||||
>
|
||||
<ha-icon-next slot="end"></ha-icon-next>
|
||||
</ha-list-item-button>`
|
||||
);
|
||||
}
|
||||
|
||||
private _renderFlow(flow: DataEntryFlowProgress) {
|
||||
return html`<ha-list-item-button
|
||||
.flow=${flow}
|
||||
@click=${this._flowInProgressPicked}
|
||||
>
|
||||
${this._renderIcon(flow.handler)}
|
||||
<span slot="headline"
|
||||
>${localizeConfigFlowTitle(this.hass.localize, flow)}</span
|
||||
>
|
||||
<span slot="supporting-text">${this._domainName(flow.handler)}</span>
|
||||
<ha-svg-icon slot="end" .path=${mdiPlus}></ha-svg-icon>
|
||||
</ha-list-item-button>`;
|
||||
}
|
||||
|
||||
private _domainName(domain: string) {
|
||||
return (
|
||||
findIntegration(this.brands, domain)?.name ||
|
||||
domainToName(this.hass.localize, domain)
|
||||
);
|
||||
}
|
||||
|
||||
private _renderIcon(domain: string): TemplateResult {
|
||||
return html`<img
|
||||
alt=""
|
||||
slot="start"
|
||||
loading="lazy"
|
||||
src=${brandsUrl(
|
||||
{
|
||||
domain,
|
||||
type: "icon",
|
||||
darkOptimized: this.hass.themes?.darkMode,
|
||||
},
|
||||
this.hass.auth.data.hassUrl
|
||||
)}
|
||||
crossorigin="anonymous"
|
||||
referrerpolicy="no-referrer"
|
||||
/>`;
|
||||
}
|
||||
|
||||
private _flowGroupPicked(
|
||||
ev: HASSDomCurrentTargetEvent<HTMLElement & { domain: string }>
|
||||
) {
|
||||
fireEvent(this, "discovered-group-picked", {
|
||||
domain: ev.currentTarget.domain,
|
||||
});
|
||||
}
|
||||
|
||||
private async _integrationPicked(
|
||||
ev: HASSDomCurrentTargetEvent<HTMLElement & { domain: string }>
|
||||
) {
|
||||
@@ -496,4 +565,8 @@ declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-domain-integrations": HaDomainIntegrations;
|
||||
}
|
||||
|
||||
interface HASSDomEvents {
|
||||
"discovered-group-picked": { domain: string };
|
||||
}
|
||||
}
|
||||
@@ -143,6 +143,7 @@ export class DialogAddUser extends DirtyStateProviderMixin<AddUserFormState>()(
|
||||
<ha-input
|
||||
class="username"
|
||||
name="username"
|
||||
autocomplete="username"
|
||||
.label=${this.hass.localize(
|
||||
"ui.panel.config.users.editor.username"
|
||||
)}
|
||||
@@ -160,6 +161,7 @@ export class DialogAddUser extends DirtyStateProviderMixin<AddUserFormState>()(
|
||||
"ui.panel.config.users.add_user.password"
|
||||
)}
|
||||
name="password"
|
||||
autocomplete="new-password"
|
||||
.value=${this._password}
|
||||
required
|
||||
@input=${this._handleValueChanged}
|
||||
@@ -173,6 +175,7 @@ export class DialogAddUser extends DirtyStateProviderMixin<AddUserFormState>()(
|
||||
"ui.panel.config.users.add_user.password_confirm"
|
||||
)}
|
||||
name="passwordConfirm"
|
||||
autocomplete="new-password"
|
||||
.value=${this._passwordConfirm}
|
||||
@input=${this._handleValueChanged}
|
||||
required
|
||||
|
||||
@@ -260,6 +260,12 @@ export const ENERGY_CARD_CATALOG: readonly EnergyCardCatalogEntry[] = [
|
||||
"ui.panel.energy.cards.energy_sources_table_title",
|
||||
(p) => hasGasSource(p)
|
||||
),
|
||||
entry(
|
||||
"gas",
|
||||
"gas-devices-detail-graph",
|
||||
"ui.panel.energy.cards.energy_devices_detail_graph_title",
|
||||
(p) => hasGasDevices(p)
|
||||
),
|
||||
entry("gas", "gas-sankey", "ui.panel.energy.cards.gas_sankey_title", (p) =>
|
||||
hasGasDevices(p)
|
||||
),
|
||||
|
||||
@@ -102,6 +102,19 @@ export class GasViewStrategy extends ReactiveElement {
|
||||
});
|
||||
}
|
||||
|
||||
if (isEnergyCardVisible("gas", "gas-devices-detail-graph", prefs, hidden)) {
|
||||
section.cards!.push({
|
||||
title: hass.localize(
|
||||
"ui.panel.energy.cards.energy_devices_detail_graph_title"
|
||||
),
|
||||
type: "gas-devices-detail-graph",
|
||||
collection_key: collectionKey,
|
||||
grid_options: {
|
||||
columns: 36,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (isEnergyCardVisible("gas", "gas-sankey", prefs, hidden)) {
|
||||
const showFloorsAndAreas = shouldShowFloorsAndAreas(
|
||||
prefs.device_consumption_gas,
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
import { TZDate } from "@date-fns/tz";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import {
|
||||
consumeEntityState,
|
||||
consumeLocalize,
|
||||
} from "../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../common/decorators/transform";
|
||||
import { resolveTimeZone } from "../../../common/datetime/resolve-time-zone";
|
||||
import { useAmPm } from "../../../common/datetime/use_am_pm";
|
||||
import { computeDomain } from "../../../common/entity/compute_domain";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-control-select-menu";
|
||||
import type { SelectOption } from "../../../components/ha-control-select-menu";
|
||||
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
|
||||
import {
|
||||
apiContext,
|
||||
configContext,
|
||||
internationalizationContext,
|
||||
} from "../../../data/context";
|
||||
import { setDateTimeValue } from "../../../data/datetime";
|
||||
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
|
||||
import { setInputDateTimeValue } from "../../../data/input_datetime";
|
||||
import { setTimeValue } from "../../../data/time";
|
||||
import type { FrontendLocaleData, TimeFormat } from "../../../data/translation";
|
||||
import type {
|
||||
HomeAssistant,
|
||||
HomeAssistantApi,
|
||||
HomeAssistantConfig,
|
||||
HomeAssistantInternationalization,
|
||||
} from "../../../types";
|
||||
import type { LovelaceCardFeature, LovelaceCardFeatureEditor } from "../types";
|
||||
import { cardFeatureStyles } from "./common/card-feature-styles";
|
||||
import type {
|
||||
LovelaceCardFeatureContext,
|
||||
TimeSetCardFeatureConfig,
|
||||
} from "./types";
|
||||
|
||||
interface TimeParts {
|
||||
hours: number;
|
||||
minutes: number;
|
||||
seconds: number;
|
||||
}
|
||||
|
||||
type Period = "AM" | "PM";
|
||||
|
||||
const TIME_REGEX = /^(\d{1,2}):(\d{2})(?::(\d{2}))?/;
|
||||
|
||||
const supportsTimeSetCardFeatureFromState = (stateObj: HassEntity) => {
|
||||
const domain = computeDomain(stateObj.entity_id);
|
||||
|
||||
return (
|
||||
domain === "time" ||
|
||||
domain === "datetime" ||
|
||||
(domain === "input_datetime" && Boolean(stateObj.attributes.has_time))
|
||||
);
|
||||
};
|
||||
|
||||
export const supportsTimeSetCardFeature = (
|
||||
hass: HomeAssistant,
|
||||
context: LovelaceCardFeatureContext
|
||||
) => {
|
||||
const stateObj = context.entity_id
|
||||
? hass.states[context.entity_id]
|
||||
: undefined;
|
||||
|
||||
if (!stateObj) return false;
|
||||
|
||||
return supportsTimeSetCardFeatureFromState(stateObj);
|
||||
};
|
||||
|
||||
// A datetime is shown in the time zone picked in the user's profile, like the
|
||||
// tile's state, so the time is read and changed in that time zone too.
|
||||
const toZonedDate = (value: string, timeZone?: string): Date => {
|
||||
const date = new Date(value);
|
||||
|
||||
if (!timeZone) {
|
||||
return date;
|
||||
}
|
||||
|
||||
const zoned = new TZDate(date, timeZone);
|
||||
|
||||
// TZDate is invalid where Intl lacks "longOffset" (Chrome < 95, Safari < 15.4)
|
||||
return isNaN(zoned.getHours()) ? date : zoned;
|
||||
};
|
||||
|
||||
const parseTime = (
|
||||
stateObj: HassEntity,
|
||||
timeZone?: string
|
||||
): TimeParts | undefined => {
|
||||
if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (computeDomain(stateObj.entity_id) === "datetime") {
|
||||
const dateObj = toZonedDate(stateObj.state, timeZone);
|
||||
|
||||
if (isNaN(dateObj.getTime())) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
hours: dateObj.getHours(),
|
||||
minutes: dateObj.getMinutes(),
|
||||
seconds: dateObj.getSeconds(),
|
||||
};
|
||||
}
|
||||
|
||||
// input_datetime with a date has a "YYYY-MM-DD HH:MM:SS" state
|
||||
const match = TIME_REGEX.exec(stateObj.state.split(" ").pop() ?? "");
|
||||
|
||||
if (!match) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
hours: Number(match[1]),
|
||||
minutes: Number(match[2]),
|
||||
seconds: match[3] ? Number(match[3]) : 0,
|
||||
};
|
||||
};
|
||||
|
||||
const pad = (value: number) => value.toString().padStart(2, "0");
|
||||
|
||||
// Seconds are kept as they are, so a time is matched on hours and minutes
|
||||
const timeKey = (time: TimeParts) => `${time.hours}:${time.minutes}`;
|
||||
|
||||
// Each write has its own id, as the same time can be sent more than once
|
||||
interface Write {
|
||||
id: number;
|
||||
key: string;
|
||||
}
|
||||
|
||||
const MINUTE_OPTIONS: SelectOption[] = Array.from({ length: 60 }, (_, i) => ({
|
||||
value: i.toString(),
|
||||
label: pad(i),
|
||||
}));
|
||||
|
||||
const HOUR_OPTIONS_24: SelectOption[] = Array.from({ length: 24 }, (_, i) => ({
|
||||
value: i.toString(),
|
||||
label: pad(i),
|
||||
}));
|
||||
|
||||
const HOUR_OPTIONS_12: SelectOption[] = [
|
||||
12,
|
||||
...Array.from({ length: 11 }, (_, i) => i + 1),
|
||||
].map((hour) => ({ value: hour.toString(), label: hour.toString() }));
|
||||
|
||||
@customElement("hui-time-set-card-feature")
|
||||
class HuiTimeSetCardFeature extends LitElement implements LovelaceCardFeature {
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
|
||||
private _stateObj?: HassEntity;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
@transform<HomeAssistantInternationalization, FrontendLocaleData>({
|
||||
transformer: ({ locale }) => locale,
|
||||
})
|
||||
private _locale?: FrontendLocaleData;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, string>({
|
||||
transformer: ({ config }) => config.time_zone,
|
||||
})
|
||||
private _serverTimeZone?: string;
|
||||
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: HomeAssistantApi;
|
||||
|
||||
@state() private _config?: TimeSetCardFeatureConfig;
|
||||
|
||||
// The newest selection and the write that sent it, shown instead of the
|
||||
// entity's time until every write is confirmed, so reports from earlier
|
||||
// writes don't overwrite it
|
||||
@state() private _selection?: {
|
||||
entityId: string;
|
||||
time: TimeParts;
|
||||
writeId: number;
|
||||
};
|
||||
|
||||
// Writes the entity hasn't reported back yet, oldest first
|
||||
private _unconfirmed: Write[] = [];
|
||||
|
||||
private _nextWriteId = 0;
|
||||
|
||||
// The entity and time last reported, to skip updates that don't change it
|
||||
private _reported?: string;
|
||||
|
||||
private get _timeZone(): string | undefined {
|
||||
return this._locale && this._serverTimeZone
|
||||
? resolveTimeZone(this._locale.time_zone, this._serverTimeZone)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
static getStubConfig(): TimeSetCardFeatureConfig {
|
||||
return {
|
||||
type: "time-set",
|
||||
};
|
||||
}
|
||||
|
||||
public static async getConfigElement(): Promise<LovelaceCardFeatureEditor> {
|
||||
await import("../editor/config-elements/hui-time-set-card-feature-editor");
|
||||
|
||||
return document.createElement("hui-time-set-card-feature-editor");
|
||||
}
|
||||
|
||||
public setConfig(config: TimeSetCardFeatureConfig): void {
|
||||
if (!config) {
|
||||
throw new Error("Invalid configuration");
|
||||
}
|
||||
|
||||
this._config = config;
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues): void {
|
||||
super.willUpdate(changedProps);
|
||||
|
||||
if (!changedProps.has("_stateObj") || !this._stateObj) {
|
||||
return;
|
||||
}
|
||||
|
||||
const current = parseTime(this._stateObj, this._timeZone);
|
||||
const key = current ? timeKey(current) : undefined;
|
||||
const reported = `${this._stateObj.entity_id} ${key}`;
|
||||
|
||||
if (reported === this._reported) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._reported = reported;
|
||||
|
||||
if (!this._selection) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Home Assistant applies writes in order, so a report confirms the oldest
|
||||
// unconfirmed write with that time, and any written before it
|
||||
const index = key
|
||||
? this._unconfirmed.findIndex((write) => write.key === key)
|
||||
: -1;
|
||||
|
||||
this._unconfirmed = index === -1 ? [] : this._unconfirmed.slice(index + 1);
|
||||
|
||||
// Once every write is confirmed, or the time changed elsewhere, show the
|
||||
// entity's time
|
||||
if (this._unconfirmed.length === 0) {
|
||||
this._selection = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Worked out from the current entity on each use, as the entity can change
|
||||
// after willUpdate when the card switches to another one
|
||||
private get _time(): TimeParts | undefined {
|
||||
if (!this._stateObj) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return this._selection?.entityId === this._stateObj.entity_id
|
||||
? this._selection.time
|
||||
: parseTime(this._stateObj, this._timeZone);
|
||||
}
|
||||
|
||||
private _useAmPm = memoizeOne(
|
||||
(locale: FrontendLocaleData, timeFormat?: TimeFormat) =>
|
||||
useAmPm(timeFormat ? { ...locale, time_format: timeFormat } : locale)
|
||||
);
|
||||
|
||||
private _periodOptions = memoizeOne((language: string): SelectOption[] => {
|
||||
const formatter = new Intl.DateTimeFormat(language, {
|
||||
hour: "numeric",
|
||||
hourCycle: "h12",
|
||||
});
|
||||
|
||||
const periodLabel = (hours: number, fallback: Period) =>
|
||||
formatter
|
||||
.formatToParts(new Date(2000, 0, 1, hours))
|
||||
.find((part) => part.type === "dayPeriod")?.value ?? fallback;
|
||||
|
||||
return [
|
||||
{ value: "AM", label: periodLabel(0, "AM") },
|
||||
{ value: "PM", label: periodLabel(12, "PM") },
|
||||
];
|
||||
});
|
||||
|
||||
private _hourSelected(ev: HaDropdownSelectEvent): void {
|
||||
const hour = Number(ev.detail.item.value);
|
||||
|
||||
if (
|
||||
!this._locale ||
|
||||
!this._useAmPm(this._locale, this._config?.time_format)
|
||||
) {
|
||||
this._setTime({ hours: hour });
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const isPm = (this._time?.hours ?? 0) >= 12;
|
||||
|
||||
this._setTime({ hours: (hour % 12) + (isPm ? 12 : 0) });
|
||||
}
|
||||
|
||||
private _minuteSelected(ev: HaDropdownSelectEvent): void {
|
||||
this._setTime({ minutes: Number(ev.detail.item.value) });
|
||||
}
|
||||
|
||||
private _periodSelected(ev: HaDropdownSelectEvent<Period>): void {
|
||||
const hours = (this._time?.hours ?? 0) % 12;
|
||||
|
||||
this._setTime({
|
||||
hours: ev.detail.item.value === "PM" ? hours + 12 : hours,
|
||||
});
|
||||
}
|
||||
|
||||
private async _setTime(change: Partial<TimeParts>) {
|
||||
if (!this._stateObj) return;
|
||||
|
||||
const stateObj = this._stateObj;
|
||||
const oldTime = this._time;
|
||||
|
||||
const time: TimeParts = {
|
||||
hours: 0,
|
||||
minutes: 0,
|
||||
seconds: 0,
|
||||
...oldTime,
|
||||
...change,
|
||||
};
|
||||
|
||||
if (
|
||||
oldTime &&
|
||||
time.hours === oldTime.hours &&
|
||||
time.minutes === oldTime.minutes
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const writeId = this._nextWriteId++;
|
||||
|
||||
this._selection = { entityId: stateObj.entity_id, time, writeId };
|
||||
this._unconfirmed = [
|
||||
...this._unconfirmed,
|
||||
{ id: writeId, key: timeKey(time) },
|
||||
];
|
||||
|
||||
const domain = computeDomain(stateObj.entity_id);
|
||||
const value = `${pad(time.hours)}:${pad(time.minutes)}:${pad(time.seconds)}`;
|
||||
|
||||
try {
|
||||
if (domain === "datetime") {
|
||||
const dateObj = toZonedDate(stateObj.state, this._timeZone);
|
||||
|
||||
dateObj.setHours(time.hours, time.minutes, time.seconds);
|
||||
|
||||
await setDateTimeValue(
|
||||
this._api.callService,
|
||||
stateObj.entity_id,
|
||||
new Date(dateObj.getTime())
|
||||
);
|
||||
} else if (domain === "input_datetime") {
|
||||
await setInputDateTimeValue(
|
||||
this._api.callService,
|
||||
stateObj.entity_id,
|
||||
value,
|
||||
stateObj.attributes.has_date
|
||||
? stateObj.state.split(" ")[0]
|
||||
: undefined
|
||||
);
|
||||
} else {
|
||||
await setTimeValue(this._api.callService, stateObj.entity_id, value);
|
||||
}
|
||||
} catch {
|
||||
this._unconfirmed = this._unconfirmed.filter(
|
||||
(write) => write.id !== writeId
|
||||
);
|
||||
|
||||
// When the write behind the shown selection fails, show the entity's
|
||||
// time again
|
||||
if (this._selection?.writeId === writeId) {
|
||||
this._selection = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (
|
||||
!this._config ||
|
||||
!this.context ||
|
||||
!this._stateObj ||
|
||||
!this._locale ||
|
||||
!supportsTimeSetCardFeatureFromState(this._stateObj)
|
||||
) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const disabled = [UNAVAILABLE, UNKNOWN].includes(this._stateObj.state);
|
||||
const useAMPM = this._useAmPm(this._locale, this._config.time_format);
|
||||
const time = this._time;
|
||||
|
||||
const hour = time
|
||||
? (useAMPM ? time.hours % 12 || 12 : time.hours).toString()
|
||||
: undefined;
|
||||
|
||||
return html`
|
||||
<ha-control-select-menu
|
||||
?hide-label=${hour !== undefined}
|
||||
.label=${this._localize("ui.card.time.hour")}
|
||||
.value=${hour}
|
||||
.options=${useAMPM ? HOUR_OPTIONS_12 : HOUR_OPTIONS_24}
|
||||
.disabled=${disabled}
|
||||
@wa-select=${this._hourSelected}
|
||||
></ha-control-select-menu>
|
||||
<span class="separator" aria-hidden="true">:</span>
|
||||
<ha-control-select-menu
|
||||
?hide-label=${time !== undefined}
|
||||
.label=${this._localize("ui.card.time.minute")}
|
||||
.value=${time?.minutes.toString()}
|
||||
.options=${MINUTE_OPTIONS}
|
||||
.disabled=${disabled}
|
||||
@wa-select=${this._minuteSelected}
|
||||
></ha-control-select-menu>
|
||||
${
|
||||
useAMPM
|
||||
? html`
|
||||
<ha-control-select-menu
|
||||
?hide-label=${time !== undefined}
|
||||
.label=${this._localize("ui.card.time.period")}
|
||||
.value=${time ? (time.hours >= 12 ? "PM" : "AM") : undefined}
|
||||
.options=${this._periodOptions(this._locale.language)}
|
||||
.disabled=${disabled}
|
||||
@wa-select=${this._periodSelected}
|
||||
></ha-control-select-menu>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = [
|
||||
cardFeatureStyles,
|
||||
css`
|
||||
:host {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-1);
|
||||
/* Times read hour first in every language, like ha-base-time-input */
|
||||
direction: ltr;
|
||||
}
|
||||
ha-control-select-menu {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
/* Leave room for "12" or "PM" when the card is narrow */
|
||||
--control-select-menu-padding: 6px var(--ha-space-1);
|
||||
}
|
||||
.separator {
|
||||
color: var(--secondary-text-color);
|
||||
font-size: var(--ha-font-size-l);
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"hui-time-set-card-feature": HuiTimeSetCardFeature;
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,7 @@ import { supportsSelectOptionsCardFeature } from "./hui-select-options-card-feat
|
||||
import { supportsTemperatureForecastCardFeature } from "./hui-temperature-forecast-card-feature";
|
||||
import { supportsTargetHumidityCardFeature } from "./hui-target-humidity-card-feature";
|
||||
import { supportsTargetTemperatureCardFeature } from "./hui-target-temperature-card-feature";
|
||||
import { supportsTimeSetCardFeature } from "./hui-time-set-card-feature";
|
||||
import { supportsTimerActionsCardFeature } from "./hui-timer-actions-card-feature";
|
||||
import { supportsTimerPresetsCardFeature } from "./hui-timer-presets-card-feature";
|
||||
import { supportsTimerProgressCardFeature } from "./hui-timer-progress-card-feature";
|
||||
@@ -109,6 +110,7 @@ export const UI_FEATURE_TYPES = [
|
||||
"trend-graph",
|
||||
"target-humidity",
|
||||
"target-temperature",
|
||||
"time-set",
|
||||
"timer-actions",
|
||||
"timer-presets",
|
||||
"timer-progress",
|
||||
@@ -169,6 +171,7 @@ export const SUPPORTS_FEATURE_TYPES: Record<UiFeatureType, SupportsFeature> = {
|
||||
"target-humidity": supportsTargetHumidityCardFeature,
|
||||
"target-temperature": supportsTargetTemperatureCardFeature,
|
||||
"temperature-forecast": supportsTemperatureForecastCardFeature,
|
||||
"time-set": supportsTimeSetCardFeature,
|
||||
"timer-actions": supportsTimerActionsCardFeature,
|
||||
"timer-presets": supportsTimerPresetsCardFeature,
|
||||
"timer-progress": supportsTimerProgressCardFeature,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AlarmMode } from "../../../data/alarm_control_panel";
|
||||
import type { HvacMode } from "../../../data/climate";
|
||||
import type { FanSpeedStyle } from "../../../data/fan";
|
||||
import type { TimeFormat } from "../../../data/translation";
|
||||
import type { OperationMode } from "../../../data/water_heater";
|
||||
import type { ForecastPrecipitationType } from "../../../data/weather";
|
||||
|
||||
@@ -213,6 +214,11 @@ export interface TargetTemperatureCardFeatureConfig {
|
||||
style?: "buttons" | "slider";
|
||||
}
|
||||
|
||||
export interface TimeSetCardFeatureConfig {
|
||||
type: "time-set";
|
||||
time_format?: TimeFormat;
|
||||
}
|
||||
|
||||
export interface ToggleCardFeatureConfig {
|
||||
type: "toggle";
|
||||
}
|
||||
@@ -408,6 +414,7 @@ export type LovelaceCardFeatureConfig =
|
||||
| TrendGraphCardFeatureConfig
|
||||
| TargetHumidityCardFeatureConfig
|
||||
| TargetTemperatureCardFeatureConfig
|
||||
| TimeSetCardFeatureConfig
|
||||
| TimerActionsCardFeatureConfig
|
||||
| TimerPresetsCardFeatureConfig
|
||||
| TimerProgressCardFeatureConfig
|
||||
|
||||
@@ -19,6 +19,14 @@ const NUMERIC_INPUT_VARIANTS: TileVariant[] = [TILE_VARIANT, ["numeric-input"]];
|
||||
|
||||
const DATE_VARIANTS: TileVariant[] = [TILE_VARIANT, ["date-set"]];
|
||||
|
||||
const TIME_VARIANTS: TileVariant[] = [TILE_VARIANT, ["time-set"]];
|
||||
|
||||
const DATETIME_VARIANTS: TileVariant[] = [
|
||||
TILE_VARIANT,
|
||||
["date-set"],
|
||||
["time-set"],
|
||||
];
|
||||
|
||||
const BUTTON_VARIANTS: TileVariant[] = [TILE_VARIANT, ["button"]];
|
||||
|
||||
const DOMAIN_VARIANTS: Record<string, TileVariant[]> = {
|
||||
@@ -89,15 +97,16 @@ const DOMAIN_VARIANTS: Record<string, TileVariant[]> = {
|
||||
select: SELECT_VARIANTS,
|
||||
input_number: NUMERIC_INPUT_VARIANTS,
|
||||
number: NUMERIC_INPUT_VARIANTS,
|
||||
input_datetime: DATE_VARIANTS,
|
||||
input_datetime: DATETIME_VARIANTS,
|
||||
date: DATE_VARIANTS,
|
||||
time: TIME_VARIANTS,
|
||||
update: [TILE_VARIANT, ["update-actions"]],
|
||||
water_heater: [
|
||||
TILE_VARIANT,
|
||||
["water-heater-operation-modes"],
|
||||
["target-temperature"],
|
||||
],
|
||||
datetime: DATE_VARIANTS,
|
||||
datetime: DATETIME_VARIANTS,
|
||||
button: BUTTON_VARIANTS,
|
||||
input_button: BUTTON_VARIANTS,
|
||||
scene: BUTTON_VARIANTS,
|
||||
|
||||
@@ -7,13 +7,16 @@ import { computeYAxisFractionDigits } from "../../../../components/chart/y-axis-
|
||||
import type { CustomLegendOption } from "../../../../components/chart/ha-chart-base";
|
||||
import type {
|
||||
DeviceConsumptionEnergyPreference,
|
||||
DeviceConsumptionResource,
|
||||
EnergyData,
|
||||
} from "../../../../data/energy";
|
||||
import {
|
||||
computeConsumptionData,
|
||||
computeEnergyDeviceLabels,
|
||||
energySourcesByType,
|
||||
getSuggestedPeriod,
|
||||
getSummedData,
|
||||
getWaterGasDevices,
|
||||
} from "../../../../data/energy";
|
||||
import type { Statistics } from "../../../../data/recorder";
|
||||
import {
|
||||
@@ -21,7 +24,7 @@ import {
|
||||
isExternalStatistic,
|
||||
} from "../../../../data/recorder";
|
||||
import type { HomeAssistantFormatters } from "../../../../types";
|
||||
import type { EnergyDevicesDetailGraphCardConfig } from "../types";
|
||||
import type { EnergyCardDevicesDetailGraphConfig } from "../types";
|
||||
import {
|
||||
computeStatMidpoint,
|
||||
type EnergyDataPoint,
|
||||
@@ -37,13 +40,15 @@ import type { FrontendLocaleData } from "../../../../data/translation";
|
||||
|
||||
const UNIT = "kWh";
|
||||
export interface EnergyDevicesDetailGraphDataParams {
|
||||
/** Which devices to show and what to measure them against. */
|
||||
resource?: DeviceConsumptionResource;
|
||||
localize: LocalizeFunc;
|
||||
locale: FrontendLocaleData;
|
||||
states: HassEntities;
|
||||
formatEntityName: HomeAssistantFormatters["formatEntityName"];
|
||||
darkMode: boolean;
|
||||
energyData: EnergyData;
|
||||
config: EnergyDevicesDetailGraphCardConfig;
|
||||
config: EnergyCardDevicesDetailGraphConfig;
|
||||
computedStyles: CSSStyleDeclaration;
|
||||
now: Date;
|
||||
/**
|
||||
@@ -59,6 +64,7 @@ export interface EnergyDevicesDetailGraphData {
|
||||
chartData: BarSeriesOption[];
|
||||
yAxisFractionDigits: number;
|
||||
legendData: CustomLegendOption["data"];
|
||||
unit: string;
|
||||
start: Date;
|
||||
end: Date;
|
||||
compareStart?: Date;
|
||||
@@ -73,7 +79,7 @@ const getStatIdFromId = (id: string): string =>
|
||||
interface ProcessContext {
|
||||
localize: LocalizeFunc;
|
||||
darkMode: boolean;
|
||||
config: EnergyDevicesDetailGraphCardConfig;
|
||||
config: EnergyCardDevicesDetailGraphConfig;
|
||||
start: Date;
|
||||
end: Date;
|
||||
compareStart?: Date;
|
||||
@@ -322,12 +328,13 @@ function processUntracked(
|
||||
// entity, so the label isn't clickable, and paired with its compare series.
|
||||
const untrackedLegendItem = (
|
||||
dataset: BarSeriesOption,
|
||||
locale: FrontendLocaleData
|
||||
locale: FrontendLocaleData,
|
||||
unit: string
|
||||
): NonNullable<CustomLegendOption["data"]>[number] => ({
|
||||
id: dataset.id as string,
|
||||
secondaryIds: [`compare-${dataset.id}`],
|
||||
name: dataset.name as string,
|
||||
value: formatSeriesTotal(dataset, locale, UNIT),
|
||||
value: formatSeriesTotal(dataset, locale, unit),
|
||||
itemStyle: {
|
||||
color: dataset.color as string,
|
||||
borderColor: dataset.itemStyle?.borderColor as string,
|
||||
@@ -335,6 +342,31 @@ const untrackedLegendItem = (
|
||||
noLabelClick: true,
|
||||
});
|
||||
|
||||
// Counterpart of computeConsumptionData for gas: the devices are measured
|
||||
// against what their sources used per period.
|
||||
const computeSourceConsumption = (
|
||||
sources: { stat_energy_from: string }[],
|
||||
stats: Statistics,
|
||||
compareStats?: Statistics
|
||||
) => {
|
||||
const usedTotal = (s: Statistics) => {
|
||||
const used_total: Record<number, number> = {};
|
||||
sources.forEach((source) =>
|
||||
s[source.stat_energy_from]?.forEach((point) => {
|
||||
if (point.change != null) {
|
||||
used_total[point.start] =
|
||||
(used_total[point.start] ?? 0) + point.change;
|
||||
}
|
||||
})
|
||||
);
|
||||
return { used_total };
|
||||
};
|
||||
return {
|
||||
consumption: usedTotal(stats),
|
||||
compareConsumption: compareStats && usedTotal(compareStats),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Transforms an `EnergyData` collection update into the ECharts bar series and
|
||||
* derived chart state for `hui-energy-devices-detail-graph-card`. Pure data
|
||||
@@ -346,6 +378,7 @@ export function generateEnergyDevicesDetailGraphData(
|
||||
params: EnergyDevicesDetailGraphDataParams
|
||||
): EnergyDevicesDetailGraphData {
|
||||
const {
|
||||
resource = "electricity",
|
||||
localize,
|
||||
locale,
|
||||
states,
|
||||
@@ -367,7 +400,11 @@ export function generateEnergyDevicesDetailGraphData(
|
||||
const data = energyData.stats;
|
||||
const compareData = energyData.statsCompare;
|
||||
|
||||
const devices = energyData.prefs.device_consumption;
|
||||
const isElectricity = resource === "electricity";
|
||||
const devices = isElectricity
|
||||
? energyData.prefs.device_consumption
|
||||
: getWaterGasDevices(energyData.prefs, resource);
|
||||
const unit = isElectricity ? UNIT : energyData.gasUnit;
|
||||
|
||||
const ctx: ProcessContext = {
|
||||
localize,
|
||||
@@ -394,7 +431,7 @@ export function generateEnergyDevicesDetailGraphData(
|
||||
});
|
||||
|
||||
const growthValues = {};
|
||||
energyData.prefs.device_consumption.forEach((device) => {
|
||||
devices.forEach((device) => {
|
||||
const value =
|
||||
device.stat_consumption in data
|
||||
? calculateStatisticSumGrowth(data[device.stat_consumption]) || 0
|
||||
@@ -403,7 +440,7 @@ export function generateEnergyDevicesDetailGraphData(
|
||||
growthValues[device.stat_consumption] = value;
|
||||
});
|
||||
const growthValuesExChildren = {};
|
||||
energyData.prefs.device_consumption.forEach((device) => {
|
||||
devices.forEach((device) => {
|
||||
growthValuesExChildren[device.stat_consumption] = (
|
||||
childMap[device.stat_consumption] || []
|
||||
).reduce(
|
||||
@@ -412,9 +449,7 @@ export function generateEnergyDevicesDetailGraphData(
|
||||
);
|
||||
});
|
||||
|
||||
const sorted_devices = energyData.prefs.device_consumption.map(
|
||||
(device) => device.stat_consumption
|
||||
);
|
||||
const sorted_devices = devices.map((device) => device.stat_consumption);
|
||||
sorted_devices.sort(
|
||||
(a, b) => growthValuesExChildren[b] - growthValuesExChildren[a]
|
||||
);
|
||||
@@ -430,17 +465,24 @@ export function generateEnergyDevicesDetailGraphData(
|
||||
|
||||
const { summedData, compareSummedData } = getSummedData(energyData);
|
||||
|
||||
const showUntracked =
|
||||
"from_grid" in summedData ||
|
||||
"solar" in summedData ||
|
||||
"from_battery" in summedData ||
|
||||
"home" in summedData;
|
||||
const sources = isElectricity
|
||||
? []
|
||||
: (energySourcesByType(energyData.prefs)[resource] ?? []);
|
||||
|
||||
const showUntracked = isElectricity
|
||||
? "from_grid" in summedData ||
|
||||
"solar" in summedData ||
|
||||
"from_battery" in summedData ||
|
||||
"home" in summedData
|
||||
: sources.length > 0;
|
||||
|
||||
const {
|
||||
consumption: consumptionData,
|
||||
compareConsumption: consumptionCompareData,
|
||||
} = showUntracked
|
||||
? computeConsumptionData(summedData, compareSummedData)
|
||||
? isElectricity
|
||||
? computeConsumptionData(summedData, compareSummedData)
|
||||
: computeSourceConsumption(sources, data, compareData)
|
||||
: { consumption: undefined, compareConsumption: undefined };
|
||||
|
||||
let compareNegativeDataset: BarSeriesOption | undefined;
|
||||
@@ -449,7 +491,7 @@ export function generateEnergyDevicesDetailGraphData(
|
||||
ctx,
|
||||
computedStyles,
|
||||
compareData,
|
||||
energyData.prefs.device_consumption,
|
||||
devices,
|
||||
sorted_devices,
|
||||
childMap,
|
||||
trackY,
|
||||
@@ -491,7 +533,7 @@ export function generateEnergyDevicesDetailGraphData(
|
||||
ctx,
|
||||
computedStyles,
|
||||
data,
|
||||
energyData.prefs.device_consumption,
|
||||
devices,
|
||||
sorted_devices,
|
||||
childMap,
|
||||
trackY
|
||||
@@ -504,7 +546,7 @@ export function generateEnergyDevicesDetailGraphData(
|
||||
id: d.id as string,
|
||||
secondaryIds: [`compare-${d.id}`],
|
||||
name: d.name as string,
|
||||
value: formatSeriesTotal(d, locale, UNIT),
|
||||
value: formatSeriesTotal(d, locale, unit),
|
||||
itemStyle: {
|
||||
color: d.color as string,
|
||||
borderColor: d.itemStyle?.borderColor as string,
|
||||
@@ -523,7 +565,7 @@ export function generateEnergyDevicesDetailGraphData(
|
||||
false
|
||||
);
|
||||
datasets.push(untrackedData);
|
||||
legendData.push(untrackedLegendItem(untrackedData, locale));
|
||||
legendData.push(untrackedLegendItem(untrackedData, locale, unit));
|
||||
|
||||
// Only surface the negative untracked series (and its legend item) when
|
||||
// either the main or compare period actually has negative values, so users
|
||||
@@ -535,7 +577,7 @@ export function generateEnergyDevicesDetailGraphData(
|
||||
datasets.push(negativeDataset);
|
||||
}
|
||||
if (hasNegative || hasCompareNegative) {
|
||||
legendData.push(untrackedLegendItem(negativeDataset, locale));
|
||||
legendData.push(untrackedLegendItem(negativeDataset, locale, unit));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -550,6 +592,7 @@ export function generateEnergyDevicesDetailGraphData(
|
||||
chartData: datasets,
|
||||
yAxisFractionDigits,
|
||||
legendData,
|
||||
unit,
|
||||
start,
|
||||
end,
|
||||
compareStart,
|
||||
|
||||
@@ -19,7 +19,10 @@ import {
|
||||
statesContext,
|
||||
uiContext,
|
||||
} from "../../../../data/context";
|
||||
import type { EnergyData } from "../../../../data/energy";
|
||||
import type {
|
||||
DeviceConsumptionResource,
|
||||
EnergyData,
|
||||
} from "../../../../data/energy";
|
||||
import {
|
||||
computeEnergyStatisticArea,
|
||||
validateEnergyCollectionKey,
|
||||
@@ -38,7 +41,10 @@ import type {
|
||||
HomeAssistantUI,
|
||||
} from "../../../../types";
|
||||
import type { LovelaceCard } from "../../types";
|
||||
import type { EnergyDevicesDetailGraphCardConfig } from "../types";
|
||||
import type {
|
||||
EnergyCardDevicesDetailGraphConfig,
|
||||
GasDevicesDetailGraphCardConfig,
|
||||
} from "../types";
|
||||
import { getCommonOptions } from "./common/energy-chart-options";
|
||||
import { storage } from "../../../../common/decorators/storage";
|
||||
import type { HaECOption } from "../../../../resources/echarts/echarts";
|
||||
@@ -63,13 +69,15 @@ export class HuiEnergyDevicesDetailGraphCard
|
||||
return document.createElement("hui-energy-devices-card-editor");
|
||||
}
|
||||
|
||||
@state() private _config?: EnergyDevicesDetailGraphCardConfig;
|
||||
protected readonly resource: DeviceConsumptionResource = "electricity";
|
||||
|
||||
@state() private _config?: EnergyCardDevicesDetailGraphConfig;
|
||||
|
||||
public static getStubConfig(
|
||||
_hass: HomeAssistant,
|
||||
_entities: string[],
|
||||
_entitiesFill: string[]
|
||||
): EnergyDevicesDetailGraphCardConfig {
|
||||
): EnergyCardDevicesDetailGraphConfig {
|
||||
return {
|
||||
type: "energy-devices-detail-graph",
|
||||
};
|
||||
@@ -77,6 +85,8 @@ export class HuiEnergyDevicesDetailGraphCard
|
||||
|
||||
@state() private _chartData: BarSeriesOption[] = [];
|
||||
|
||||
@state() private _unit = UNIT;
|
||||
|
||||
@state() private _yAxisFractionDigits = 1;
|
||||
|
||||
@state() private _data?: EnergyData;
|
||||
@@ -97,7 +107,7 @@ export class HuiEnergyDevicesDetailGraphCard
|
||||
state: true,
|
||||
subscribe: false,
|
||||
})
|
||||
private _hiddenStats: string[] = [];
|
||||
protected _hiddenStats: string[] = [];
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
@@ -136,7 +146,7 @@ export class HuiEnergyDevicesDetailGraphCard
|
||||
return 3;
|
||||
}
|
||||
|
||||
public setConfig(config: EnergyDevicesDetailGraphCardConfig): void {
|
||||
public setConfig(config: EnergyCardDevicesDetailGraphConfig): void {
|
||||
if (config.collection_key) {
|
||||
validateEnergyCollectionKey(config.collection_key);
|
||||
}
|
||||
@@ -177,7 +187,7 @@ export class HuiEnergyDevicesDetailGraphCard
|
||||
this._end,
|
||||
this._i18n.locale,
|
||||
this._hassConfig,
|
||||
UNIT,
|
||||
this._unit,
|
||||
this._compareStart,
|
||||
this._compareEnd,
|
||||
this._yAxisFractionDigits,
|
||||
@@ -202,8 +212,8 @@ export class HuiEnergyDevicesDetailGraphCard
|
||||
|
||||
private _formatTotal = (total: number) =>
|
||||
this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.energy_usage_graph.total_consumed",
|
||||
{ num: formatNumber(total, this._i18n.locale), unit: UNIT }
|
||||
"ui.panel.lovelace.cards.energy.energy_devices_detail_graph.total_consumed",
|
||||
{ num: formatNumber(total, this._i18n.locale), unit: this._unit }
|
||||
);
|
||||
|
||||
// ha-chart-base will track hidden per ID (so it will have two entries for ID and compare-ID)
|
||||
@@ -320,11 +330,13 @@ export class HuiEnergyDevicesDetailGraphCard
|
||||
chartData,
|
||||
yAxisFractionDigits,
|
||||
legendData,
|
||||
unit,
|
||||
start,
|
||||
end,
|
||||
compareStart,
|
||||
compareEnd,
|
||||
} = generateEnergyDevicesDetailGraphData({
|
||||
resource: this.resource,
|
||||
localize: this._i18n.localize,
|
||||
locale: this._i18n.locale,
|
||||
states: this._states,
|
||||
@@ -342,6 +354,7 @@ export class HuiEnergyDevicesDetailGraphCard
|
||||
this._compareStart = compareStart;
|
||||
this._compareEnd = compareEnd;
|
||||
this._legendData = legendData;
|
||||
this._unit = unit;
|
||||
this._yAxisFractionDigits = yAxisFractionDigits;
|
||||
this._chartData = chartData;
|
||||
}
|
||||
@@ -366,8 +379,29 @@ export class HuiEnergyDevicesDetailGraphCard
|
||||
`;
|
||||
}
|
||||
|
||||
@customElement("hui-gas-devices-detail-graph-card")
|
||||
export class HuiGasDevicesDetailGraphCard extends HuiEnergyDevicesDetailGraphCard {
|
||||
protected readonly resource = "gas";
|
||||
|
||||
// Separate from electricity: the untracked series share their ids
|
||||
@state()
|
||||
@storage({
|
||||
key: "gas-devices-hidden-stats",
|
||||
state: true,
|
||||
subscribe: false,
|
||||
})
|
||||
protected _hiddenStats: string[] = [];
|
||||
|
||||
public static getStubConfig(): GasDevicesDetailGraphCardConfig {
|
||||
return {
|
||||
type: "gas-devices-detail-graph",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"hui-energy-devices-detail-graph-card": HuiEnergyDevicesDetailGraphCard;
|
||||
"hui-gas-devices-detail-graph-card": HuiGasDevicesDetailGraphCard;
|
||||
}
|
||||
}
|
||||
@@ -820,15 +820,14 @@ class HuiWeatherForecastCard extends LitElement implements LovelaceCard {
|
||||
}
|
||||
|
||||
.temp-attribute .temp {
|
||||
position: relative;
|
||||
margin-right: 24px;
|
||||
direction: ltr;
|
||||
}
|
||||
|
||||
.temp-attribute .temp span {
|
||||
position: absolute;
|
||||
position: relative;
|
||||
font-size: var(--ha-font-size-2xl);
|
||||
top: 1px;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.state,
|
||||
@@ -1025,12 +1024,6 @@ class HuiWeatherForecastCard extends LitElement implements LovelaceCard {
|
||||
font-size: var(--ha-font-size-xl);
|
||||
}
|
||||
|
||||
[class*="narrow"] .temp-attribute .temp {
|
||||
margin-right: 16px;
|
||||
margin-inline-end: 16px;
|
||||
margin-inline-start: initial;
|
||||
}
|
||||
|
||||
[class*="narrow"] .temp span {
|
||||
top: 1px;
|
||||
font-size: var(--ha-font-size-l);
|
||||
|
||||
@@ -241,12 +241,19 @@ export interface EnergyDevicesGraphCardConfig extends EnergyCardConfig {
|
||||
expand_legend?: boolean;
|
||||
}
|
||||
|
||||
export interface EnergyDevicesDetailGraphCardConfig extends EnergyCardConfig {
|
||||
type: "energy-devices-detail-graph";
|
||||
export interface EnergyCardDevicesDetailGraphConfig extends EnergyCardConfig {
|
||||
max_devices?: number;
|
||||
expand_legend?: boolean;
|
||||
}
|
||||
|
||||
export interface EnergyDevicesDetailGraphCardConfig extends EnergyCardDevicesDetailGraphConfig {
|
||||
type: "energy-devices-detail-graph";
|
||||
}
|
||||
|
||||
export interface GasDevicesDetailGraphCardConfig extends EnergyCardDevicesDetailGraphConfig {
|
||||
type: "gas-devices-detail-graph";
|
||||
}
|
||||
|
||||
export interface EnergySourcesTableCardConfig extends EnergyCardConfig {
|
||||
type: "energy-sources-table";
|
||||
types?: (keyof EnergySourceByType)[];
|
||||
|
||||
@@ -51,6 +51,8 @@ const LAZY_LOAD_TYPES = {
|
||||
"energy-distribution": () =>
|
||||
import("../cards/energy/hui-energy-distribution-card"),
|
||||
"energy-gas-graph": () => import("../cards/energy/hui-energy-gas-graph-card"),
|
||||
"gas-devices-detail-graph": () =>
|
||||
import("../cards/energy/hui-energy-devices-detail-graph-card"),
|
||||
"gas-sankey": () => import("../cards/water-gas/hui-water-gas-sankey-card"),
|
||||
"gas-flow-sankey": () =>
|
||||
import("../cards/water-gas/hui-water-gas-flow-sankey-card"),
|
||||
|
||||
@@ -36,6 +36,7 @@ import "../card-features/hui-numeric-input-card-feature";
|
||||
import "../card-features/hui-select-options-card-feature";
|
||||
import "../card-features/hui-target-humidity-card-feature";
|
||||
import "../card-features/hui-target-temperature-card-feature";
|
||||
import "../card-features/hui-time-set-card-feature";
|
||||
import "../card-features/hui-timer-actions-card-feature";
|
||||
import "../card-features/hui-timer-presets-card-feature";
|
||||
import "../card-features/hui-timer-progress-card-feature";
|
||||
@@ -103,6 +104,7 @@ const TYPES = new Set<LovelaceCardFeatureConfig["type"]>([
|
||||
"target-humidity",
|
||||
"target-temperature",
|
||||
"temperature-forecast",
|
||||
"time-set",
|
||||
"timer-actions",
|
||||
"timer-presets",
|
||||
"timer-progress",
|
||||
|
||||
@@ -9,6 +9,8 @@ export {
|
||||
showPromptDialog,
|
||||
} from "../../dialogs/generic/show-dialog-box";
|
||||
export { importMoreInfoControl } from "../../dialogs/more-info/state_more_info_control";
|
||||
|
||||
export { subscribeVisibility } from "../../common/condition/subscribe-visibility";
|
||||
export { createBadgeElement } from "./create-element/create-badge-element";
|
||||
export { createCardElement } from "./create-element/create-card-element";
|
||||
export { createHeaderFooterElement } from "./create-element/create-header-footer-element";
|
||||
|
||||
@@ -8,6 +8,7 @@ import deepFreeze from "deep-freeze";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import { ctrlOrCmdLabel } from "../../../../common/keyboard/ctrl-or-cmd";
|
||||
@@ -75,6 +76,8 @@ export class HuiDialogEditBadge
|
||||
|
||||
@state() private _animateWidth = false;
|
||||
|
||||
private _largeBeforeCodeEditor = false;
|
||||
|
||||
@state() private _badgeConfig?: LovelaceBadgeConfig;
|
||||
|
||||
@state() private _saving = false;
|
||||
@@ -99,6 +102,7 @@ export class HuiDialogEditBadge
|
||||
this._badgeConfig = params.badgeConfig;
|
||||
|
||||
this.large = false;
|
||||
this._animateWidth = false;
|
||||
if (this._badgeConfig && !Object.isFrozen(this._badgeConfig)) {
|
||||
this._badgeConfig = deepFreeze(this._badgeConfig);
|
||||
}
|
||||
@@ -202,7 +206,10 @@ export class HuiDialogEditBadge
|
||||
.open=${this._open}
|
||||
.accessibleLabel=${heading}
|
||||
.width=${this.large ? "full" : "large"}
|
||||
class=${this._animateWidth ? "animate-width" : ""}
|
||||
class=${classMap({
|
||||
"animate-width": this._animateWidth,
|
||||
"yaml-mode": !this._GUImode,
|
||||
})}
|
||||
@dialog-set-fullscreen=${this._stopWidthAnimation}
|
||||
.preventScrimClose=${this.isEffectiveDirtyState}
|
||||
@keydown=${this._ignoreKeydown}
|
||||
@@ -345,11 +352,21 @@ export class HuiDialogEditBadge
|
||||
|
||||
private _handleGUIModeChanged(ev: HASSDomEvent<GUIModeChangedEvent>): void {
|
||||
ev.stopPropagation();
|
||||
// Fired again on every error while staying in the same mode
|
||||
if (ev.detail.guiMode !== this._GUImode) {
|
||||
if (ev.detail.guiMode) {
|
||||
this.large = this._largeBeforeCodeEditor;
|
||||
} else {
|
||||
this._largeBeforeCodeEditor = this.large;
|
||||
this.large = true;
|
||||
}
|
||||
}
|
||||
this._GUImode = ev.detail.guiMode;
|
||||
this._guiModeAvailable = ev.detail.guiModeAvailable;
|
||||
}
|
||||
|
||||
private _toggleMode(): void {
|
||||
this._animateWidth = true;
|
||||
withViewTransition(() => {
|
||||
this._badgeEditorEl?.toggleMode();
|
||||
});
|
||||
@@ -513,6 +530,17 @@ export class HuiDialogEditBadge
|
||||
ha-dialog ha-icon-button[slot="headerActionItems"] {
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
@supports (min-height: min(1px, 2px)) {
|
||||
@media (min-width: 1000px) {
|
||||
ha-dialog.yaml-mode {
|
||||
/* Minus the toolbar of the code editor */
|
||||
--code-mirror-min-height: min(
|
||||
500px,
|
||||
var(--code-mirror-max-height, 100vh) - 28px
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
ha-dialog.animate-width {
|
||||
--ha-dialog-width-transition:
|
||||
min-width var(--ha-animation-duration-normal) ease-out,
|
||||
|
||||
@@ -8,6 +8,7 @@ import deepFreeze from "deep-freeze";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
@@ -83,6 +84,8 @@ export class HuiDialogEditCard
|
||||
|
||||
@state() private _animateWidth = false;
|
||||
|
||||
private _largeBeforeCodeEditor = false;
|
||||
|
||||
@state() private _cardConfig?: LovelaceCardConfig;
|
||||
|
||||
@state() private _sectionConfig?: LovelaceSectionConfig;
|
||||
@@ -111,6 +114,7 @@ export class HuiDialogEditCard
|
||||
this._cardConfig = params.cardConfig;
|
||||
|
||||
this.large = false;
|
||||
this._animateWidth = false;
|
||||
if (this._cardConfig && !Object.isFrozen(this._cardConfig)) {
|
||||
this._cardConfig = deepFreeze(this._cardConfig);
|
||||
}
|
||||
@@ -214,7 +218,10 @@ export class HuiDialogEditCard
|
||||
.open=${this._open}
|
||||
.accessibleLabel=${heading}
|
||||
.width=${this.large ? "full" : "large"}
|
||||
class=${this._animateWidth ? "animate-width" : ""}
|
||||
class=${classMap({
|
||||
"animate-width": this._animateWidth,
|
||||
"yaml-mode": !this._GUImode,
|
||||
})}
|
||||
@dialog-set-fullscreen=${this._stopWidthAnimation}
|
||||
.preventScrimClose=${this.isEffectiveDirtyState}
|
||||
@keydown=${this._ignoreKeydown}
|
||||
@@ -371,11 +378,21 @@ export class HuiDialogEditCard
|
||||
|
||||
private _handleGUIModeChanged(ev: HASSDomEvent<GUIModeChangedEvent>): void {
|
||||
ev.stopPropagation();
|
||||
// Fired again on every error while staying in the same mode
|
||||
if (ev.detail.guiMode !== this._GUImode) {
|
||||
if (ev.detail.guiMode) {
|
||||
this.large = this._largeBeforeCodeEditor;
|
||||
} else {
|
||||
this._largeBeforeCodeEditor = this.large;
|
||||
this.large = true;
|
||||
}
|
||||
}
|
||||
this._GUImode = ev.detail.guiMode;
|
||||
this._guiModeAvailable = ev.detail.guiModeAvailable;
|
||||
}
|
||||
|
||||
private _toggleMode(): void {
|
||||
this._animateWidth = true;
|
||||
withViewTransition(() => {
|
||||
this._cardEditorEl?.toggleMode();
|
||||
});
|
||||
@@ -595,6 +612,17 @@ export class HuiDialogEditCard
|
||||
ha-dialog ha-icon-button[slot="headerActionItems"] {
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
@supports (min-height: min(1px, 2px)) {
|
||||
@media (min-width: 1000px) {
|
||||
ha-dialog.yaml-mode {
|
||||
/* Minus the toolbar of the code editor */
|
||||
--code-mirror-min-height: min(
|
||||
500px,
|
||||
var(--code-mirror-max-height, 100vh) - 28px
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
ha-dialog.animate-width {
|
||||
--ha-dialog-width-transition:
|
||||
min-width var(--ha-animation-duration-normal) ease-out,
|
||||
|
||||
@@ -236,6 +236,8 @@ export class HaCardConditionEditor extends LitElement {
|
||||
|
||||
@property({ type: Boolean }) public last = false;
|
||||
|
||||
@property({ type: Boolean, reflect: true }) public disabled = false;
|
||||
|
||||
@property({ attribute: false }) public sortableData?: VisibilityCondition;
|
||||
|
||||
@state()
|
||||
@@ -539,79 +541,7 @@ export class HaCardConditionEditor extends LitElement {
|
||||
}
|
||||
</ha-automation-row-event-chip>
|
||||
<slot name="drag-handle" slot="icons"></slot>
|
||||
<ha-dropdown
|
||||
slot="icons"
|
||||
@wa-select=${this._handleAction}
|
||||
@click=${stopPropagation}
|
||||
placement="bottom-end"
|
||||
>
|
||||
<ha-icon-button
|
||||
slot="trigger"
|
||||
.label=${this.hass.localize("ui.common.menu")}
|
||||
.path=${mdiDotsVertical}
|
||||
>
|
||||
</ha-icon-button>
|
||||
|
||||
${
|
||||
hideLiveTest
|
||||
? nothing
|
||||
: html`<ha-dropdown-item value="test">
|
||||
${this.hass.localize(
|
||||
"ui.panel.lovelace.editor.condition-editor.test"
|
||||
)}
|
||||
<ha-svg-icon slot="icon" .path=${mdiFlask}></ha-svg-icon>
|
||||
</ha-dropdown-item>`
|
||||
}
|
||||
|
||||
<ha-dropdown-item value="duplicate">
|
||||
${this.hass.localize(
|
||||
"ui.panel.lovelace.editor.edit_card.duplicate"
|
||||
)}
|
||||
<ha-svg-icon
|
||||
slot="icon"
|
||||
.path=${mdiContentDuplicate}
|
||||
></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
|
||||
<ha-dropdown-item value="copy">
|
||||
${this.hass.localize("ui.panel.lovelace.editor.edit_card.copy")}
|
||||
<ha-svg-icon slot="icon" .path=${mdiContentCopy}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
|
||||
<ha-dropdown-item value="cut">
|
||||
${this.hass.localize("ui.panel.lovelace.editor.edit_card.cut")}
|
||||
<ha-svg-icon slot="icon" .path=${mdiContentCut}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
|
||||
<ha-dropdown-item value="move_up" .disabled=${this.first}>
|
||||
${this.hass.localize("ui.panel.config.automation.editor.move_up")}
|
||||
<ha-svg-icon slot="icon" .path=${mdiArrowUp}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
|
||||
<ha-dropdown-item value="move_down" .disabled=${this.last}>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.automation.editor.move_down"
|
||||
)}
|
||||
<ha-svg-icon slot="icon" .path=${mdiArrowDown}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
|
||||
<ha-dropdown-item
|
||||
value="toggle_yaml"
|
||||
.disabled=${!this._uiAvailable}
|
||||
>
|
||||
${this.hass.localize(
|
||||
`ui.panel.lovelace.editor.edit_view.edit_${!this._yamlMode ? "yaml" : "ui"}`
|
||||
)}
|
||||
<ha-svg-icon slot="icon" .path=${mdiPlaylistEdit}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
|
||||
<wa-divider></wa-divider>
|
||||
|
||||
<ha-dropdown-item variant="danger" value="delete">
|
||||
${this.hass!.localize("ui.common.delete")}
|
||||
<ha-svg-icon slot="icon" .path=${mdiDelete}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
</ha-dropdown>
|
||||
${this.disabled ? nothing : this._renderMenu(hideLiveTest)}
|
||||
${
|
||||
!this._uiAvailable
|
||||
? html`
|
||||
@@ -646,6 +576,7 @@ export class HaCardConditionEditor extends LitElement {
|
||||
? html`
|
||||
<ha-yaml-editor
|
||||
.defaultValue=${this.condition}
|
||||
.readOnly=${this.disabled}
|
||||
@value-changed=${this._onYamlChange}
|
||||
></ha-yaml-editor>
|
||||
`
|
||||
@@ -655,6 +586,7 @@ export class HaCardConditionEditor extends LitElement {
|
||||
.hass=${this.hass}
|
||||
.condition=${condition}
|
||||
.uiSupported=${true}
|
||||
.disabled=${this.disabled}
|
||||
@ui-mode-not-available=${this._handleUiModeNotAvailable}
|
||||
></ha-automation-condition-editor>
|
||||
`
|
||||
@@ -667,6 +599,7 @@ export class HaCardConditionEditor extends LitElement {
|
||||
{
|
||||
hass: this.hass,
|
||||
condition: condition,
|
||||
disabled: this.disabled,
|
||||
}
|
||||
)}
|
||||
`
|
||||
@@ -677,6 +610,74 @@ export class HaCardConditionEditor extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderMenu(hideLiveTest: boolean) {
|
||||
return html`
|
||||
<ha-dropdown
|
||||
slot="icons"
|
||||
@wa-select=${this._handleAction}
|
||||
@click=${stopPropagation}
|
||||
placement="bottom-end"
|
||||
>
|
||||
<ha-icon-button
|
||||
slot="trigger"
|
||||
.label=${this.hass.localize("ui.common.menu")}
|
||||
.path=${mdiDotsVertical}
|
||||
>
|
||||
</ha-icon-button>
|
||||
|
||||
${
|
||||
hideLiveTest
|
||||
? nothing
|
||||
: html`<ha-dropdown-item value="test">
|
||||
${this.hass.localize(
|
||||
"ui.panel.lovelace.editor.condition-editor.test"
|
||||
)}
|
||||
<ha-svg-icon slot="icon" .path=${mdiFlask}></ha-svg-icon>
|
||||
</ha-dropdown-item>`
|
||||
}
|
||||
|
||||
<ha-dropdown-item value="duplicate">
|
||||
${this.hass.localize("ui.panel.lovelace.editor.edit_card.duplicate")}
|
||||
<ha-svg-icon slot="icon" .path=${mdiContentDuplicate}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
|
||||
<ha-dropdown-item value="copy">
|
||||
${this.hass.localize("ui.panel.lovelace.editor.edit_card.copy")}
|
||||
<ha-svg-icon slot="icon" .path=${mdiContentCopy}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
|
||||
<ha-dropdown-item value="cut">
|
||||
${this.hass.localize("ui.panel.lovelace.editor.edit_card.cut")}
|
||||
<ha-svg-icon slot="icon" .path=${mdiContentCut}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
|
||||
<ha-dropdown-item value="move_up" .disabled=${this.first}>
|
||||
${this.hass.localize("ui.panel.config.automation.editor.move_up")}
|
||||
<ha-svg-icon slot="icon" .path=${mdiArrowUp}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
|
||||
<ha-dropdown-item value="move_down" .disabled=${this.last}>
|
||||
${this.hass.localize("ui.panel.config.automation.editor.move_down")}
|
||||
<ha-svg-icon slot="icon" .path=${mdiArrowDown}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
|
||||
<ha-dropdown-item value="toggle_yaml" .disabled=${!this._uiAvailable}>
|
||||
${this.hass.localize(
|
||||
`ui.panel.lovelace.editor.edit_view.edit_${!this._yamlMode ? "yaml" : "ui"}`
|
||||
)}
|
||||
<ha-svg-icon slot="icon" .path=${mdiPlaylistEdit}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
|
||||
<wa-divider></wa-divider>
|
||||
|
||||
<ha-dropdown-item variant="danger" value="delete">
|
||||
${this.hass!.localize("ui.common.delete")}
|
||||
<ha-svg-icon slot="icon" .path=${mdiDelete}></ha-svg-icon>
|
||||
</ha-dropdown-item>
|
||||
</ha-dropdown>
|
||||
`;
|
||||
}
|
||||
|
||||
private _handleAction(ev: HaDropdownSelectEvent) {
|
||||
const action = ev.detail.item.value;
|
||||
|
||||
@@ -788,6 +789,14 @@ export class HaCardConditionEditor extends LitElement {
|
||||
color: var(--secondary-text-color);
|
||||
opacity: 0.9;
|
||||
}
|
||||
:host([disabled]) ha-expansion-panel::part(summary) {
|
||||
color: var(--ha-color-text-disabled);
|
||||
}
|
||||
:host([disabled]) .icon-badge-wrapper,
|
||||
:host([disabled]) ha-automation-condition-summary {
|
||||
color: var(--ha-color-text-disabled);
|
||||
opacity: 0.8;
|
||||
}
|
||||
.content {
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
@@ -75,6 +75,8 @@ export class HaCardConditionsEditor extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public conditions!: VisibilityCondition[];
|
||||
|
||||
@property({ type: Boolean }) public disabled = false;
|
||||
|
||||
@state()
|
||||
@consume({ context: conditionsEntityContext, subscribe: true })
|
||||
private _entityContext?: ConditionsEntityContext;
|
||||
@@ -152,6 +154,7 @@ export class HaCardConditionsEditor extends LitElement {
|
||||
<ha-sortable
|
||||
handle-selector=".handle"
|
||||
draggable-selector="ha-card-condition-editor"
|
||||
.disabled=${this.disabled}
|
||||
group="lovelace-conditions"
|
||||
invert-swap
|
||||
@item-moved=${this._conditionMoved}
|
||||
@@ -174,28 +177,19 @@ export class HaCardConditionsEditor extends LitElement {
|
||||
@value-changed=${this._conditionChanged}
|
||||
.hass=${this.hass}
|
||||
.condition=${cond}
|
||||
.disabled=${this.disabled}
|
||||
>
|
||||
<div
|
||||
slot="drag-handle"
|
||||
class="handle ${
|
||||
this._rowSortSelected === idx ? "active" : ""
|
||||
}"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
aria-label=${this.hass.localize("ui.common.move")}
|
||||
aria-pressed=${this._rowSortSelected === idx}
|
||||
.index=${idx}
|
||||
@click=${this._handleDragClick}
|
||||
@keydown=${this._handleDragKeydown}
|
||||
>
|
||||
<ha-svg-icon .path=${mdiDragHorizontalVariant}></ha-svg-icon>
|
||||
</div>
|
||||
${this.disabled ? nothing : this._renderDragHandle(idx)}
|
||||
</ha-card-condition-editor>
|
||||
`
|
||||
)}
|
||||
<div>
|
||||
<ha-dropdown @wa-select=${this._addCondition}>
|
||||
<ha-button slot="trigger" appearance="filled">
|
||||
<ha-button
|
||||
slot="trigger"
|
||||
appearance="filled"
|
||||
.disabled=${this.disabled}
|
||||
>
|
||||
<ha-svg-icon .path=${mdiPlus} slot="start"></ha-svg-icon>
|
||||
${this.hass.localize(
|
||||
"ui.panel.lovelace.editor.condition-editor.add"
|
||||
@@ -238,6 +232,24 @@ export class HaCardConditionsEditor extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderDragHandle(idx: number) {
|
||||
return html`
|
||||
<div
|
||||
slot="drag-handle"
|
||||
class="handle ${this._rowSortSelected === idx ? "active" : ""}"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
aria-label=${this.hass.localize("ui.common.move")}
|
||||
aria-pressed=${this._rowSortSelected === idx}
|
||||
.index=${idx}
|
||||
@click=${this._handleDragClick}
|
||||
@keydown=${this._handleDragKeydown}
|
||||
>
|
||||
<ha-svg-icon .path=${mdiDragHorizontalVariant}></ha-svg-icon>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private _move(oldIndex: number, newIndex: number) {
|
||||
const conditions = [...this.conditions];
|
||||
const condition = conditions.splice(oldIndex, 1)[0];
|
||||
|
||||
@@ -38,6 +38,7 @@ export class HaCardConditionNumericAnd extends LitElement {
|
||||
nested
|
||||
.hass=${this.hass}
|
||||
.conditions=${this.condition.conditions}
|
||||
.disabled=${this.disabled}
|
||||
@value-changed=${this._valueChanged}
|
||||
>
|
||||
</ha-card-conditions-editor>
|
||||
|
||||
@@ -38,6 +38,7 @@ export class HaCardConditionNot extends LitElement {
|
||||
nested
|
||||
.hass=${this.hass}
|
||||
.conditions=${this.condition.conditions}
|
||||
.disabled=${this.disabled}
|
||||
@value-changed=${this._valueChanged}
|
||||
>
|
||||
</ha-card-conditions-editor>
|
||||
|
||||
@@ -38,6 +38,7 @@ export class HaCardConditionOr extends LitElement {
|
||||
nested
|
||||
.hass=${this.hass}
|
||||
.conditions=${this.condition.conditions}
|
||||
.disabled=${this.disabled}
|
||||
@value-changed=${this._valueChanged}
|
||||
>
|
||||
</ha-card-conditions-editor>
|
||||
|
||||
@@ -77,6 +77,7 @@ export class HaCardConditionUser extends LitElement {
|
||||
selection-position="end"
|
||||
.value=${user.id}
|
||||
.selected=${selectedUsers.includes(user.id)}
|
||||
.disabled=${this.disabled}
|
||||
>
|
||||
<ha-user-badge slot="start" .user=${user}></ha-user-badge>
|
||||
<span slot="headline">${user.name}</span>
|
||||
|
||||
@@ -65,6 +65,7 @@ import { supportsNumericInputCardFeature } from "../../card-features/hui-numeric
|
||||
import { supportsSelectOptionsCardFeature } from "../../card-features/hui-select-options-card-feature";
|
||||
import { supportsTargetHumidityCardFeature } from "../../card-features/hui-target-humidity-card-feature";
|
||||
import { supportsTargetTemperatureCardFeature } from "../../card-features/hui-target-temperature-card-feature";
|
||||
import { supportsTimeSetCardFeature } from "../../card-features/hui-time-set-card-feature";
|
||||
import { supportsTimerActionsCardFeature } from "../../card-features/hui-timer-actions-card-feature";
|
||||
import { supportsTimerPresetsCardFeature } from "../../card-features/hui-timer-presets-card-feature";
|
||||
import { supportsTimerProgressCardFeature } from "../../card-features/hui-timer-progress-card-feature";
|
||||
@@ -135,6 +136,7 @@ const UI_FEATURE_TYPES = [
|
||||
"target-humidity",
|
||||
"target-temperature",
|
||||
"temperature-forecast",
|
||||
"time-set",
|
||||
"timer-actions",
|
||||
"timer-presets",
|
||||
"timer-progress",
|
||||
@@ -181,6 +183,7 @@ const EDITABLES_FEATURE_TYPES = new Set<UiFeatureTypes>([
|
||||
"select-options",
|
||||
"target-humidity",
|
||||
"target-temperature",
|
||||
"time-set",
|
||||
"timer-actions",
|
||||
"timer-presets",
|
||||
"trend-graph",
|
||||
@@ -239,6 +242,7 @@ const SUPPORTS_FEATURE_TYPES: Record<
|
||||
"target-humidity": supportsTargetHumidityCardFeature,
|
||||
"target-temperature": supportsTargetTemperatureCardFeature,
|
||||
"temperature-forecast": supportsTemperatureForecastCardFeature,
|
||||
"time-set": supportsTimeSetCardFeature,
|
||||
"timer-actions": supportsTimerActionsCardFeature,
|
||||
"timer-presets": supportsTimerPresetsCardFeature,
|
||||
"timer-progress": supportsTimerProgressCardFeature,
|
||||
|
||||
@@ -63,10 +63,6 @@ const cardConfigStruct = assign(
|
||||
})
|
||||
);
|
||||
|
||||
type ClockCardFormData = Omit<ClockCardConfig, "time_format"> & {
|
||||
time_format?: ClockCardConfig["time_format"] | "auto";
|
||||
};
|
||||
|
||||
@customElement("hui-clock-card-editor")
|
||||
export class HuiClockCardEditor
|
||||
extends LitElement
|
||||
@@ -125,15 +121,7 @@ export class HuiClockCardEditor
|
||||
value: "digital",
|
||||
},
|
||||
selector: {
|
||||
select: {
|
||||
mode: "dropdown",
|
||||
options: ["auto", ...Object.values(TimeFormat)].map((value) => ({
|
||||
value,
|
||||
label: localize(
|
||||
`ui.panel.lovelace.editor.card.clock.time_formats.${value}`
|
||||
),
|
||||
})),
|
||||
},
|
||||
ui_clock_time_format: {},
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -231,14 +219,13 @@ export class HuiClockCardEditor
|
||||
] as const satisfies readonly HaFormSchema[]
|
||||
);
|
||||
|
||||
private _data = memoizeOne((config: ClockCardConfig): ClockCardFormData => {
|
||||
private _data = memoizeOne((config: ClockCardConfig): ClockCardConfig => {
|
||||
const dateConfig = getClockCardDateConfig(config);
|
||||
|
||||
const data: ClockCardFormData = {
|
||||
const data: ClockCardConfig = {
|
||||
...config,
|
||||
clock_style: config.clock_style ?? "digital",
|
||||
clock_size: config.clock_size ?? "small",
|
||||
time_format: config.time_format ?? "auto",
|
||||
show_seconds: config.show_seconds ?? false,
|
||||
no_background: config.no_background ?? false,
|
||||
// Analog clock options
|
||||
@@ -275,14 +262,14 @@ export class HuiClockCardEditor
|
||||
`;
|
||||
}
|
||||
|
||||
private _valueChanged(ev: ValueChangedEvent<ClockCardFormData>): void {
|
||||
private _valueChanged(ev: ValueChangedEvent<ClockCardConfig>): void {
|
||||
const config = ev.detail.value;
|
||||
|
||||
if (!config.date_format || config.date_format.length === 0) {
|
||||
delete config.date_format;
|
||||
}
|
||||
|
||||
if (config.time_format === "auto") {
|
||||
if (!config.time_format) {
|
||||
delete config.time_format;
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import type {
|
||||
EnergyCardConfig,
|
||||
EnergyDevicesDetailGraphCardConfig,
|
||||
EnergyDevicesGraphCardConfig,
|
||||
GasDevicesDetailGraphCardConfig,
|
||||
} from "../../cards/types";
|
||||
import type { LovelaceCardEditor } from "../../types";
|
||||
import { baseLovelaceCardConfig } from "../structs/base-card-struct";
|
||||
@@ -37,6 +38,7 @@ const cardConfigStruct = assign(
|
||||
type: union([
|
||||
literal("energy-devices-graph"),
|
||||
literal("energy-devices-detail-graph"),
|
||||
literal("gas-devices-detail-graph"),
|
||||
]),
|
||||
title: optional(string()),
|
||||
collection_key: optional(string()),
|
||||
@@ -52,7 +54,8 @@ const chartModeOpts = ["bar", "pie"] as const;
|
||||
type EnergyDevicesCardConfig =
|
||||
| EnergyCardConfig
|
||||
| EnergyDevicesGraphCardConfig
|
||||
| EnergyDevicesDetailGraphCardConfig;
|
||||
| EnergyDevicesDetailGraphCardConfig
|
||||
| GasDevicesDetailGraphCardConfig;
|
||||
@customElement("hui-energy-devices-card-editor")
|
||||
export class HuiEnergyDevicesCardEditor
|
||||
extends LitElement
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import "../../../../components/ha-form/ha-form";
|
||||
import type {
|
||||
HaFormSchema,
|
||||
SchemaUnion,
|
||||
} from "../../../../components/ha-form/types";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
|
||||
import type {
|
||||
LovelaceCardFeatureContext,
|
||||
TimeSetCardFeatureConfig,
|
||||
} from "../../card-features/types";
|
||||
import type { LovelaceCardFeatureEditor } from "../../types";
|
||||
|
||||
const SCHEMA = [
|
||||
{
|
||||
name: "time_format",
|
||||
selector: {
|
||||
ui_clock_time_format: {},
|
||||
},
|
||||
},
|
||||
] as const satisfies readonly HaFormSchema[];
|
||||
|
||||
@customElement("hui-time-set-card-feature-editor")
|
||||
export class HuiTimeSetCardFeatureEditor
|
||||
extends LitElement
|
||||
implements LovelaceCardFeatureEditor
|
||||
{
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
|
||||
|
||||
@state() private _config?: TimeSetCardFeatureConfig;
|
||||
|
||||
public setConfig(config: TimeSetCardFeatureConfig): void {
|
||||
this._config = config;
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this._config) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${this._config}
|
||||
.schema=${SCHEMA}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
@value-changed=${this._valueChanged}
|
||||
></ha-form>
|
||||
`;
|
||||
}
|
||||
|
||||
private _valueChanged(ev: ValueChangedEvent<TimeSetCardFeatureConfig>) {
|
||||
const { time_format, ...rest } = ev.detail.value;
|
||||
|
||||
const config: TimeSetCardFeatureConfig = time_format
|
||||
? { ...rest, time_format }
|
||||
: rest;
|
||||
|
||||
fireEvent(this, "config-changed", { config });
|
||||
}
|
||||
|
||||
private _computeLabelCallback = (schema: SchemaUnion<typeof SCHEMA>) =>
|
||||
this.hass!.localize(
|
||||
`ui.panel.lovelace.editor.features.types.time-set.${schema.name}`
|
||||
);
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"hui-time-set-card-feature-editor": HuiTimeSetCardFeatureEditor;
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ const NON_STANDARD_CARD_URLS = {
|
||||
"power-sankey": "energy/#power-flow-sankey-graph",
|
||||
"water-sankey": "energy/#water-sankey-graph",
|
||||
"water-flow-sankey": "energy/#water-flow-sankey-graph",
|
||||
"gas-devices-detail-graph": "energy/#gas-devices-detail-graph",
|
||||
"gas-sankey": "energy/#gas-sankey-graph",
|
||||
"gas-flow-sankey": "energy/#gas-flow-sankey-graph",
|
||||
"power-sources-graph": "energy/#power-sources-graph",
|
||||
|
||||
@@ -211,6 +211,10 @@ export const energyCards: Card[] = [
|
||||
type: "water-flow-sankey",
|
||||
showElement: false,
|
||||
},
|
||||
{
|
||||
type: "gas-devices-detail-graph",
|
||||
showElement: false,
|
||||
},
|
||||
{
|
||||
type: "gas-sankey",
|
||||
showElement: false,
|
||||
|
||||
@@ -264,8 +264,11 @@ export class HuiDialogEditSection
|
||||
<ha-dialog
|
||||
.open=${this._open}
|
||||
.accessibleLabel=${heading}
|
||||
width="large"
|
||||
class=${this._animateWidth ? "animate-width" : ""}
|
||||
.width=${this._yamlMode ? "full" : "large"}
|
||||
class=${classMap({
|
||||
"animate-width": this._animateWidth,
|
||||
"yaml-mode": this._yamlMode,
|
||||
})}
|
||||
style=${styleMap({ "--preview-column-span": previewColumnSpan })}
|
||||
@dialog-set-fullscreen=${this._stopWidthAnimation}
|
||||
.preventScrimClose=${this.isDirtyState}
|
||||
@@ -529,6 +532,7 @@ export class HuiDialogEditSection
|
||||
|
||||
private async _toggleMode(): Promise<void> {
|
||||
if (this._yamlMode && this._yamlError) return;
|
||||
this._animateWidth = true;
|
||||
await withViewTransition(() => {
|
||||
this._yamlMode = !this._yamlMode;
|
||||
});
|
||||
@@ -750,6 +754,17 @@ export class HuiDialogEditSection
|
||||
);
|
||||
}
|
||||
|
||||
@supports (min-height: min(1px, 2px)) {
|
||||
@media (min-width: 1000px) {
|
||||
ha-dialog.yaml-mode {
|
||||
/* Minus the toolbar of the code editor */
|
||||
--code-mirror-min-height: min(
|
||||
500px,
|
||||
var(--code-mirror-max-height, 100vh) - 28px
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
ha-dialog.animate-width {
|
||||
--ha-dialog-width-transition:
|
||||
min-width var(--ha-animation-duration-normal) ease-out,
|
||||
@@ -836,10 +851,11 @@ export class HuiDialogEditSection
|
||||
@media (min-width: 1000px) {
|
||||
ha-dialog {
|
||||
--editor-column-width: 520px;
|
||||
/* Plus the paddings of the preview and the dialog */
|
||||
/* Plus the paddings of the preview */
|
||||
--preview-column-total-width: calc(var(--preview-width) + 28px);
|
||||
--ha-dialog-width-lg: calc(
|
||||
var(--editor-column-width) + var(--preview-width) + 28px + 2 *
|
||||
var(--dialog-content-padding)
|
||||
var(--editor-column-width) + var(--preview-column-total-width) +
|
||||
2 * var(--dialog-content-padding)
|
||||
);
|
||||
}
|
||||
.content {
|
||||
@@ -854,6 +870,13 @@ export class HuiDialogEditSection
|
||||
.content > .element-preview {
|
||||
flex: 1 1 0;
|
||||
}
|
||||
ha-dialog.yaml-mode .content > .element-editor {
|
||||
flex: 1 0 var(--editor-column-width);
|
||||
}
|
||||
ha-dialog.yaml-mode .content > .element-preview {
|
||||
box-sizing: border-box;
|
||||
flex: 0 1 var(--preview-column-total-width);
|
||||
}
|
||||
.content > .element-editor,
|
||||
.content > .element-preview {
|
||||
min-width: 0;
|
||||
|
||||
@@ -90,6 +90,8 @@ export class HuiDialogEditView extends DirtyStateProviderMixin<LovelaceViewConfi
|
||||
|
||||
@state() private _open = false;
|
||||
|
||||
@state() private _animateWidth = false;
|
||||
|
||||
get _type(): string {
|
||||
return getViewType(this._config);
|
||||
}
|
||||
@@ -136,6 +138,7 @@ export class HuiDialogEditView extends DirtyStateProviderMixin<LovelaceViewConfi
|
||||
this._params = undefined;
|
||||
this._config = {};
|
||||
this._yamlMode = false;
|
||||
this._animateWidth = false;
|
||||
this._currTab = TABS[0];
|
||||
fireEvent(this, "dialog-closed", { dialog: this.localName });
|
||||
}
|
||||
@@ -210,10 +213,12 @@ export class HuiDialogEditView extends DirtyStateProviderMixin<LovelaceViewConfi
|
||||
<ha-dialog
|
||||
.open=${this._open}
|
||||
.accessibleLabel=${this._viewConfigTitle}
|
||||
width="large"
|
||||
.width=${this._yamlMode ? "full" : "large"}
|
||||
.preventScrimClose=${this.isDirtyState}
|
||||
@closed=${this._dialogClosed}
|
||||
@dialog-set-fullscreen=${this._stopWidthAnimation}
|
||||
class=${classMap({
|
||||
"animate-width": this._animateWidth,
|
||||
"yaml-mode": this._yamlMode,
|
||||
})}
|
||||
>
|
||||
@@ -365,7 +370,13 @@ export class HuiDialogEditView extends DirtyStateProviderMixin<LovelaceViewConfi
|
||||
}
|
||||
}
|
||||
|
||||
// The code editor's fullscreen changes the height at once, so the width must not lag behind
|
||||
private _stopWidthAnimation() {
|
||||
this._animateWidth = false;
|
||||
}
|
||||
|
||||
private async _toggleMode() {
|
||||
this._animateWidth = true;
|
||||
this._yamlMode = !this._yamlMode;
|
||||
if (this._yamlMode) {
|
||||
await this.updateComplete;
|
||||
@@ -680,6 +691,29 @@ export class HuiDialogEditView extends DirtyStateProviderMixin<LovelaceViewConfi
|
||||
ha-dialog.yaml-mode {
|
||||
--dialog-content-padding: 0;
|
||||
}
|
||||
@media (min-width: 1000px) {
|
||||
ha-dialog.yaml-mode {
|
||||
/* 80px - margin of the dialog
|
||||
137px - header and footer */
|
||||
--code-mirror-max-height: calc(100vh - 217px);
|
||||
}
|
||||
}
|
||||
@supports (min-height: min(1px, 2px)) {
|
||||
@media (min-width: 1000px) {
|
||||
ha-dialog.yaml-mode {
|
||||
/* Minus the toolbar of the code editor */
|
||||
--code-mirror-min-height: min(
|
||||
500px,
|
||||
var(--code-mirror-max-height, 100vh) - 28px
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
ha-dialog.animate-width {
|
||||
--ha-dialog-width-transition:
|
||||
min-width var(--ha-animation-duration-normal) ease-out,
|
||||
max-width var(--ha-animation-duration-normal) ease-out;
|
||||
}
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: inherit;
|
||||
|
||||
@@ -305,6 +305,11 @@ export const haTheme = EditorView.theme({
|
||||
|
||||
".cm-scroller": { outline: "none" },
|
||||
|
||||
// On these instead of the editor, so that the gutter grows along
|
||||
".cm-content, .cm-gutter": {
|
||||
minHeight: "var(--code-mirror-min-height, 100%)",
|
||||
},
|
||||
|
||||
".cm-content": {
|
||||
caretColor: "var(--secondary-text-color)",
|
||||
paddingTop: "16px",
|
||||
|
||||
@@ -340,6 +340,11 @@
|
||||
"text": {
|
||||
"empty_value": "(empty value)"
|
||||
},
|
||||
"time": {
|
||||
"hour": "Hour",
|
||||
"minute": "Minute",
|
||||
"period": "AM or PM"
|
||||
},
|
||||
"timer": {
|
||||
"actions": {
|
||||
"start": "Start",
|
||||
@@ -948,6 +953,15 @@
|
||||
},
|
||||
"style": "Time format style"
|
||||
},
|
||||
"clock-time-format-picker": {
|
||||
"auto": "Use user settings",
|
||||
"formats": {
|
||||
"language": "[%key:ui::panel::profile::time_format::formats::language%]",
|
||||
"system": "[%key:ui::panel::profile::time_format::formats::system%]",
|
||||
"24": "[%key:ui::panel::profile::time_format::formats::24%]",
|
||||
"12": "[%key:ui::panel::profile::time_format::formats::12%]"
|
||||
}
|
||||
},
|
||||
"filter-entity-types": {
|
||||
"caption": "Type",
|
||||
"no_device_class": "No type",
|
||||
@@ -2017,6 +2031,7 @@
|
||||
"logbook": "Activity",
|
||||
"device_info": "[%key:ui::panel::config::devices::device_info_heading%]",
|
||||
"service_info": "[%key:ui::panel::config::devices::service_info_heading%]",
|
||||
"directions": "[%key:ui::panel::lovelace::cards::map::overview::directions%]",
|
||||
"last_changed": "Last changed",
|
||||
"last_updated": "Last updated",
|
||||
"show_more": "Show more",
|
||||
@@ -7136,6 +7151,9 @@
|
||||
"community_forums": "View blueprints on the community forums",
|
||||
"url": "Blueprint address",
|
||||
"raw_blueprint": "Blueprint content",
|
||||
"raw_blueprint_description": "Check the code before you import it.",
|
||||
"view_raw_blueprint": "View",
|
||||
"view_raw_blueprint_label": "View blueprint content",
|
||||
"importing": "Loading blueprint…",
|
||||
"import_btn": "Preview",
|
||||
"saving": "Importing blueprint…",
|
||||
@@ -7616,7 +7634,6 @@
|
||||
},
|
||||
"remote": {
|
||||
"title": "Remote access",
|
||||
"card_title": "Remote connection",
|
||||
"connected": "Connected",
|
||||
"not_connected": "Not connected",
|
||||
"reconnecting": "Not connected. Trying to reconnect.",
|
||||
@@ -8127,6 +8144,7 @@
|
||||
"description": "Manage integrations with services or devices",
|
||||
"integration": "integration",
|
||||
"discovered": "Discovered",
|
||||
"discovered_devices": "{count} {count, plural,\n one {device}\n other {devices}\n}",
|
||||
"manage_discovered": "Manage discovered devices",
|
||||
"manage_discovered_description": "Ignore or configure previously discovered devices",
|
||||
"disabled": "Disabled",
|
||||
@@ -8266,6 +8284,7 @@
|
||||
"delete": "Delete",
|
||||
"delete_confirm_title": "Delete {title}?",
|
||||
"delete_confirm_text": "Its devices and entities will be permanently deleted.",
|
||||
"delete_confirm_dependents": "{integrations} {count, plural,\n one {depends on {name} and may stop working.}\n other {depend on {name} and may stop working.}\n}",
|
||||
"enable_debug_logging": "Enable debug logging",
|
||||
"reconfigure": "Reconfigure",
|
||||
"reload": "Reload",
|
||||
@@ -10691,7 +10710,8 @@
|
||||
"over_reported_consumption": "Over-reported consumption",
|
||||
"untracked": "untracked",
|
||||
"other": "Other",
|
||||
"other_devices": "{count, plural, one {# other device} other {# other devices}}"
|
||||
"other_devices": "{count, plural, one {# other device} other {# other devices}}",
|
||||
"total_consumed": "[%key:ui::panel::lovelace::cards::energy::energy_gas_graph::total_consumed%]"
|
||||
},
|
||||
"carbon_consumed_gauge": {
|
||||
"card_indicates_energy_used": "This card indicates how much of the electricity consumed by your home was generated using non-fossil fuels like solar, wind, and nuclear. The higher, the better!",
|
||||
@@ -11629,6 +11649,10 @@
|
||||
"name": "Water flow Sankey graph",
|
||||
"description": "This card shows the real-time flow of water in your home."
|
||||
},
|
||||
"gas-devices-detail-graph": {
|
||||
"name": "Device gas detail graph",
|
||||
"description": "This card shows gas usage per device over time."
|
||||
},
|
||||
"gas-sankey": {
|
||||
"name": "Gas Sankey graph",
|
||||
"description": "This card shows the distribution of gas consumption in your home on a Sankey graph."
|
||||
@@ -11967,13 +11991,6 @@
|
||||
}
|
||||
},
|
||||
"time_format": "[%key:ui::panel::profile::time_format::dropdown_label%]",
|
||||
"time_formats": {
|
||||
"auto": "Use user settings",
|
||||
"language": "[%key:ui::panel::profile::time_format::formats::language%]",
|
||||
"system": "[%key:ui::panel::profile::time_format::formats::system%]",
|
||||
"24": "[%key:ui::panel::profile::time_format::formats::24%]",
|
||||
"12": "[%key:ui::panel::profile::time_format::formats::12%]"
|
||||
},
|
||||
"time_zone": "[%key:ui::panel::profile::time_zone::dropdown_label%]",
|
||||
"time_zones": {
|
||||
"auto": "Use user settings"
|
||||
@@ -12442,6 +12459,10 @@
|
||||
"reset": "Reset"
|
||||
}
|
||||
},
|
||||
"time-set": {
|
||||
"label": "Set time",
|
||||
"time_format": "[%key:ui::panel::profile::time_format::dropdown_label%]"
|
||||
},
|
||||
"timer-actions": {
|
||||
"label": "Timer actions",
|
||||
"customize": "[%key:ui::panel::lovelace::editor::features::types::counter-actions::customize%]",
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { subscribeVisibility } from "../../../src/common/condition/subscribe-visibility";
|
||||
import type { VisibilityCondition } from "../../../src/panels/lovelace/common/validate-condition";
|
||||
import type { HomeAssistant } from "../../../src/types";
|
||||
|
||||
interface CapturedSubscription {
|
||||
push: (message: { result?: boolean }) => void;
|
||||
unsub: ReturnType<typeof vi.fn>;
|
||||
condition: unknown;
|
||||
}
|
||||
|
||||
let subs: CapturedSubscription[];
|
||||
|
||||
const tick = () =>
|
||||
new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, 10);
|
||||
});
|
||||
|
||||
const createHass = (userId = "user1"): HomeAssistant =>
|
||||
({
|
||||
connection: {
|
||||
subscribeMessage: vi.fn(
|
||||
(
|
||||
onChange: CapturedSubscription["push"],
|
||||
msg: { condition: unknown }
|
||||
) => {
|
||||
const unsub = vi.fn();
|
||||
|
||||
subs.push({ push: onChange, unsub, condition: msg.condition });
|
||||
|
||||
return Promise.resolve(unsub);
|
||||
}
|
||||
),
|
||||
},
|
||||
states: {},
|
||||
user: { id: userId },
|
||||
locale: { time_zone: "local" },
|
||||
config: { time_zone: "America/New_York" },
|
||||
}) as unknown as HomeAssistant;
|
||||
|
||||
describe("subscribeVisibility", () => {
|
||||
beforeEach(() => {
|
||||
subs = [];
|
||||
});
|
||||
|
||||
it("checks client conditions again with each hass passed to update", async () => {
|
||||
const onChange = vi.fn();
|
||||
|
||||
const conditions: VisibilityCondition[] = [
|
||||
{ condition: "user", users: ["user1"] },
|
||||
];
|
||||
|
||||
const subscription = subscribeVisibility(
|
||||
createHass("user1"),
|
||||
conditions,
|
||||
onChange
|
||||
);
|
||||
|
||||
await tick();
|
||||
expect(onChange).toHaveBeenLastCalledWith("visible", undefined);
|
||||
|
||||
subscription.update(createHass("user2"));
|
||||
expect(onChange).toHaveBeenLastCalledWith("hidden", undefined);
|
||||
});
|
||||
|
||||
it("closes core subscriptions and stops reporting after unsubscribe", async () => {
|
||||
const onChange = vi.fn();
|
||||
|
||||
const conditions: VisibilityCondition[] = [
|
||||
{ condition: "state", entity: "light.kitchen", state: "on" },
|
||||
];
|
||||
|
||||
const subscription = subscribeVisibility(
|
||||
createHass(),
|
||||
conditions,
|
||||
onChange
|
||||
);
|
||||
|
||||
await tick();
|
||||
expect(subs).toHaveLength(1);
|
||||
|
||||
subs[0].push({ result: true });
|
||||
expect(onChange).toHaveBeenLastCalledWith("visible", undefined);
|
||||
onChange.mockClear();
|
||||
|
||||
subscription.unsubscribe();
|
||||
await tick();
|
||||
expect(subs[0].unsub).toHaveBeenCalled();
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sends the context entity to core for conditions without one", async () => {
|
||||
const conditions: VisibilityCondition[] = [
|
||||
{ condition: "state", state: "on" },
|
||||
];
|
||||
|
||||
subscribeVisibility(createHass(), conditions, vi.fn(), {
|
||||
entity_id: "light.kitchen",
|
||||
});
|
||||
|
||||
await tick();
|
||||
expect(subs).toHaveLength(1);
|
||||
expect(subs[0].condition).toEqual({
|
||||
condition: "state",
|
||||
entity_id: "light.kitchen",
|
||||
state: "on",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cancelEnteringFullscreen,
|
||||
claimFullscreenEnterHide,
|
||||
FULLSCREEN_ENTER_TIME,
|
||||
isEnteringFullscreen,
|
||||
startEnteringFullscreen,
|
||||
} from "../../../src/common/dom/entering-fullscreen";
|
||||
|
||||
describe("entering-fullscreen", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("lets each stream through one hidden page per entering", () => {
|
||||
const streamA = {};
|
||||
const streamB = {};
|
||||
|
||||
expect(claimFullscreenEnterHide(streamA)).toBe(false);
|
||||
|
||||
// Each stream once, and the window counts from the last claim
|
||||
startEnteringFullscreen();
|
||||
vi.advanceTimersByTime(FULLSCREEN_ENTER_TIME - 100);
|
||||
expect(claimFullscreenEnterHide(streamA)).toBe(true);
|
||||
expect(claimFullscreenEnterHide(streamA)).toBe(false);
|
||||
vi.advanceTimersByTime(FULLSCREEN_ENTER_TIME - 100);
|
||||
expect(claimFullscreenEnterHide(streamB)).toBe(true);
|
||||
vi.advanceTimersByTime(FULLSCREEN_ENTER_TIME);
|
||||
expect(isEnteringFullscreen()).toBe(false);
|
||||
expect(claimFullscreenEnterHide({})).toBe(false);
|
||||
|
||||
// Expired before any claim
|
||||
startEnteringFullscreen();
|
||||
vi.advanceTimersByTime(FULLSCREEN_ENTER_TIME);
|
||||
expect(claimFullscreenEnterHide(streamA)).toBe(false);
|
||||
|
||||
startEnteringFullscreen();
|
||||
cancelEnteringFullscreen();
|
||||
expect(claimFullscreenEnterHide(streamA)).toBe(false);
|
||||
|
||||
// A new entering lets the same stream through again
|
||||
startEnteringFullscreen();
|
||||
expect(claimFullscreenEnterHide(streamA)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -162,4 +162,31 @@ describe("finalizeMapStyle", () => {
|
||||
"atmosphere-blend": 0.5,
|
||||
});
|
||||
});
|
||||
|
||||
it("flattens the globe into mercator between zoom 5 and 6", () => {
|
||||
const globe = style();
|
||||
globe.projection = { type: "globe" };
|
||||
|
||||
expect(finalizeMapStyle("colorful", globe).projection).toEqual({
|
||||
type: [
|
||||
"interpolate",
|
||||
["linear"],
|
||||
["zoom"],
|
||||
5,
|
||||
"vertical-perspective",
|
||||
6,
|
||||
"mercator",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves a style that is not a globe alone", () => {
|
||||
const mercator = style();
|
||||
mercator.projection = { type: "mercator" };
|
||||
|
||||
expect(finalizeMapStyle("colorful", mercator).projection).toEqual({
|
||||
type: "mercator",
|
||||
});
|
||||
expect(finalizeMapStyle("colorful", style()).projection).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -100,11 +100,18 @@ describe("ha-map", () => {
|
||||
beforeEach(() => {
|
||||
resizeCallbacks.length = 0;
|
||||
vi.stubGlobal("ResizeObserver", MockResizeObserver);
|
||||
// jsdom has no Web Animations API, which markercluster animates with.
|
||||
// getAnimations is left out, like on Chrome 67-83: the Leaflet engine adds
|
||||
// its own fallback.
|
||||
Element.prototype.animate = vi.fn();
|
||||
vi.stubGlobal("matchMedia", () => ({ matches: false }));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
vi.unstubAllGlobals();
|
||||
Reflect.deleteProperty(Element.prototype, "getAnimations");
|
||||
Reflect.deleteProperty(Element.prototype, "animate");
|
||||
});
|
||||
|
||||
it("fits the map to its entities once the container is laid out", async () => {
|
||||
@@ -381,6 +388,10 @@ describe("ha-map", () => {
|
||||
map.setZoom(12, { animate: false });
|
||||
const shownAgain = await settledBubble(el, zoomedIn);
|
||||
expect(shownAgain.querySelectorAll("ha-entity-marker")).toHaveLength(2);
|
||||
|
||||
// Without a native getAnimations, clusters must not start animations
|
||||
// that a later zoom couldn't cancel
|
||||
expect(Element.prototype.animate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { SelectOption } from "../../../src/data/selector";
|
||||
import {
|
||||
findPickerOption,
|
||||
toPickerId,
|
||||
} from "../../../src/components/ha-selector/ha-selector-select";
|
||||
|
||||
describe("picker IDs", () => {
|
||||
it("are never empty, so the picker can select every option", () => {
|
||||
expect(toPickerId("")).not.toBe("");
|
||||
expect(toPickerId(0)).not.toBe("");
|
||||
});
|
||||
|
||||
it("find the option they were made from", () => {
|
||||
const options: SelectOption[] = [
|
||||
{ value: "", label: "None" },
|
||||
{ value: "___empty___", label: "Placeholder-like" },
|
||||
{ value: "option:", label: "Prefix-like" },
|
||||
{ value: "a", label: "A" },
|
||||
];
|
||||
|
||||
for (const option of options) {
|
||||
expect(findPickerOption(options, toPickerId(option.value))).toBe(option);
|
||||
}
|
||||
expect(findPickerOption(options, "a")).toBeUndefined();
|
||||
expect(findPickerOption(options, undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("match a number and its text", () => {
|
||||
// ha-form-select passes numeric option values at runtime.
|
||||
const options = [{ value: 0, label: "Zero" }] as unknown as SelectOption[];
|
||||
|
||||
expect(findPickerOption(options, toPickerId("0"))).toBe(options[0]);
|
||||
});
|
||||
});
|
||||
+44
-1
@@ -1,5 +1,8 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getConfigSubpageTitle } from "../../src/data/panel";
|
||||
import {
|
||||
getConfigSubpageTitle,
|
||||
getSelectedPanelUrlPath,
|
||||
} from "../../src/data/panel";
|
||||
import type { PageNavigation } from "../../src/layouts/hass-tabs-subpage";
|
||||
import type { HomeAssistant } from "../../src/types";
|
||||
|
||||
@@ -83,3 +86,43 @@ describe("getConfigSubpageTitle", () => {
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSelectedPanelUrlPath", () => {
|
||||
const urlPaths = ["lovelace", "history", "config/logs", "config/logs/raw"];
|
||||
|
||||
it("falls back to the first path segment", () => {
|
||||
expect(getSelectedPanelUrlPath(urlPaths, "/config/automation")).toBe(
|
||||
"config"
|
||||
);
|
||||
expect(getSelectedPanelUrlPath(urlPaths, "/profile/general")).toBe(
|
||||
"profile"
|
||||
);
|
||||
});
|
||||
|
||||
it("selects a panel whose url_path has several segments", () => {
|
||||
expect(getSelectedPanelUrlPath(urlPaths, "/config/logs")).toBe(
|
||||
"config/logs"
|
||||
);
|
||||
expect(getSelectedPanelUrlPath(urlPaths, "/config/logs/details")).toBe(
|
||||
"config/logs"
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers the most specific url_path", () => {
|
||||
expect(getSelectedPanelUrlPath(urlPaths, "/config/logs/raw")).toBe(
|
||||
"config/logs/raw"
|
||||
);
|
||||
});
|
||||
|
||||
it("only matches whole segments", () => {
|
||||
expect(getSelectedPanelUrlPath(urlPaths, "/config/logsfoo")).toBe("config");
|
||||
});
|
||||
|
||||
it("keeps matching single segment panels on their subpaths", () => {
|
||||
expect(getSelectedPanelUrlPath(urlPaths, "/lovelace/0")).toBe("lovelace");
|
||||
});
|
||||
|
||||
it("returns an empty url_path for the root path", () => {
|
||||
expect(getSelectedPanelUrlPath(urlPaths, "/")).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -137,6 +137,75 @@ describe("filterSelectorEntities device filter", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterSelectorEntities capabilities filter", () => {
|
||||
const button = {
|
||||
entity_id: "event.button",
|
||||
state: "unknown",
|
||||
attributes: {
|
||||
event_types: ["single_press", "long_press_start", "long_press_end"],
|
||||
mode: "auto",
|
||||
},
|
||||
} as unknown as HassEntity;
|
||||
|
||||
const matches = (
|
||||
capabilities: Record<string, (string | string[])[]>,
|
||||
stateObj: HassEntity = button
|
||||
) => filterSelectorEntities({ capabilities }, stateObj);
|
||||
|
||||
it("matches when the entity has one of the listed values", () => {
|
||||
expect(matches({ event_types: ["multi_press", "single_press"] })).toBe(
|
||||
true
|
||||
);
|
||||
expect(matches({ event_types: ["multi_press", "press_start"] })).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
it("requires every value of a nested list", () => {
|
||||
expect(
|
||||
matches({ event_types: [["long_press_start", "long_press_end"]] })
|
||||
).toBe(true);
|
||||
expect(matches({ event_types: [["long_press_start", "press_end"]] })).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
it("matches a nested list as one of the alternatives", () => {
|
||||
expect(
|
||||
matches({ event_types: ["multi_press", ["single_press", "press_end"]] })
|
||||
).toBe(false);
|
||||
expect(
|
||||
matches({
|
||||
event_types: ["multi_press", ["long_press_start", "long_press_end"]],
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("matches a scalar attribute against the listed values", () => {
|
||||
expect(matches({ mode: ["auto", "manual"] })).toBe(true);
|
||||
expect(matches({ mode: ["manual"] })).toBe(false);
|
||||
});
|
||||
|
||||
it("requires every capability to match", () => {
|
||||
expect(matches({ event_types: ["single_press"], mode: ["auto"] })).toBe(
|
||||
true
|
||||
);
|
||||
expect(matches({ event_types: ["single_press"], mode: ["manual"] })).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
it("does not match when the attribute is missing or null", () => {
|
||||
expect(matches({ hvac_modes: ["heat"] })).toBe(false);
|
||||
expect(
|
||||
matches({ event_types: ["single_press"] }, {
|
||||
...button,
|
||||
attributes: { event_types: null },
|
||||
} as unknown as HassEntity)
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveEntityIDs", () => {
|
||||
const areaHass = {
|
||||
states: {
|
||||
|
||||
+8
@@ -9,6 +9,7 @@ exports[`generateEnergyDevicesDetailGraphData > large month-of-hourly digest is
|
||||
"end",
|
||||
"legendData",
|
||||
"start",
|
||||
"unit",
|
||||
"yAxisFractionDigits",
|
||||
],
|
||||
"numberCount": 20452,
|
||||
@@ -26,6 +27,7 @@ exports[`generateEnergyDevicesDetailGraphData > large month-of-hourly digest is
|
||||
"end",
|
||||
"legendData",
|
||||
"start",
|
||||
"unit",
|
||||
"yAxisFractionDigits",
|
||||
],
|
||||
"numberCount": 67660,
|
||||
@@ -14701,6 +14703,7 @@ exports[`generateEnergyDevicesDetailGraphData > matches snapshot for 5minute per
|
||||
},
|
||||
],
|
||||
"start": 2024-01-01T00:00:00.000Z,
|
||||
"unit": "kWh",
|
||||
"yAxisFractionDigits": 0,
|
||||
}
|
||||
`;
|
||||
@@ -16112,6 +16115,7 @@ exports[`generateEnergyDevicesDetailGraphData > matches snapshot for a small hou
|
||||
},
|
||||
],
|
||||
"start": 2024-01-01T00:00:00.000Z,
|
||||
"unit": "kWh",
|
||||
"yAxisFractionDigits": 0,
|
||||
}
|
||||
`;
|
||||
@@ -16673,6 +16677,7 @@ exports[`generateEnergyDevicesDetailGraphData > matches snapshot for daily perio
|
||||
},
|
||||
],
|
||||
"start": 2024-01-01T00:00:00.000Z,
|
||||
"unit": "kWh",
|
||||
"yAxisFractionDigits": 0,
|
||||
}
|
||||
`;
|
||||
@@ -18308,6 +18313,7 @@ exports[`generateEnergyDevicesDetailGraphData > matches snapshot with child devi
|
||||
},
|
||||
],
|
||||
"start": 2024-01-01T00:00:00.000Z,
|
||||
"unit": "kWh",
|
||||
"yAxisFractionDigits": 0,
|
||||
}
|
||||
`;
|
||||
@@ -23097,6 +23103,7 @@ exports[`generateEnergyDevicesDetailGraphData > matches snapshot with compare da
|
||||
},
|
||||
],
|
||||
"start": 2024-01-01T00:00:00.000Z,
|
||||
"unit": "kWh",
|
||||
"yAxisFractionDigits": 0,
|
||||
}
|
||||
`;
|
||||
@@ -24271,6 +24278,7 @@ exports[`generateEnergyDevicesDetailGraphData > respects max_devices config 1`]
|
||||
},
|
||||
],
|
||||
"start": 2024-01-01T00:00:00.000Z,
|
||||
"unit": "kWh",
|
||||
"yAxisFractionDigits": 0,
|
||||
}
|
||||
`;
|
||||
@@ -374,6 +374,53 @@ describe("generateEnergyDevicesDetailGraphData", () => {
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
it("shows only the gas devices, measured against the gas sources", () => {
|
||||
const dayMs = 24 * 60 * 60 * 1000;
|
||||
const start = new Date("2025-09-01T00:00:00Z");
|
||||
const day1 = start.getTime();
|
||||
const day2 = day1 + dayMs;
|
||||
const bucket = (ts: number, change: number) => ({
|
||||
start: ts,
|
||||
end: ts + dayMs,
|
||||
change,
|
||||
});
|
||||
const prefs = {
|
||||
...generateEnergyPreferences({ grid: true, gas: true }),
|
||||
device_consumption: buildPrefs(false).device_consumption,
|
||||
device_consumption_gas: [
|
||||
{ stat_consumption: "sensor.stove", name: "Stove" },
|
||||
],
|
||||
};
|
||||
const energyData = {
|
||||
...generateEnergyData(1, { days: 1, prefs }),
|
||||
start,
|
||||
end: new Date(day2 + dayMs),
|
||||
stats: {
|
||||
// Electricity devices must not show up in the gas graph
|
||||
"sensor.grid_consumption": [bucket(day1, 30), bucket(day2, 30)],
|
||||
"sensor.gas_consumption": [bucket(day1, 10), bucket(day2, 12)],
|
||||
"sensor.stove": [bucket(day1, 4), bucket(day2, 5)],
|
||||
},
|
||||
};
|
||||
const result = generateEnergyDevicesDetailGraphData({
|
||||
...baseParams,
|
||||
resource: "gas",
|
||||
energyData,
|
||||
});
|
||||
assert.equal(result.unit, energyData.gasUnit);
|
||||
// Untracked is the gas sources minus the stove: (10 - 4) + (12 - 5)
|
||||
assert.deepEqual(
|
||||
result.legendData?.map((l) => [l.name, l.value]),
|
||||
[
|
||||
["Stove", "9 m³"],
|
||||
[
|
||||
"ui.panel.lovelace.cards.energy.energy_devices_detail_graph.untracked_consumption",
|
||||
"13 m³",
|
||||
],
|
||||
]
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("limitTooltipParams", () => {
|
||||
|
||||
Reference in new issue
Block a user