mirror of
https://github.com/home-assistant/frontend.git
synced 2026-11-23 13:18:54 +00:00
Compare commits
18
Commits
skeletons/wave
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f08e3b299e | ||
|
|
089ddb9ade | ||
|
|
50c911fe2f | ||
|
|
bf16d4e5a1 | ||
|
|
608ad23071 | ||
|
|
0d84bb01ec | ||
|
|
ff95b531b7 | ||
|
|
921b7362a5 | ||
|
|
fb20d72938 | ||
|
|
4a1328970f | ||
|
|
f441726c3c | ||
|
|
731fd30b07 | ||
|
|
b6660a23ed | ||
|
|
f3990796ba | ||
|
|
4fb7eefb27 | ||
|
|
214762a052 | ||
|
|
a75f7265ff | ||
|
|
3a5c534def |
No files matched your search
@@ -70,7 +70,7 @@ workflows:
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
- 'actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0'
|
||||
- 'home-assistant/actions@07f46fd2e19967768b5fd3000f91f857452b767c'
|
||||
- 'home-assistant/actions@2026.11.0'
|
||||
- 'home-assistant/wheels@9e17ab1ed5c4c79d8b61e29fa63de25ca2710716'
|
||||
- 'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086'
|
||||
'.github/workflows/restrict-task-creation.yaml':
|
||||
@@ -156,7 +156,7 @@ dependencies:
|
||||
commit: 'sha1-33d7b85da1a04171e211befe2c739303b9a4c066'
|
||||
owner_id: 9919
|
||||
repo_id: 259445878
|
||||
'home-assistant/actions@07f46fd2e19967768b5fd3000f91f857452b767c':
|
||||
'home-assistant/actions@2026.11.0':
|
||||
ref: '2026.11.0'
|
||||
commit: 'sha1-07f46fd2e19967768b5fd3000f91f857452b767c'
|
||||
owner_id: 13844975
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
python-version: ${{ env.PYTHON_VERSION }}
|
||||
|
||||
- name: Verify version
|
||||
uses: home-assistant/actions/helpers/verify-version@07f46fd2e19967768b5fd3000f91f857452b767c # master
|
||||
uses: home-assistant/actions/helpers/verify-version@2026.11.0
|
||||
|
||||
- name: Setup Node and install
|
||||
uses: $/.github/actions/setup
|
||||
|
||||
@@ -250,6 +250,9 @@ sit inside `<ha-list-selectable>`, which owns selection state and toggles
|
||||
|
||||
- `selected` (Boolean, default `false`, reflected) — set by the parent
|
||||
`ha-list-selectable`.
|
||||
- `indeterminate` (Boolean, default `false`, reflected) — draws the checkbox
|
||||
as mixed, for a row that stands for a partly selected set. Screen readers
|
||||
hear it as "Partly selected" through `aria-description`.
|
||||
- `value` (String) — value identifying the option.
|
||||
- `appearance` (`"line"` | `"checkbox"`, default `"line"`) — `"line"`
|
||||
highlights the row; `"checkbox"` renders a decorative `<ha-checkbox>`.
|
||||
|
||||
+1
-1
@@ -64,7 +64,7 @@
|
||||
"@formatjs/intl-pluralrules": "7.1.0",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.3",
|
||||
"@home-assistant/webawesome": "3.14.0-ha.2",
|
||||
"@lezer/common": "1.5.5",
|
||||
"@lezer/common": "1.5.6",
|
||||
"@lezer/highlight": "1.2.5",
|
||||
"@lit-labs/motion": "1.1.0",
|
||||
"@lit-labs/observers": "2.1.0",
|
||||
|
||||
Generated
+21
-21
@@ -261,8 +261,8 @@ importers:
|
||||
specifier: 3.14.0-ha.2
|
||||
version: 3.14.0-ha.2(@floating-ui/[email protected])(@types/[email protected])
|
||||
'@lezer/common':
|
||||
specifier: 1.5.5
|
||||
version: 1.5.5
|
||||
specifier: 1.5.6
|
||||
version: 1.5.6
|
||||
'@lezer/highlight':
|
||||
specifier: 1.2.5
|
||||
version: 1.2.5
|
||||
@@ -2251,8 +2251,8 @@ packages:
|
||||
'@konnorr/[email protected]':
|
||||
resolution: {integrity: sha512-6Ae3AfG45MOqF9Qde+1YxIxKf/GUsRmcriV7iCb/HaR+Mk1YDFYP3RINDRMI8z8YMWW3BnSthOujX9RoOex/Kw==}
|
||||
|
||||
'@lezer/[email protected].5':
|
||||
resolution: {integrity: sha512-Pw7PVCndruF1pb3ebCxpSVpkMHSDjwRCLcTRw+RizUKco5QbWylwq2g4lnG/RYN7yTTQDXE9F77MwtkAyphrjg==}
|
||||
'@lezer/[email protected].6':
|
||||
resolution: {integrity: sha512-NZxu3q49ck+YYbEJPuIPIyFP37XneBvzPIarBHEXBLBVfkZqQieZ/Y2boYnGNYtmjpOZLnAKs/lwqtmDpi365w==}
|
||||
|
||||
'@lezer/[email protected]':
|
||||
resolution: {integrity: sha512-YJE78Wcg+zX8f10hiHWQ4Az48Qr/c13eId0VtRQYLBpxHDmDeSrXIlkbl+fJGW42rWC/uoUco9mhBZeVWP/A1g==}
|
||||
@@ -9486,21 +9486,21 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.15
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.15
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.4
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/css': 1.3.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -9511,7 +9511,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.15
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/css': 1.3.6
|
||||
'@lezer/html': 1.3.13
|
||||
|
||||
@@ -9522,7 +9522,7 @@ snapshots:
|
||||
'@codemirror/lint': 6.9.8
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.15
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/javascript': 1.5.4
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -9532,7 +9532,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.15
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.10
|
||||
|
||||
@@ -9541,7 +9541,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.4
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/python': 1.1.19
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -9549,7 +9549,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.4
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.10
|
||||
'@lezer/yaml': 1.0.4
|
||||
@@ -9559,7 +9559,7 @@ snapshots:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/streamparser': 6.0.0
|
||||
'@codemirror/view': 6.43.15
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.10
|
||||
style-mod: 4.1.3
|
||||
@@ -10097,43 +10097,43 @@ snapshots:
|
||||
|
||||
'@konnorr/[email protected]': {}
|
||||
|
||||
'@lezer/[email protected].5': {}
|
||||
'@lezer/[email protected].6': {}
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.10
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.10
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.10
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.10
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.5
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.10
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ export const generateColorPalette = (
|
||||
}
|
||||
|
||||
return steps.map((step) => {
|
||||
const name = `ha-color-${label}-${step}`;
|
||||
const name = `ha-color-${label}-${String(step).padStart(2, "0")}`;
|
||||
|
||||
// Base color at 50%
|
||||
if (step === 50) {
|
||||
|
||||
@@ -6,15 +6,17 @@ const isConditionObject = (c: unknown): c is VisibilityCondition =>
|
||||
typeof c === "object" && c !== null;
|
||||
|
||||
/**
|
||||
* Drop entries that are not condition objects, at any depth. Returns the
|
||||
* same array when every entry is valid.
|
||||
* Drop entries that are not condition objects, at any depth. A single
|
||||
* condition mapping is wrapped in an array. Returns the same array when it
|
||||
* is an array and every entry is valid.
|
||||
*/
|
||||
export const dropInvalidConditions = (
|
||||
conditions: VisibilityCondition[]
|
||||
conditions: VisibilityCondition | VisibilityCondition[]
|
||||
): VisibilityCondition[] => {
|
||||
let changed = false;
|
||||
const list = ensureArray(conditions);
|
||||
let changed = list !== conditions;
|
||||
const valid: VisibilityCondition[] = [];
|
||||
for (const c of conditions) {
|
||||
for (const c of list) {
|
||||
if (!isConditionObject(c)) {
|
||||
changed = true;
|
||||
continue;
|
||||
@@ -30,5 +32,5 @@ export const dropInvalidConditions = (
|
||||
}
|
||||
valid.push(c);
|
||||
}
|
||||
return changed ? valid : conditions;
|
||||
return changed ? valid : list;
|
||||
};
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { ThemeVars } from "../../data/ws-themes";
|
||||
import {
|
||||
getThemeVariables,
|
||||
themeDefinesColor,
|
||||
themeDefinesPrimaryPalette,
|
||||
} from "../../data/ws-themes";
|
||||
import { darkColorVariables } from "../../resources/theme/color";
|
||||
import { darkSemanticVariables } from "../../resources/theme/semantic.globals";
|
||||
import { derivedStyles } from "../../resources/theme/theme";
|
||||
@@ -10,9 +15,9 @@ import {
|
||||
rgb2hex,
|
||||
rgb2lab,
|
||||
} from "../color/convert-color";
|
||||
import { hexBlend } from "../color/hex";
|
||||
import { cssColorToHex, hexBlend } from "../color/hex";
|
||||
import { labBrighten, labDarken } from "../color/lab";
|
||||
import { generateColorPalette } from "../color/palette";
|
||||
import { generateColorPalette, normalizeLuminance } from "../color/palette";
|
||||
import { rgbContrast } from "../color/rgb";
|
||||
|
||||
interface ProcessedTheme {
|
||||
@@ -56,78 +61,56 @@ export const applyThemesOnElement = (
|
||||
themeRules = { ...darkSemanticVariables, ...darkColorVariables };
|
||||
}
|
||||
|
||||
if (themeToApply === "default") {
|
||||
// Determine the primary and accent colors from the current settings.
|
||||
// Fallbacks are implicitly the HA default blue and orange or the
|
||||
// derived "darkStyles" values, depending on the light vs dark mode.
|
||||
const primaryColor = themeSettings?.primaryColor;
|
||||
const accentColor = themeSettings?.accentColor;
|
||||
const isDefaultTheme = themeToApply === "default";
|
||||
const customTheme =
|
||||
themeToApply && !isDefaultTheme ? themes.themes[themeToApply] : undefined;
|
||||
const customThemeRules = customTheme
|
||||
? getThemeVariables(customTheme, darkMode)
|
||||
: undefined;
|
||||
|
||||
if (darkMode && primaryColor) {
|
||||
themeRules["app-header-background-color"] = hexBlend(
|
||||
primaryColor,
|
||||
"#121212",
|
||||
8
|
||||
);
|
||||
}
|
||||
const primaryColor =
|
||||
isDefaultTheme ||
|
||||
(customThemeRules && !themeDefinesColor(customThemeRules, "primary"))
|
||||
? themeSettings?.primaryColor
|
||||
: undefined;
|
||||
const accentColor =
|
||||
isDefaultTheme ||
|
||||
(customThemeRules && !themeDefinesColor(customThemeRules, "accent"))
|
||||
? themeSettings?.accentColor
|
||||
: undefined;
|
||||
|
||||
if (primaryColor) {
|
||||
cacheKey = `${cacheKey}__primary_${primaryColor}`;
|
||||
const rgbPrimaryColor = hex2rgb(primaryColor);
|
||||
const labPrimaryColor = rgb2lab(rgbPrimaryColor);
|
||||
themeRules["primary-color"] = primaryColor;
|
||||
const rgbLightPrimaryColor = lab2rgb(labBrighten(labPrimaryColor));
|
||||
if (primaryColor) {
|
||||
cacheKey = `${cacheKey}__primary_${primaryColor}`;
|
||||
}
|
||||
if (accentColor) {
|
||||
cacheKey = `${cacheKey}__accent_${accentColor}`;
|
||||
}
|
||||
themeRules = {
|
||||
...themeRules,
|
||||
...getUserColorRules(primaryColor, accentColor, isDefaultTheme && darkMode),
|
||||
};
|
||||
|
||||
generateColorPalette(primaryColor, "primary").forEach(([key, color]) => {
|
||||
themeRules[key] = color;
|
||||
});
|
||||
|
||||
themeRules["light-primary-color"] = rgb2hex(rgbLightPrimaryColor);
|
||||
themeRules["dark-primary-color"] = lab2hex(labDarken(labPrimaryColor));
|
||||
themeRules["darker-primary-color"] = lab2hex(
|
||||
labDarken(labPrimaryColor, 2)
|
||||
);
|
||||
themeRules["text-primary-color"] =
|
||||
rgbContrast(rgbPrimaryColor, [33, 33, 33]) < 6 ? "#fff" : "#212121";
|
||||
themeRules["text-light-primary-color"] =
|
||||
rgbContrast(rgbLightPrimaryColor, [33, 33, 33]) < 6
|
||||
? "#fff"
|
||||
: "#212121";
|
||||
themeRules["state-icon-color"] = themeRules["dark-primary-color"];
|
||||
}
|
||||
if (accentColor) {
|
||||
cacheKey = `${cacheKey}__accent_${accentColor}`;
|
||||
themeRules["accent-color"] = accentColor;
|
||||
const rgbAccentColor = hex2rgb(accentColor);
|
||||
themeRules["text-accent-color"] =
|
||||
rgbContrast(rgbAccentColor, [33, 33, 33]) < 6 ? "#fff" : "#212121";
|
||||
}
|
||||
|
||||
// Nothing was changed
|
||||
if (element.__themes?.cacheKey === cacheKey) {
|
||||
return;
|
||||
}
|
||||
// Nothing was changed
|
||||
if (isDefaultTheme && element.__themes?.cacheKey === cacheKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Custom theme logic (not relevant for default theme, since it would override
|
||||
// the derived calculations from above)
|
||||
if (
|
||||
themeToApply &&
|
||||
themeToApply !== "default" &&
|
||||
themes.themes[themeToApply]
|
||||
) {
|
||||
// Apply theme vars that are relevant for all modes (but extract the "modes" section first)
|
||||
const { modes, ...baseThemeRules } = themes.themes[themeToApply];
|
||||
themeRules = { ...themeRules, ...baseThemeRules };
|
||||
// Unparseable colors like `var(--x)` are skipped.
|
||||
const themePrimaryColor =
|
||||
customThemeRules?.["primary-color"] &&
|
||||
!themeDefinesPrimaryPalette(customThemeRules)
|
||||
? cssColorToHex(customThemeRules["primary-color"])
|
||||
: undefined;
|
||||
if (themePrimaryColor) {
|
||||
// Older themes often use a near black primary color for the header.
|
||||
themeRules = {
|
||||
...themeRules,
|
||||
...getPrimaryPaletteRules(normalizeLuminance(themePrimaryColor)),
|
||||
};
|
||||
}
|
||||
|
||||
// Apply theme vars for the specific mode if available
|
||||
if (modes) {
|
||||
if (darkMode) {
|
||||
themeRules = { ...themeRules, ...modes.dark };
|
||||
} else {
|
||||
themeRules = { ...themeRules, ...modes.light };
|
||||
}
|
||||
}
|
||||
if (customThemeRules) {
|
||||
themeRules = { ...themeRules, ...customThemeRules };
|
||||
}
|
||||
|
||||
if (!element.__themes?.keys && !Object.keys(themeRules).length) {
|
||||
@@ -154,6 +137,57 @@ export const applyThemesOnElement = (
|
||||
}
|
||||
};
|
||||
|
||||
const getPrimaryPaletteRules = (primaryColor: string): Partial<ThemeVars> => {
|
||||
const rules: Partial<ThemeVars> = {};
|
||||
const labPrimaryColor = rgb2lab(hex2rgb(primaryColor));
|
||||
|
||||
generateColorPalette(primaryColor, "primary").forEach(([key, color]) => {
|
||||
rules[key] = color;
|
||||
});
|
||||
|
||||
rules["light-primary-color"] = rgb2hex(lab2rgb(labBrighten(labPrimaryColor)));
|
||||
rules["dark-primary-color"] = lab2hex(labDarken(labPrimaryColor));
|
||||
rules["darker-primary-color"] = lab2hex(labDarken(labPrimaryColor, 2));
|
||||
return rules;
|
||||
};
|
||||
|
||||
const getUserColorRules = (
|
||||
primaryColor: string | undefined,
|
||||
accentColor: string | undefined,
|
||||
tintHeader: boolean
|
||||
): Partial<ThemeVars> => {
|
||||
const rules: Partial<ThemeVars> = {};
|
||||
|
||||
if (primaryColor) {
|
||||
if (tintHeader) {
|
||||
rules["app-header-background-color"] = hexBlend(
|
||||
primaryColor,
|
||||
"#121212",
|
||||
8
|
||||
);
|
||||
}
|
||||
|
||||
Object.assign(rules, getPrimaryPaletteRules(primaryColor));
|
||||
rules["primary-color"] = primaryColor;
|
||||
rules["text-primary-color"] =
|
||||
rgbContrast(hex2rgb(primaryColor), [33, 33, 33]) < 6 ? "#fff" : "#212121";
|
||||
rules["text-light-primary-color"] =
|
||||
rgbContrast(hex2rgb(rules["light-primary-color"]!), [33, 33, 33]) < 6
|
||||
? "#fff"
|
||||
: "#212121";
|
||||
rules["state-icon-color"] = rules["dark-primary-color"];
|
||||
}
|
||||
|
||||
if (accentColor) {
|
||||
rules["accent-color"] = accentColor;
|
||||
const rgbAccentColor = hex2rgb(accentColor);
|
||||
rules["text-accent-color"] =
|
||||
rgbContrast(rgbAccentColor, [33, 33, 33]) < 6 ? "#fff" : "#212121";
|
||||
}
|
||||
|
||||
return rules;
|
||||
};
|
||||
|
||||
const processTheme = (
|
||||
cacheKey: string,
|
||||
theme: Partial<ThemeVars>
|
||||
|
||||
@@ -12,7 +12,12 @@ const SWIPE_LOCKED_COMPONENTS = new Set([
|
||||
"ha-filter-chip",
|
||||
]);
|
||||
|
||||
const SWIPE_LOCKED_CLASSES = new Set(["volume-slider-container", "forecast"]);
|
||||
const SWIPE_LOCKED_CLASSES = new Set([
|
||||
"volume-slider-container",
|
||||
"forecast",
|
||||
// A zoomed in camera picture pans on touch
|
||||
"camera-player-zoomed",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Whether a touch inside a bottom sheet belongs to its content rather than to
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// Some WebViews become visible after thawing without dispatching visibilitychange,
|
||||
// resume, or focus. Check visibility while waiting so reconnects cannot stay blocked.
|
||||
export const whenDocumentVisible = (callback: () => void): (() => void) => {
|
||||
const check = () => {
|
||||
if (!document.hidden) {
|
||||
cancel();
|
||||
callback();
|
||||
}
|
||||
};
|
||||
const interval = window.setInterval(check, 1000);
|
||||
const cancel = () => {
|
||||
window.clearInterval(interval);
|
||||
document.removeEventListener("visibilitychange", check);
|
||||
document.removeEventListener("resume", check);
|
||||
window.removeEventListener("focus", check);
|
||||
};
|
||||
document.addEventListener("visibilitychange", check);
|
||||
document.addEventListener("resume", check);
|
||||
window.addEventListener("focus", check);
|
||||
return cancel;
|
||||
};
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
TEMPERATURE_ATTRIBUTES,
|
||||
} from "../../data/entity/entity_attributes";
|
||||
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
|
||||
import { computeGroupMemberEntries } from "../../data/group";
|
||||
import type { FrontendLocaleData } from "../../data/translation";
|
||||
import { TimeZone } from "../../data/translation";
|
||||
import type { WeatherEntity } from "../../data/weather";
|
||||
@@ -182,6 +183,13 @@ export const computeAttributeValueToParts = (
|
||||
localize(
|
||||
`component.${registryEntry.platform}.entity.${domain}.${translationKey}.state_attributes.${attribute}.state.${attributeValue}`
|
||||
)) ||
|
||||
computeMemberAttributeValueDisplay(
|
||||
localize,
|
||||
stateObj,
|
||||
entities,
|
||||
attribute,
|
||||
attributeValue
|
||||
) ||
|
||||
(deviceClass &&
|
||||
localize(
|
||||
`component.${domain}.entity_component.${deviceClass}.state_attributes.${attribute}.state.${attributeValue}`
|
||||
@@ -193,6 +201,27 @@ export const computeAttributeValueToParts = (
|
||||
return [{ type: "value", value: formattedValue }];
|
||||
};
|
||||
|
||||
// A group has no translations for the values of its members, for example the
|
||||
// effects of a light group, so use the translation of a member.
|
||||
const computeMemberAttributeValueDisplay = (
|
||||
localize: LocalizeFunc,
|
||||
stateObj: HassEntity,
|
||||
entities: HomeAssistant["entities"],
|
||||
attribute: string,
|
||||
attributeValue: string
|
||||
): string | undefined => {
|
||||
const domain = computeStateDomain(stateObj);
|
||||
for (const member of computeGroupMemberEntries(stateObj, entities)) {
|
||||
const translation = localize(
|
||||
`component.${member.platform}.entity.${domain}.${member.translation_key}.state_attributes.${attribute}.state.${attributeValue}`
|
||||
);
|
||||
if (translation) {
|
||||
return translation;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const computeAttributeNameDisplay = (
|
||||
localize: LocalizeFunc,
|
||||
stateObj: HassEntity,
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { HTMLTemplateResult } from "lit";
|
||||
import { polyfillLocaleData } from "../../resources/polyfills/locale-data-polyfill";
|
||||
import type { Resources, TranslationDict } from "../../types";
|
||||
import { fireEvent } from "../dom/fire_event";
|
||||
import { NAME_PLACEHOLDERS } from "./name-placeholders";
|
||||
|
||||
// Exclude some patterns from key type checking for now
|
||||
// These are intended to be removed as errors are fixed
|
||||
@@ -140,7 +141,10 @@ export const computeLocalize = async <Keys extends string = LocalizeKeys>(
|
||||
}
|
||||
|
||||
try {
|
||||
return translatedMessage.format<string>(argObject) as string;
|
||||
return translatedMessage.format<string>({
|
||||
...NAME_PLACEHOLDERS,
|
||||
...argObject,
|
||||
}) as string;
|
||||
} catch (err: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error("Translation error", key, language, err);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
export const MARKETPLACE_NAME = "Marketplace";
|
||||
|
||||
export const NAME_PLACEHOLDERS = {
|
||||
marketplace: MARKETPLACE_NAME,
|
||||
};
|
||||
@@ -1,32 +1,29 @@
|
||||
// Handle 16x9, 16:9, 1.78x1, 1.78:1, 1.78
|
||||
// Ignore everything else
|
||||
const parseOrThrow = (num) => {
|
||||
const parsed = parseFloat(num);
|
||||
if (isNaN(parsed)) {
|
||||
throw new Error(`${num} is not a number`);
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
// Handle 16x9, 16:9, 1.78x1, 1.78:1, 1.78 and 23%
|
||||
// Return null for everything else
|
||||
const NUMBER = String.raw`(\d+(?:\.\d*)?|\.\d+)`;
|
||||
const RATIO_REGEX = new RegExp(
|
||||
String.raw`^\s*${NUMBER}\s*(?:[x:]\s*${NUMBER}\s*)?$`
|
||||
);
|
||||
const PERCENTAGE_REGEX = new RegExp(String.raw`^\s*${NUMBER}\s*%\s*$`);
|
||||
|
||||
export default function parseAspectRatio(input: string) {
|
||||
if (!input) {
|
||||
// YAML loads an unquoted 16:9 as the base-60 number 969, so skip non-strings
|
||||
if (!input || typeof input !== "string") {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (input.endsWith("%")) {
|
||||
return { w: 100, h: parseOrThrow(input.slice(0, -1)) };
|
||||
}
|
||||
|
||||
const arr = input.replace(":", "x").split("x");
|
||||
if (arr.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return arr.length === 1
|
||||
? { w: parseOrThrow(arr[0]), h: 1 }
|
||||
: { w: parseOrThrow(arr[0]), h: parseOrThrow(arr[1]) };
|
||||
} catch (_err: any) {
|
||||
// Ignore the error
|
||||
const percentage = PERCENTAGE_REGEX.exec(input);
|
||||
if (percentage) {
|
||||
return { w: 100, h: parseFloat(percentage[1]) };
|
||||
}
|
||||
|
||||
const ratio = RATIO_REGEX.exec(input);
|
||||
if (ratio) {
|
||||
return {
|
||||
w: parseFloat(ratio[1]),
|
||||
h: ratio[2] === undefined ? 1 : parseFloat(ratio[2]),
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
// as much as it can, without ever going more than once per `wait` duration;
|
||||
// but if you'd like to disable the execution on the leading edge, pass
|
||||
// `false for leading`. To disable execution on the trailing edge, ditto.
|
||||
// The trailing call uses the arguments of the latest call.
|
||||
export const throttle = <T extends any[]>(
|
||||
func: (...args: T) => void,
|
||||
wait: number,
|
||||
@@ -13,12 +14,17 @@ export const throttle = <T extends any[]>(
|
||||
) => {
|
||||
let timeout: number | undefined;
|
||||
let previous = 0;
|
||||
const throttledFunc = (...args: T): void => {
|
||||
const later = () => {
|
||||
previous = leading === false ? 0 : Date.now();
|
||||
timeout = undefined;
|
||||
let pendingArgs: T | undefined;
|
||||
const later = () => {
|
||||
previous = leading === false ? 0 : Date.now();
|
||||
timeout = undefined;
|
||||
const args = pendingArgs;
|
||||
pendingArgs = undefined;
|
||||
if (args) {
|
||||
func(...args);
|
||||
};
|
||||
}
|
||||
};
|
||||
const throttledFunc = (...args: T): void => {
|
||||
const now = Date.now();
|
||||
if (!previous && leading === false) {
|
||||
previous = now;
|
||||
@@ -30,15 +36,20 @@ export const throttle = <T extends any[]>(
|
||||
timeout = undefined;
|
||||
}
|
||||
previous = now;
|
||||
pendingArgs = undefined;
|
||||
func(...args);
|
||||
} else if (!timeout && trailing !== false) {
|
||||
timeout = window.setTimeout(later, remaining);
|
||||
} else if (trailing !== false) {
|
||||
pendingArgs = args;
|
||||
if (!timeout) {
|
||||
timeout = window.setTimeout(later, remaining);
|
||||
}
|
||||
}
|
||||
};
|
||||
throttledFunc.cancel = () => {
|
||||
clearTimeout(timeout);
|
||||
timeout = undefined;
|
||||
previous = 0;
|
||||
pendingArgs = undefined;
|
||||
};
|
||||
return throttledFunc;
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,153 @@
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import type {
|
||||
CameraStreamStatus,
|
||||
CameraStreamType,
|
||||
} from "../../data/camera-streams";
|
||||
import "../ha-spinner";
|
||||
|
||||
/** Names of the protocols, the same in every language. */
|
||||
export const CAMERA_STREAM_TYPE_NAMES: Record<CameraStreamType, string> = {
|
||||
web_rtc: "WebRTC",
|
||||
hls: "HLS",
|
||||
mjpeg: "MJPEG",
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows over a camera stream how it is connected. A faster stream that still
|
||||
* connects in the background is shown next to the current one.
|
||||
*/
|
||||
@customElement("ha-camera-stream-badge")
|
||||
export class HaCameraStreamBadge extends LitElement {
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@property({ attribute: false }) public status?: CameraStreamStatus;
|
||||
|
||||
protected render() {
|
||||
const status = this.status;
|
||||
if (!status) {
|
||||
return nothing;
|
||||
}
|
||||
const connecting = status.connecting || !status.type;
|
||||
const label = connecting
|
||||
? this._localize("ui.components.camera-player.connecting")
|
||||
: CAMERA_STREAM_TYPE_NAMES[status.type!];
|
||||
|
||||
return html`
|
||||
<button
|
||||
type="button"
|
||||
aria-label=${this._ariaLabel(status)}
|
||||
class=${connecting ? "connecting" : "live"}
|
||||
>
|
||||
<span class="dot"></span>
|
||||
<span class="label">${label}</span>
|
||||
${
|
||||
status.upgrading
|
||||
? html`<span class="upgrading" aria-hidden="true">
|
||||
<ha-spinner></ha-spinner>
|
||||
${CAMERA_STREAM_TYPE_NAMES[status.upgrading]}
|
||||
</span>`
|
||||
: nothing
|
||||
}
|
||||
</button>
|
||||
`;
|
||||
}
|
||||
|
||||
private _ariaLabel(status: CameraStreamStatus): string {
|
||||
if (status.connecting || !status.type) {
|
||||
return this._localize(
|
||||
"ui.components.camera-player.stream_info_connecting"
|
||||
);
|
||||
}
|
||||
if (status.upgrading) {
|
||||
return this._localize(
|
||||
"ui.components.camera-player.stream_info_upgrading",
|
||||
{
|
||||
type: CAMERA_STREAM_TYPE_NAMES[status.type],
|
||||
upgrading: CAMERA_STREAM_TYPE_NAMES[status.upgrading],
|
||||
}
|
||||
);
|
||||
}
|
||||
return this._localize("ui.components.camera-player.stream_info", {
|
||||
type: CAMERA_STREAM_TYPE_NAMES[status.type],
|
||||
});
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
/* Readable on a dark and on a bright picture */
|
||||
button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-1);
|
||||
height: 28px;
|
||||
padding-inline: var(--ha-space-2);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
border-radius: var(--ha-border-radius-pill);
|
||||
background-color: rgba(0, 0, 0, 0.45);
|
||||
backdrop-filter: blur(8px);
|
||||
-webkit-backdrop-filter: blur(8px);
|
||||
color: var(--ha-color-white);
|
||||
font-family: inherit;
|
||||
font-size: var(--ha-font-size-s);
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:focus-visible {
|
||||
outline: var(--wa-focus-ring-style) var(--wa-focus-ring-width)
|
||||
var(--ha-color-white);
|
||||
outline-offset: var(--wa-focus-ring-offset);
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: var(--ha-border-radius-circle);
|
||||
background-color: var(--ha-color-green-60);
|
||||
}
|
||||
|
||||
.connecting .dot {
|
||||
background-color: rgba(255, 255, 255, 0.8);
|
||||
animation: pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.upgrading {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-1);
|
||||
padding-inline-start: var(--ha-space-1);
|
||||
border-inline-start: 1px solid rgba(255, 255, 255, 0.3);
|
||||
opacity: 0.7;
|
||||
--ha-spinner-indicator-color: var(--ha-color-white);
|
||||
--ha-spinner-size: 10px;
|
||||
--ha-spinner-divider-color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
50% {
|
||||
opacity: 0.3;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.connecting .dot {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-camera-stream-badge": HaCameraStreamBadge;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Zoom and pan of content that fills a viewport, applied as
|
||||
* `translate(x, y) scale(scale)` with the transform origin at the top left.
|
||||
*/
|
||||
export interface ZoomPan {
|
||||
scale: number;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface ZoomPanSize {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export const ZOOM_PAN_IDENTITY: ZoomPan = { scale: 1, x: 0, y: 0 };
|
||||
|
||||
export const MAX_ZOOM = 5;
|
||||
|
||||
export const isZoomed = (zoomPan: ZoomPan): boolean => zoomPan.scale > 1;
|
||||
|
||||
/** Keeps the scale in range and the content covering the whole viewport. */
|
||||
export const clampZoomPan = (
|
||||
{ scale, x, y }: ZoomPan,
|
||||
{ width, height }: ZoomPanSize,
|
||||
maxScale = MAX_ZOOM
|
||||
): ZoomPan => {
|
||||
const clampedScale = Math.min(Math.max(scale, 1), maxScale);
|
||||
if (clampedScale === 1) {
|
||||
return ZOOM_PAN_IDENTITY;
|
||||
}
|
||||
const minX = width - width * clampedScale;
|
||||
const minY = height - height * clampedScale;
|
||||
return {
|
||||
scale: clampedScale,
|
||||
x: Math.min(0, Math.max(minX, x)),
|
||||
y: Math.min(0, Math.max(minY, y)),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Zooms to a new scale while the point under the cursor or between the
|
||||
* fingers stays where it is. The point is relative to the viewport.
|
||||
*/
|
||||
export const zoomAtPoint = (
|
||||
zoomPan: ZoomPan,
|
||||
scale: number,
|
||||
point: { x: number; y: number },
|
||||
size: ZoomPanSize,
|
||||
maxScale = MAX_ZOOM
|
||||
): ZoomPan => {
|
||||
const clampedScale = Math.min(Math.max(scale, 1), maxScale);
|
||||
const ratio = clampedScale / zoomPan.scale;
|
||||
return clampZoomPan(
|
||||
{
|
||||
scale: clampedScale,
|
||||
x: point.x - (point.x - zoomPan.x) * ratio,
|
||||
y: point.y - (point.y - zoomPan.y) * ratio,
|
||||
},
|
||||
size,
|
||||
maxScale
|
||||
);
|
||||
};
|
||||
|
||||
export const panBy = (
|
||||
zoomPan: ZoomPan,
|
||||
dx: number,
|
||||
dy: number,
|
||||
size: ZoomPanSize,
|
||||
maxScale = MAX_ZOOM
|
||||
): ZoomPan =>
|
||||
clampZoomPan(
|
||||
{ ...zoomPan, x: zoomPan.x + dx, y: zoomPan.y + dy },
|
||||
size,
|
||||
maxScale
|
||||
);
|
||||
@@ -19,7 +19,9 @@ interface MinMaxFrame {
|
||||
maxPoint: Point;
|
||||
maxX: number;
|
||||
maxY: number;
|
||||
lastPoint: Point;
|
||||
lastX: number;
|
||||
lastY: number;
|
||||
gapPoint: Point | undefined;
|
||||
}
|
||||
|
||||
@@ -69,7 +71,9 @@ function newFrame(
|
||||
maxPoint: point,
|
||||
maxX: x,
|
||||
maxY: y,
|
||||
lastPoint: point,
|
||||
lastX: x,
|
||||
lastY: y,
|
||||
gapPoint,
|
||||
};
|
||||
}
|
||||
@@ -176,7 +180,9 @@ export function downSampleLineData<
|
||||
if (!frame) {
|
||||
frames.set(frameIndex, newFrame(point, x, y, undefined));
|
||||
} else if (frame.hasValue) {
|
||||
frame.lastPoint = point;
|
||||
frame.lastX = x;
|
||||
frame.lastY = y;
|
||||
// Match the original strict-less / strict-greater comparisons so the
|
||||
// first occurrence wins on ties.
|
||||
if (y < frame.minY) {
|
||||
@@ -192,7 +198,9 @@ export function downSampleLineData<
|
||||
} else {
|
||||
// the frame held nothing but a marker so far
|
||||
frame.hasValue = true;
|
||||
frame.lastPoint = point;
|
||||
frame.lastX = x;
|
||||
frame.lastY = y;
|
||||
frame.minPoint = point;
|
||||
frame.minX = x;
|
||||
frame.minY = y;
|
||||
@@ -203,7 +211,13 @@ export function downSampleLineData<
|
||||
}
|
||||
|
||||
const result: T[] = [];
|
||||
for (const frame of frames.values()) {
|
||||
for (const [frameIndex, frame] of frames) {
|
||||
// A marker followed by a value in its own frame is a gap that closed
|
||||
// within one frame, which is about one device pixel: too narrow to show.
|
||||
// That value may be neither min nor max, so check the frame's last x.
|
||||
const keepGap =
|
||||
frame.gapPoint !== undefined &&
|
||||
Number(getPointData(frame.gapPoint)[0]) >= frame.lastX;
|
||||
if (frame.hasValue) {
|
||||
// The order of the data must be preserved so max may be before min
|
||||
if (frame.minX > frame.maxX) {
|
||||
@@ -213,15 +227,19 @@ export function downSampleLineData<
|
||||
if (frame.minX < frame.maxX) {
|
||||
result.push(frame.maxPoint as T);
|
||||
}
|
||||
}
|
||||
if (frame.gapPoint !== undefined) {
|
||||
// A marker followed by a value in its own frame is a gap that closed
|
||||
// within one frame, which is about one device pixel: too narrow to show.
|
||||
// That value may be neither min nor max, so check the frame's last x.
|
||||
if (Number(getPointData(frame.gapPoint)[0]) >= frame.lastX) {
|
||||
result.push(frame.gapPoint as T);
|
||||
// Step lines hold the last value until the next point, so it must
|
||||
// survive when that point is more than a frame away.
|
||||
if (
|
||||
!keepGap &&
|
||||
!frames.has(frameIndex + 1) &&
|
||||
frame.lastY !== (frame.minX < frame.maxX ? frame.maxY : frame.minY)
|
||||
) {
|
||||
result.push(frame.lastPoint as T);
|
||||
}
|
||||
}
|
||||
if (keepGap) {
|
||||
result.push(frame.gapPoint as T);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
@@ -243,6 +243,10 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
|
||||
}
|
||||
|
||||
private _handleTouchStart = (ev: TouchEvent) => {
|
||||
if (ev.touches.length > 1) {
|
||||
this._cancelResizing();
|
||||
return;
|
||||
}
|
||||
if (this.preventScrimClose) {
|
||||
return;
|
||||
}
|
||||
@@ -269,6 +273,10 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
|
||||
}
|
||||
|
||||
private _handleTouchMove = (ev: TouchEvent) => {
|
||||
if (ev.touches.length > 1) {
|
||||
this._cancelResizing();
|
||||
return;
|
||||
}
|
||||
const currentY = ev.touches[0].clientY;
|
||||
const delta = this._gestureRecognizer.move(currentY);
|
||||
|
||||
@@ -341,6 +349,18 @@ export class HaBottomSheet extends ScrollableFadeMixin(LitElement) {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A second finger makes it a pinch, like zooming a camera picture, which
|
||||
* never moves the sheet. Puts the sheet back where it was.
|
||||
*/
|
||||
private _cancelResizing() {
|
||||
this._unregisterResizeHandlers();
|
||||
if (this._isDragging) {
|
||||
this._isDragging = false;
|
||||
this._animateSnapBack();
|
||||
}
|
||||
}
|
||||
|
||||
private _unregisterResizeHandlers = () => {
|
||||
document.removeEventListener("touchmove", this._handleTouchMove);
|
||||
document.removeEventListener("touchend", this._handleTouchEnd);
|
||||
|
||||
@@ -19,9 +19,11 @@ import {
|
||||
type CameraEntity,
|
||||
} from "../data/camera";
|
||||
import {
|
||||
computeCameraStreamStatus,
|
||||
MJPEG_STREAM,
|
||||
selectCameraStreams,
|
||||
type CameraStream,
|
||||
type CameraStreamStatus,
|
||||
type CameraStreamTracks,
|
||||
type CameraStreamType,
|
||||
} from "../data/camera-streams";
|
||||
@@ -32,10 +34,16 @@ import {
|
||||
formattersContext,
|
||||
} from "../data/context";
|
||||
import "./ha-hls-player";
|
||||
import type { HaHLSPlayer } from "./ha-hls-player";
|
||||
import "./ha-mjpeg-player";
|
||||
import type { HaMjpegPlayer } from "./ha-mjpeg-player";
|
||||
import "./ha-web-rtc-player";
|
||||
import type { HaWebRtcPlayer } from "./ha-web-rtc-player";
|
||||
|
||||
export type { CameraStreamType } from "../data/camera-streams";
|
||||
export type {
|
||||
CameraStreamStatus,
|
||||
CameraStreamType,
|
||||
} from "../data/camera-streams";
|
||||
|
||||
@customElement("ha-camera-stream")
|
||||
export class HaCameraStream extends LitElement {
|
||||
@@ -70,6 +78,13 @@ export class HaCameraStream extends LitElement {
|
||||
@property({ type: Boolean, attribute: "allow-exoplayer" })
|
||||
public allowExoPlayer = false;
|
||||
|
||||
/**
|
||||
* Shows an MJPEG stream in a player that can also open it picture in
|
||||
* picture, which copies its frames into a video while open.
|
||||
*/
|
||||
@property({ type: Boolean, attribute: "mjpeg-video" })
|
||||
public mjpegVideo = false;
|
||||
|
||||
// Video background image before its loaded
|
||||
@state() private _posterUrl?: string;
|
||||
|
||||
@@ -81,10 +96,25 @@ export class HaCameraStream extends LitElement {
|
||||
|
||||
@state() private _webRtcStreams?: CameraStreamTracks;
|
||||
|
||||
// Streams that played their first frame
|
||||
@state() private _loadedStreams: ReadonlySet<CameraStreamType> = new Set();
|
||||
|
||||
// The app plays the HLS stream in its own player, over the page
|
||||
@state() private _hlsInApp = false;
|
||||
|
||||
@query("ha-web-rtc-player") private _webRtcPlayer?: HaWebRtcPlayer;
|
||||
|
||||
@query("ha-mjpeg-player") private _mjpegPlayer?: HaMjpegPlayer;
|
||||
|
||||
@query(
|
||||
"ha-hls-player:not(.hidden), ha-web-rtc-player:not(.hidden), ha-mjpeg-player"
|
||||
)
|
||||
private _visiblePlayer?: HaHLSPlayer | HaWebRtcPlayer | HaMjpegPlayer;
|
||||
|
||||
private _visibleStreamType?: CameraStreamType;
|
||||
|
||||
private _status?: CameraStreamStatus;
|
||||
|
||||
private _capabilitiesRequest = 0;
|
||||
|
||||
private _thumbnailApi = memoizeOne(
|
||||
@@ -118,6 +148,17 @@ export class HaCameraStream extends LitElement {
|
||||
this._getCapabilities();
|
||||
this._getPosterUrl();
|
||||
}
|
||||
|
||||
const oldConnection = changedProps.get("_connection") as
|
||||
ContextType<typeof connectionContext> | undefined;
|
||||
if (
|
||||
oldConnection &&
|
||||
!oldConnection.connected &&
|
||||
this._connection.connected
|
||||
) {
|
||||
// An MJPEG stream doesn't come back on its own
|
||||
this._restartMjpeg();
|
||||
}
|
||||
}
|
||||
|
||||
/** The microphone track sent to the camera, only on WebRTC streams. */
|
||||
@@ -125,6 +166,22 @@ export class HaCameraStream extends LitElement {
|
||||
return this._webRtcPlayer?.microphoneTrack;
|
||||
}
|
||||
|
||||
/** The video of the shown stream. */
|
||||
public get videoElement(): HTMLVideoElement | undefined {
|
||||
return this._visiblePlayer?.videoElement;
|
||||
}
|
||||
|
||||
/** Opens the video of the shown stream picture in picture. */
|
||||
public async requestPictureInPicture() {
|
||||
const player = this._visiblePlayer;
|
||||
// An MJPEG stream first has to start copying its image into the video
|
||||
if (player && "requestPictureInPicture" in player) {
|
||||
await player.requestPictureInPicture();
|
||||
return;
|
||||
}
|
||||
await this.videoElement?.requestPictureInPicture();
|
||||
}
|
||||
|
||||
/** Toggles sending the microphone to the camera, only on WebRTC streams. */
|
||||
public async toggleMicrophone() {
|
||||
await this._webRtcPlayer?.toggleMicrophone();
|
||||
@@ -157,6 +214,27 @@ export class HaCameraStream extends LitElement {
|
||||
this._visibleStreamType = visibleStreamType;
|
||||
fireEvent(this, "stream-type-changed", { type: visibleStreamType });
|
||||
}
|
||||
const status: CameraStreamStatus = {
|
||||
...computeCameraStreamStatus(
|
||||
streams,
|
||||
// Nothing plays while Home Assistant is disconnected
|
||||
this._connection.connected ? this._loadedStreams : new Set(),
|
||||
this._hlsStreams,
|
||||
this._webRtcStreams
|
||||
),
|
||||
inApp: visibleStreamType === STREAM_TYPE_HLS && this._hlsInApp,
|
||||
};
|
||||
if (
|
||||
!this._status ||
|
||||
status.type !== this._status.type ||
|
||||
status.connecting !== this._status.connecting ||
|
||||
status.upgrading !== this._status.upgrading ||
|
||||
status.hasAudio !== this._status.hasAudio ||
|
||||
status.inApp !== this._status.inApp
|
||||
) {
|
||||
this._status = status;
|
||||
fireEvent(this, "camera-stream-status-changed", status);
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
@@ -176,14 +254,25 @@ export class HaCameraStream extends LitElement {
|
||||
return nothing;
|
||||
}
|
||||
if (stream.type === MJPEG_STREAM) {
|
||||
const mjpegPath = computeMJPEGStreamUrl(this.stateObj);
|
||||
const streamUrl = __DEMO__
|
||||
? this.stateObj.attributes.entity_picture
|
||||
: this._connected
|
||||
? computeMJPEGStreamUrl(this.stateObj)
|
||||
? // Like the other streams, as the frontend can be served elsewhere
|
||||
mjpegPath && this._connection.hassUrl(mjpegPath)
|
||||
: this._posterUrl;
|
||||
if (!streamUrl) {
|
||||
return nothing;
|
||||
}
|
||||
if (this.mjpegVideo) {
|
||||
return html`<ha-mjpeg-player
|
||||
.src=${streamUrl}
|
||||
.alt=${`Preview of the ${this._formatters?.formatEntityName(this.stateObj) ?? ""} camera.`}
|
||||
.aspectRatio=${this.aspectRatio}
|
||||
.fitMode=${this.fitMode}
|
||||
@load=${this._handleMjpegLoad}
|
||||
></ha-mjpeg-player>`;
|
||||
}
|
||||
return html`<img
|
||||
.src=${streamUrl}
|
||||
style=${styleMap({
|
||||
@@ -205,6 +294,8 @@ export class HaCameraStream extends LitElement {
|
||||
.entityid=${this.stateObj.entity_id}
|
||||
.posterUrl=${this._posterUrl}
|
||||
@streams=${this._handleHlsStreams}
|
||||
@load=${this._handleHlsLoad}
|
||||
@exoplayer-changed=${this._handleExoPlayerChanged}
|
||||
class=${stream.visible ? "" : "hidden"}
|
||||
.aspectRatio=${this.aspectRatio}
|
||||
.fitMode=${this.fitMode}
|
||||
@@ -220,6 +311,7 @@ export class HaCameraStream extends LitElement {
|
||||
.entityid=${this.stateObj.entity_id}
|
||||
.posterUrl=${this._posterUrl}
|
||||
@streams=${this._handleWebRtcStreams}
|
||||
@load=${this._handleWebRtcLoad}
|
||||
class=${stream.visible ? "" : "hidden"}
|
||||
.aspectRatio=${this.aspectRatio}
|
||||
.fitMode=${this.fitMode}
|
||||
@@ -261,6 +353,27 @@ export class HaCameraStream extends LitElement {
|
||||
private _resetStreams() {
|
||||
this._hlsStreams = undefined;
|
||||
this._webRtcStreams = undefined;
|
||||
this._loadedStreams = new Set();
|
||||
this._hlsInApp = false;
|
||||
this._mjpegPlayer?.restart();
|
||||
}
|
||||
|
||||
private _restartMjpeg() {
|
||||
this._setLoaded(MJPEG_STREAM, false);
|
||||
this._mjpegPlayer?.restart();
|
||||
}
|
||||
|
||||
private _setLoaded(type: CameraStreamType, loaded: boolean) {
|
||||
if (this._loadedStreams.has(type) === loaded) {
|
||||
return;
|
||||
}
|
||||
const loadedStreams = new Set(this._loadedStreams);
|
||||
if (loaded) {
|
||||
loadedStreams.add(type);
|
||||
} else {
|
||||
loadedStreams.delete(type);
|
||||
}
|
||||
this._loadedStreams = loadedStreams;
|
||||
}
|
||||
|
||||
private async _getPosterUrl(): Promise<void> {
|
||||
@@ -278,11 +391,33 @@ export class HaCameraStream extends LitElement {
|
||||
}
|
||||
|
||||
private _handleImageLoad() {
|
||||
this._setLoaded(MJPEG_STREAM, true);
|
||||
fireEvent(this, "load");
|
||||
}
|
||||
|
||||
private _handleMjpegLoad() {
|
||||
this._setLoaded(MJPEG_STREAM, true);
|
||||
}
|
||||
|
||||
private _handleHlsLoad() {
|
||||
this._setLoaded(STREAM_TYPE_HLS, true);
|
||||
}
|
||||
|
||||
private _handleExoPlayerChanged(
|
||||
ev: HASSDomEvent<HASSDomEvents["exoplayer-changed"]>
|
||||
) {
|
||||
this._hlsInApp = ev.detail.active;
|
||||
}
|
||||
|
||||
private _handleWebRtcLoad() {
|
||||
this._setLoaded(STREAM_TYPE_WEB_RTC, true);
|
||||
}
|
||||
|
||||
private _handleHlsStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
|
||||
this._hlsStreams = ev.detail;
|
||||
if (!ev.detail.hasVideo) {
|
||||
this._setLoaded(STREAM_TYPE_HLS, false);
|
||||
}
|
||||
}
|
||||
|
||||
private _handleWebRtcStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
|
||||
@@ -294,9 +429,13 @@ export class HaCameraStream extends LitElement {
|
||||
) {
|
||||
// Without another stream type, keep the player to show why it failed.
|
||||
// Only a browser without WebRTC falls back to MJPEG.
|
||||
this._setLoaded(STREAM_TYPE_WEB_RTC, false);
|
||||
return;
|
||||
}
|
||||
this._webRtcStreams = ev.detail;
|
||||
if (!ev.detail.hasVideo) {
|
||||
this._setLoaded(STREAM_TYPE_WEB_RTC, false);
|
||||
}
|
||||
}
|
||||
|
||||
private _streams = memoizeOne(
|
||||
@@ -318,7 +457,8 @@ export class HaCameraStream extends LitElement {
|
||||
|
||||
static styles = css`
|
||||
:host,
|
||||
img {
|
||||
img,
|
||||
ha-mjpeg-player {
|
||||
display: block;
|
||||
}
|
||||
|
||||
@@ -350,6 +490,7 @@ declare global {
|
||||
load: undefined;
|
||||
"stream-type-changed": { type?: CameraStreamType };
|
||||
"camera-capabilities-changed": { capabilities?: CameraCapabilities };
|
||||
"camera-stream-status-changed": CameraStreamStatus;
|
||||
streams: {
|
||||
hasAudio: boolean;
|
||||
hasVideo: boolean;
|
||||
|
||||
@@ -55,6 +55,15 @@ export class HaFilterBlueprints extends LitElement {
|
||||
|
||||
private _relatedRequestId = 0;
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
// The config pages are cached, so an item may have been edited while this
|
||||
// filter was not on screen
|
||||
if (this.hasUpdated && this.value?.length) {
|
||||
this._findRelated();
|
||||
}
|
||||
}
|
||||
|
||||
public willUpdate(properties: PropertyValues<this>) {
|
||||
super.willUpdate(properties);
|
||||
|
||||
|
||||
@@ -74,6 +74,15 @@ export class HaFilterDevices extends LitElement {
|
||||
|
||||
private _relatedRequestId = 0;
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
// The config pages are cached, so an item may have been edited while this
|
||||
// filter was not on screen
|
||||
if (this.hasUpdated && this.value?.length) {
|
||||
this._findRelated();
|
||||
}
|
||||
}
|
||||
|
||||
public willUpdate(properties: PropertyValues<this>) {
|
||||
super.willUpdate(properties);
|
||||
|
||||
|
||||
@@ -80,6 +80,15 @@ export class HaFilterEntities extends LitElement {
|
||||
|
||||
private _relatedRequestId = 0;
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
// The config pages are cached, so an item may have been edited while this
|
||||
// filter was not on screen
|
||||
if (this.hasUpdated && this.value?.length) {
|
||||
this._findRelated();
|
||||
}
|
||||
}
|
||||
|
||||
public willUpdate(properties: PropertyValues<this>) {
|
||||
super.willUpdate(properties);
|
||||
|
||||
|
||||
@@ -110,6 +110,21 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
|
||||
private _relatedRequestId = 0;
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
// The config pages are cached, so an item may have been edited while this
|
||||
// filter was not on screen
|
||||
if (
|
||||
this.hasUpdated &&
|
||||
this.value &&
|
||||
(this.value.areas?.length ||
|
||||
this.value.floors?.length ||
|
||||
this.value.no_area)
|
||||
) {
|
||||
this._findRelated();
|
||||
}
|
||||
}
|
||||
|
||||
public willUpdate(properties: PropertyValues) {
|
||||
super.willUpdate(properties);
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ type HlsLite = Omit<
|
||||
const HIDDEN_CLEANUP_DELAY = 60000;
|
||||
|
||||
@customElement("ha-hls-player")
|
||||
class HaHLSPlayer extends LitElement {
|
||||
export class HaHLSPlayer extends LitElement {
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
@@ -111,6 +111,11 @@ class HaHLSPlayer extends LitElement {
|
||||
}
|
||||
};
|
||||
|
||||
/** The video that plays the stream, undefined while the app plays it. */
|
||||
public get videoElement(): HTMLVideoElement | undefined {
|
||||
return this._exoPlayer ? undefined : (this._videoEl ?? undefined);
|
||||
}
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
HaHLSPlayer.streamCount += 1;
|
||||
@@ -309,6 +314,7 @@ class HaHLSPlayer extends LitElement {
|
||||
|
||||
private async _renderHLSExoPlayer(url: string) {
|
||||
this._exoPlayer = true;
|
||||
fireEvent(this, "exoplayer-changed", { active: true });
|
||||
window.addEventListener("resize", this._resizeExoPlayer);
|
||||
this.updateComplete.then(() => nextRender()).then(this._resizeExoPlayer);
|
||||
this._videoEl.style.visibility = "hidden";
|
||||
@@ -444,6 +450,7 @@ class HaHLSPlayer extends LitElement {
|
||||
window.removeEventListener("resize", this._resizeExoPlayer);
|
||||
this._config.auth.external!.fireMessage({ type: "exoplayer/stop" });
|
||||
this._exoPlayer = false;
|
||||
fireEvent(this, "exoplayer-changed", { active: false });
|
||||
}
|
||||
if (this._videoEl) {
|
||||
this._videoEl.removeAttribute("src");
|
||||
@@ -505,6 +512,10 @@ class HaHLSPlayer extends LitElement {
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HASSDomEvents {
|
||||
"exoplayer-changed": { active: boolean };
|
||||
}
|
||||
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-hls-player": HaHLSPlayer;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { live } from "lit/directives/live";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
|
||||
const LOAD_CHECK_INTERVAL = 250;
|
||||
|
||||
// Limits the copying, MJPEG streams rarely send more frames than this
|
||||
const PICTURE_IN_PICTURE_FRAME_RATE = 15;
|
||||
|
||||
/**
|
||||
* Shows an MJPEG stream as an image, like any browser can. Picture in
|
||||
* picture only works with a video, so while it is open, the image is copied
|
||||
* into a canvas that a hidden video plays. The video only plays then, so
|
||||
* browsers don't offer picture in picture on their own.
|
||||
*/
|
||||
@customElement("ha-mjpeg-player")
|
||||
export class HaMjpegPlayer extends LitElement {
|
||||
@property() public src?: string;
|
||||
|
||||
@property() public alt?: string;
|
||||
|
||||
@property({ attribute: false }) public aspectRatio?: number;
|
||||
|
||||
@property({ attribute: false }) public fitMode?: "cover" | "contain" | "fill";
|
||||
|
||||
@state() private _loaded = false;
|
||||
|
||||
// The image can be copied, it is not from another origin
|
||||
@state() private _canCopy = false;
|
||||
|
||||
@query("#stream") private _imageEl?: HTMLImageElement;
|
||||
|
||||
@query("video") private _videoEl?: HTMLVideoElement;
|
||||
|
||||
private _canvas?: HTMLCanvasElement;
|
||||
|
||||
private _stream?: MediaStream;
|
||||
|
||||
private _loadCheckInterval?: number;
|
||||
|
||||
private _drawInterval?: number;
|
||||
|
||||
/** The video for picture in picture, undefined when it can't be shown. */
|
||||
public get videoElement(): HTMLVideoElement | undefined {
|
||||
return this._canCopy ? this._videoEl : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts copying the image into the video and opens it picture in
|
||||
* picture. Stops copying again when it can't be opened.
|
||||
*/
|
||||
public async requestPictureInPicture(): Promise<void> {
|
||||
const video = this._videoEl;
|
||||
if (!this._canCopy || !video) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (!this._stream) {
|
||||
this._drawFrame();
|
||||
// Captures a frame whenever the canvas is drawn
|
||||
this._stream = this._canvas!.captureStream();
|
||||
video.srcObject = this._stream;
|
||||
this._drawInterval = window.setInterval(
|
||||
() => this._drawFrame(),
|
||||
1000 / PICTURE_IN_PICTURE_FRAME_RATE
|
||||
);
|
||||
}
|
||||
// Picture in picture needs the video to play first
|
||||
await video.play();
|
||||
await video.requestPictureInPicture();
|
||||
} catch (err: unknown) {
|
||||
this._stopVideo();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Loads the stream again and waits for its first frame. */
|
||||
public restart() {
|
||||
if (!this.hasUpdated) {
|
||||
return;
|
||||
}
|
||||
// Without a source, the image drops its last frame, so the next one
|
||||
// really is from the new stream
|
||||
this._imageEl?.removeAttribute("src");
|
||||
this._loaded = false;
|
||||
this._canCopy = false;
|
||||
// Sets the source again, also when nothing else changed
|
||||
this.requestUpdate();
|
||||
this._startLoadCheck();
|
||||
}
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
if (this.hasUpdated && !this._loaded) {
|
||||
this._startLoadCheck();
|
||||
}
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._stopLoadCheck();
|
||||
this._stopVideo();
|
||||
}
|
||||
|
||||
protected firstUpdated() {
|
||||
this._startLoadCheck();
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.src) {
|
||||
return nothing;
|
||||
}
|
||||
const style = styleMap({
|
||||
aspectRatio: this.aspectRatio,
|
||||
objectFit: this.fitMode,
|
||||
});
|
||||
return html`
|
||||
${this._loaded ? nothing : html`<div class="placeholder"></div>`}
|
||||
<img
|
||||
id="stream"
|
||||
class=${this._loaded ? "" : "loading"}
|
||||
.src=${live(this.src)}
|
||||
alt=${this.alt ?? ""}
|
||||
style=${style}
|
||||
draggable="false"
|
||||
@load=${this._checkLoaded}
|
||||
@error=${this._stopLoadCheck}
|
||||
/>
|
||||
<video
|
||||
muted
|
||||
playsinline
|
||||
disableremoteplayback
|
||||
aria-hidden="true"
|
||||
@leavepictureinpicture=${this._stopVideo}
|
||||
></video>
|
||||
`;
|
||||
}
|
||||
|
||||
private _startLoadCheck() {
|
||||
this._stopLoadCheck();
|
||||
this._loadCheckInterval = window.setInterval(
|
||||
() => this._checkLoaded(),
|
||||
LOAD_CHECK_INTERVAL
|
||||
);
|
||||
}
|
||||
|
||||
private _stopLoadCheck() {
|
||||
clearInterval(this._loadCheckInterval);
|
||||
this._loadCheckInterval = undefined;
|
||||
}
|
||||
|
||||
// An MJPEG stream never completes loading, so only wait for a first frame
|
||||
private _checkLoaded() {
|
||||
if (!this._imageEl?.naturalWidth) {
|
||||
return;
|
||||
}
|
||||
this._canCopy = this._testCopy();
|
||||
this._setLoaded();
|
||||
}
|
||||
|
||||
private _setLoaded() {
|
||||
this._stopLoadCheck();
|
||||
if (!this._loaded) {
|
||||
this._loaded = true;
|
||||
fireEvent(this, "load");
|
||||
}
|
||||
}
|
||||
|
||||
/** An image from another origin can't be copied out of a canvas. */
|
||||
private _testCopy(): boolean {
|
||||
try {
|
||||
this._drawFrame();
|
||||
this._canvas?.getContext("2d")?.getImageData(0, 0, 1, 1);
|
||||
return Boolean(this._canvas);
|
||||
} catch (_err: unknown) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private _drawFrame() {
|
||||
const image = this._imageEl;
|
||||
if (!image?.naturalWidth) {
|
||||
return;
|
||||
}
|
||||
if (!this._canvas) {
|
||||
this._canvas = document.createElement("canvas");
|
||||
}
|
||||
const canvas = this._canvas;
|
||||
if (
|
||||
canvas.width !== image.naturalWidth ||
|
||||
canvas.height !== image.naturalHeight
|
||||
) {
|
||||
canvas.width = image.naturalWidth;
|
||||
canvas.height = image.naturalHeight;
|
||||
}
|
||||
canvas.getContext("2d")?.drawImage(image, 0, 0);
|
||||
}
|
||||
|
||||
private _stopVideo = () => {
|
||||
clearInterval(this._drawInterval);
|
||||
this._drawInterval = undefined;
|
||||
this._stream?.getTracks().forEach((track) => track.stop());
|
||||
this._stream = undefined;
|
||||
if (this._videoEl) {
|
||||
this._videoEl.srcObject = null;
|
||||
}
|
||||
};
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
max-height: var(--video-max-height, calc(100vh - 97px));
|
||||
object-fit: contain;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
|
||||
/* Keeps the room of a picture until the first frame, so nothing jumps */
|
||||
.placeholder {
|
||||
aspect-ratio: 16 / 9;
|
||||
max-height: var(--video-max-height, calc(100vh - 97px));
|
||||
}
|
||||
|
||||
/* Shows over the placeholder as soon as the browser draws a frame, some
|
||||
browsers don't load a stream they don't show */
|
||||
img.loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* Only plays for picture in picture, kept rendered so it can play */
|
||||
video {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-mjpeg-player": HaMjpegPlayer;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type {
|
||||
LocationSelector,
|
||||
LocationSelectorValue,
|
||||
} from "../../data/selector";
|
||||
|
||||
export const DEFAULT_RADIUS = 1000;
|
||||
|
||||
/**
|
||||
* The selector's value from its form's value. A value that never had a radius
|
||||
* falls back to the default the map draws, while a radius the user cleared is
|
||||
* left out so the field stays empty. A read-only radius is kept as is because
|
||||
* core stores it as a float.
|
||||
*/
|
||||
export const computeLocationSelectorValue = (
|
||||
selector: LocationSelector,
|
||||
value: LocationSelectorValue
|
||||
): LocationSelectorValue => {
|
||||
if (!selector.location?.radius) {
|
||||
return { latitude: value.latitude, longitude: value.longitude };
|
||||
}
|
||||
const radius = "radius" in value ? value.radius : DEFAULT_RADIUS;
|
||||
if (radius === undefined || radius === null) {
|
||||
return { latitude: value.latitude, longitude: value.longitude };
|
||||
}
|
||||
return {
|
||||
latitude: value.latitude,
|
||||
longitude: value.longitude,
|
||||
radius: selector.location.radius_readonly ? radius : Math.round(radius),
|
||||
};
|
||||
};
|
||||
@@ -12,6 +12,10 @@ import type { MarkerLocation } from "../map/ha-locations-editor";
|
||||
import "../map/ha-locations-editor";
|
||||
import "../ha-form/ha-form";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import {
|
||||
computeLocationSelectorValue,
|
||||
DEFAULT_RADIUS,
|
||||
} from "./compute-location-selector-value";
|
||||
|
||||
@customElement("ha-selector-location")
|
||||
export class HaLocationSelector extends LitElement {
|
||||
@@ -51,7 +55,7 @@ export class HaLocationSelector extends LitElement {
|
||||
{
|
||||
name: "radius",
|
||||
required: true,
|
||||
default: 1000,
|
||||
default: DEFAULT_RADIUS,
|
||||
disabled: !!radius_readonly,
|
||||
selector: {
|
||||
number: {
|
||||
@@ -74,7 +78,7 @@ export class HaLocationSelector extends LitElement {
|
||||
this.value = {
|
||||
latitude: this.hass.config.latitude,
|
||||
longitude: this.hass.config.longitude,
|
||||
radius: this.selector.location?.radius ? 1000 : undefined,
|
||||
radius: this.selector.location?.radius ? DEFAULT_RADIUS : undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -126,7 +130,9 @@ export class HaLocationSelector extends LitElement {
|
||||
!value || isNaN(value.longitude)
|
||||
? this.hass.config.longitude
|
||||
: value.longitude,
|
||||
radius: selector.location?.radius ? value?.radius || 1000 : undefined,
|
||||
radius: selector.location?.radius
|
||||
? value?.radius || DEFAULT_RADIUS
|
||||
: undefined,
|
||||
radius_color: selector.location?.color || zoneRadiusColor,
|
||||
name: selector.location?.name,
|
||||
icon:
|
||||
@@ -155,20 +161,8 @@ export class HaLocationSelector extends LitElement {
|
||||
|
||||
private _valueChanged(ev: CustomEvent) {
|
||||
ev.stopPropagation();
|
||||
const value = ev.detail.value;
|
||||
const radius = Math.round(ev.detail.value.radius);
|
||||
|
||||
fireEvent(this, "value-changed", {
|
||||
value: {
|
||||
latitude: value.latitude,
|
||||
longitude: value.longitude,
|
||||
...(this.selector.location?.radius &&
|
||||
!this.selector.location?.radius_readonly
|
||||
? {
|
||||
radius,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
value: computeLocationSelectorValue(this.selector, ev.detail.value),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,21 @@ import type { ContextType } from "@lit/context";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { cssColorToHex } from "../common/color/hex";
|
||||
import { normalizeLuminance } from "../common/color/palette";
|
||||
import { consume } from "../common/decorators/consume";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { uiContext } from "../data/context";
|
||||
import {
|
||||
getThemeModeSupport,
|
||||
getThemeVariables,
|
||||
themeDefinesColor,
|
||||
type Theme,
|
||||
type ThemeModeSupport,
|
||||
} from "../data/ws-themes";
|
||||
import {
|
||||
DefaultAccentColor,
|
||||
DefaultPrimaryColor,
|
||||
@@ -41,6 +52,10 @@ export class HaThemeSettings extends LitElement {
|
||||
@consume({ context: uiContext, subscribe: true })
|
||||
private _ui!: ContextType<typeof uiContext>;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@property({ attribute: false }) public selectedTheme?: ThemeSettings | null;
|
||||
|
||||
@property({ attribute: false }) public labels?: ThemeSettingsLabels;
|
||||
@@ -69,12 +84,30 @@ export class HaThemeSettings extends LitElement {
|
||||
? this._ui.themes.default_dark_theme || this._ui.themes.default_theme
|
||||
: this._ui.themes.default_theme;
|
||||
|
||||
const showDarkMode =
|
||||
curTheme === HOME_ASSISTANT_THEME ||
|
||||
const customTheme =
|
||||
curTheme && curTheme !== HOME_ASSISTANT_THEME
|
||||
? this._ui.themes.themes[curTheme]
|
||||
: undefined;
|
||||
const showThemeOptions = curTheme === HOME_ASSISTANT_THEME || !!customTheme;
|
||||
|
||||
// With "use default theme", the mode picks the default light or dark theme.
|
||||
const modeSupport: ThemeModeSupport =
|
||||
!customTheme ||
|
||||
(curThemeIsUseDefault &&
|
||||
this._ui.themes.default_dark_theme &&
|
||||
this._ui.themes.default_theme) ||
|
||||
this._supportsModeSelection(curTheme);
|
||||
this._ui.themes.default_theme)
|
||||
? "both"
|
||||
: getThemeModeSupport(customTheme);
|
||||
|
||||
const themeColors = this._themeColors(
|
||||
customTheme,
|
||||
this._ui.themes.darkMode
|
||||
);
|
||||
const primaryColorLocked = themeColors.primary !== undefined;
|
||||
const accentColorLocked = themeColors.accent !== undefined;
|
||||
const showReset =
|
||||
(!!themeSettings?.primaryColor && !primaryColorLocked) ||
|
||||
(!!themeSettings?.accentColor && !accentColorLocked);
|
||||
|
||||
return html`
|
||||
<ha-list-base>
|
||||
@@ -108,9 +141,20 @@ export class HaThemeSettings extends LitElement {
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
showDarkMode
|
||||
showThemeOptions
|
||||
? html`
|
||||
<ha-list-item-base>
|
||||
<ha-list-item-base
|
||||
class="set-by-theme"
|
||||
wrap-supporting-text
|
||||
.supportingText=${
|
||||
modeSupport !== "both"
|
||||
? this._localize(
|
||||
`ui.panel.profile.themes.mode_set_by_theme.${modeSupport}`,
|
||||
{ theme: curTheme }
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<span slot="headline"
|
||||
>${this.labels?.mode ?? "Theme mode"}</span
|
||||
>
|
||||
@@ -118,13 +162,8 @@ export class HaThemeSettings extends LitElement {
|
||||
slot="end"
|
||||
@change=${this._handleDarkMode}
|
||||
name="dark_mode"
|
||||
.value=${
|
||||
themeSettings?.dark === undefined
|
||||
? "auto"
|
||||
: themeSettings.dark
|
||||
? "dark"
|
||||
: "light"
|
||||
}
|
||||
.value=${this._modeValue(modeSupport, themeSettings?.dark)}
|
||||
.disabled=${modeSupport !== "both"}
|
||||
orientation="horizontal"
|
||||
>
|
||||
<ha-radio-option value="auto">
|
||||
@@ -142,31 +181,56 @@ export class HaThemeSettings extends LitElement {
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
curTheme === HOME_ASSISTANT_THEME
|
||||
showThemeOptions
|
||||
? html`
|
||||
<ha-list-item-base>
|
||||
<ha-list-item-base
|
||||
class="set-by-theme"
|
||||
wrap-supporting-text
|
||||
.supportingText=${
|
||||
primaryColorLocked || accentColorLocked
|
||||
? this._localize(
|
||||
`ui.panel.profile.themes.colors_set_by_theme.${
|
||||
primaryColorLocked && accentColorLocked
|
||||
? "both"
|
||||
: primaryColorLocked
|
||||
? "primary"
|
||||
: "accent"
|
||||
}`,
|
||||
{ theme: curTheme }
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<span slot="headline"
|
||||
>${this.labels?.colors ?? "Custom colors"}</span
|
||||
>
|
||||
<div slot="end" class="color-pickers">
|
||||
<ha-input
|
||||
.value=${themeSettings?.primaryColor || DefaultPrimaryColor}
|
||||
.value=${
|
||||
themeColors.primary ??
|
||||
(themeSettings?.primaryColor || DefaultPrimaryColor)
|
||||
}
|
||||
type="color"
|
||||
.label=${this.labels?.primaryColor ?? "Primary color"}
|
||||
.name=${"primaryColor"}
|
||||
.disabled=${primaryColorLocked}
|
||||
@change=${this._handleColorChange}
|
||||
></ha-input>
|
||||
<ha-input
|
||||
.value=${themeSettings?.accentColor || DefaultAccentColor}
|
||||
.value=${
|
||||
themeColors.accent ??
|
||||
(themeSettings?.accentColor || DefaultAccentColor)
|
||||
}
|
||||
type="color"
|
||||
.label=${this.labels?.accentColor ?? "Accent color"}
|
||||
.name=${"accentColor"}
|
||||
.disabled=${accentColorLocked}
|
||||
@change=${this._handleColorChange}
|
||||
></ha-input>
|
||||
</div>
|
||||
</ha-list-item-base>
|
||||
${
|
||||
themeSettings?.primaryColor || themeSettings?.accentColor
|
||||
showReset
|
||||
? html`
|
||||
<div class="reset-row">
|
||||
<ha-button
|
||||
@@ -207,15 +271,49 @@ export class HaThemeSettings extends LitElement {
|
||||
});
|
||||
}
|
||||
|
||||
private _supportsModeSelection(themeName: string): boolean {
|
||||
const theme = this._ui.themes.themes[themeName];
|
||||
if (!theme) {
|
||||
return false;
|
||||
private _modeValue(
|
||||
modeSupport: ThemeModeSupport,
|
||||
dark: boolean | undefined
|
||||
): string {
|
||||
switch (modeSupport) {
|
||||
case "light":
|
||||
case "dark":
|
||||
return modeSupport;
|
||||
case "none":
|
||||
// The theme has fixed colors, so neither light nor dark is accurate.
|
||||
return "";
|
||||
default:
|
||||
return dark === undefined ? "auto" : dark ? "dark" : "light";
|
||||
}
|
||||
|
||||
return !!(theme.modes && "light" in theme.modes && "dark" in theme.modes);
|
||||
}
|
||||
|
||||
/** Colors the theme sets itself, `undefined` when the user can pick them. */
|
||||
private _themeColors = memoizeOne(
|
||||
(
|
||||
theme: Theme | undefined,
|
||||
darkMode: boolean
|
||||
): { primary?: string; accent?: string } => {
|
||||
if (!theme) {
|
||||
return {};
|
||||
}
|
||||
const variables = getThemeVariables(theme, darkMode);
|
||||
const toHex = (value: string | undefined, fallback: string) =>
|
||||
(value && cssColorToHex(value)) || fallback;
|
||||
return {
|
||||
primary: themeDefinesColor(variables, "primary")
|
||||
? toHex(
|
||||
// A theme that only sets the palette uses its base step as primary
|
||||
variables["primary-color"] ?? variables["ha-color-primary-40"],
|
||||
DefaultPrimaryColor
|
||||
)
|
||||
: undefined,
|
||||
accent: themeDefinesColor(variables, "accent")
|
||||
? toHex(variables["accent-color"], DefaultAccentColor)
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
private _handleDarkMode(ev: Event) {
|
||||
let dark: boolean | undefined;
|
||||
switch ((ev.currentTarget as HaRadioGroup).value) {
|
||||
@@ -267,6 +365,9 @@ export class HaThemeSettings extends LitElement {
|
||||
ha-theme-picker {
|
||||
min-width: 150px;
|
||||
}
|
||||
.set-by-theme::part(supporting-text) {
|
||||
color: var(--ha-color-text-secondary);
|
||||
}
|
||||
.color-pickers {
|
||||
display: flex;
|
||||
gap: var(--ha-space-2);
|
||||
|
||||
@@ -121,6 +121,11 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
return this._localReturnAudioTrack ? "on" : "off";
|
||||
}
|
||||
|
||||
/** The video that plays the stream, undefined while showing an error. */
|
||||
public get videoElement(): HTMLVideoElement | undefined {
|
||||
return this._videoEl ?? undefined;
|
||||
}
|
||||
|
||||
public get microphoneTrack(): MediaStreamTrack | undefined {
|
||||
return this._localReturnAudioTrack;
|
||||
}
|
||||
@@ -631,10 +636,7 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
if (!this._remoteStream) {
|
||||
return;
|
||||
}
|
||||
// If the track is audio and the player is muted, we do not add it to the stream.
|
||||
if (event.track.kind === "audio" && this.muted) {
|
||||
return;
|
||||
}
|
||||
// Audio is always added, even when muted, so it can be unmuted later
|
||||
this._remoteStream.addTrack(event.track);
|
||||
if (!this.hasUpdated) {
|
||||
await this.updateComplete;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { CSSResultGroup, TemplateResult } from "lit";
|
||||
import { css, html, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import "../ha-checkbox";
|
||||
import "../ha-ripple";
|
||||
import { HaListItemBase } from "./ha-list-item-base";
|
||||
@@ -15,7 +17,8 @@ export type HaListItemOptionSelectionPosition = "start" | "end";
|
||||
*
|
||||
* @summary
|
||||
* Selectable list row (role `option`). Selection state is driven by the parent
|
||||
* `ha-list-selectable`; reflects `aria-selected`. When `appearance="checkbox"`, renders
|
||||
* `ha-list-selectable`; reflects `aria-selected`, and describes an `indeterminate` row
|
||||
* as partly selected through `aria-description`. When `appearance="checkbox"`, renders
|
||||
* a decorative `<ha-checkbox>` (clicks on the row are handled by the listbox).
|
||||
*
|
||||
* @csspart checkbox - Wrapper around the `<ha-checkbox>` when `appearance="checkbox"`.
|
||||
@@ -47,6 +50,10 @@ export class HaListItemOption extends HaListItemBase {
|
||||
|
||||
public override interactive = true;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize?: LocalizeFunc;
|
||||
|
||||
public update(changed: Map<string, unknown>) {
|
||||
super.update(changed);
|
||||
if (changed.has("selected")) {
|
||||
@@ -55,6 +62,18 @@ export class HaListItemOption extends HaListItemBase {
|
||||
if (changed.has("disabled")) {
|
||||
this.setAttribute("aria-disabled", this.disabled ? "true" : "false");
|
||||
}
|
||||
if (changed.has("indeterminate") || changed.has("_localize")) {
|
||||
// `option` has no mixed selection state, so describe it instead of
|
||||
// letting the row read as unselected
|
||||
const description = this.indeterminate
|
||||
? this._localize?.("ui.components.list-item-option.partly_selected")
|
||||
: undefined;
|
||||
if (description) {
|
||||
this.setAttribute("aria-description", description);
|
||||
} else {
|
||||
this.removeAttribute("aria-description");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected _renderBase(inner: TemplateResult): TemplateResult {
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import type { ContextType } from "@lit/context";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import { computeStateDomain } from "../../common/entity/compute_state_domain";
|
||||
import { consumeEntityState } from "../../common/decorators/consume-context-entry";
|
||||
import { consumeEntityStates } from "../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../common/decorators/transform";
|
||||
import { computeDomain } from "../../common/entity/compute_domain";
|
||||
import type { User } from "../../data/user";
|
||||
import { computeUserInitials } from "../../data/user";
|
||||
import { connectionContext, statesContext } from "../../data/context";
|
||||
import { connectionContext, entitiesContext } from "../../data/context";
|
||||
import type { CurrentUser } from "../../types";
|
||||
|
||||
@customElement("ha-user-badge")
|
||||
@@ -21,38 +21,29 @@ class UserBadge extends LitElement {
|
||||
@consume({ context: connectionContext, subscribe: true })
|
||||
private _connection?: ContextType<typeof connectionContext>;
|
||||
|
||||
// Read by the @consumeEntityStates decorator below.
|
||||
@state()
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
private _states?: HassEntities;
|
||||
|
||||
@state() private _personEntityId?: string;
|
||||
@consume({ context: entitiesContext, subscribe: true })
|
||||
@transform<ContextType<typeof entitiesContext>, string[]>({
|
||||
transformer: (entities) =>
|
||||
Object.keys(entities ?? {}).filter(
|
||||
(entityId) => computeDomain(entityId) === "person"
|
||||
),
|
||||
})
|
||||
protected _personEntityIds?: string[];
|
||||
|
||||
@state()
|
||||
@consumeEntityState({ entityIdPath: ["_personEntityId"] })
|
||||
private _personState?: HassEntity;
|
||||
|
||||
public willUpdate(changedProps: PropertyValues) {
|
||||
super.willUpdate(changedProps);
|
||||
// Re-scan for the user's person entity when the user changes, or when the
|
||||
// states change while we don't have a (still-present) person entity. Once
|
||||
// resolved, `_personState` keeps the picture up to date via
|
||||
// `consumeEntityState`, so there's no need to rescan on every state update.
|
||||
if (
|
||||
changedProps.has("user") ||
|
||||
(changedProps.has("_states") &&
|
||||
(!this._personEntityId || !this._states?.[this._personEntityId]))
|
||||
) {
|
||||
this._updatePersonEntityId();
|
||||
}
|
||||
}
|
||||
@consumeEntityStates({ entityIdPath: ["_personEntityIds"] })
|
||||
private _personStates?: Record<string, HassEntity>;
|
||||
|
||||
protected render() {
|
||||
if (!this.user) {
|
||||
return nothing;
|
||||
}
|
||||
const picture =
|
||||
this._personEntityId &&
|
||||
(this._personState?.attributes.entity_picture as string | undefined);
|
||||
const userId = this.user.id;
|
||||
const picture = Object.values(this._personStates ?? {}).find(
|
||||
(entity) => entity.attributes.user_id === userId
|
||||
)?.attributes.entity_picture as string | undefined;
|
||||
|
||||
if (picture && this._connection) {
|
||||
return html`<div
|
||||
@@ -70,22 +61,6 @@ class UserBadge extends LitElement {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private _updatePersonEntityId() {
|
||||
this._personEntityId = undefined;
|
||||
if (!this.user || !this._states) {
|
||||
return;
|
||||
}
|
||||
for (const entity of Object.values(this._states)) {
|
||||
if (
|
||||
entity.attributes.user_id === this.user.id &&
|
||||
computeStateDomain(entity) === "person"
|
||||
) {
|
||||
this._personEntityId = entity.entity_id;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
|
||||
@@ -78,3 +78,45 @@ export const selectCameraStreams = ({
|
||||
{ type: STREAM_TYPE_WEB_RTC, visible: false },
|
||||
];
|
||||
};
|
||||
|
||||
/** What the player tells the user about the connection of its stream. */
|
||||
export interface CameraStreamStatus {
|
||||
/** The stream that is shown, undefined until the camera's types are known */
|
||||
type?: CameraStreamType;
|
||||
/** The shown stream has not played its first frame yet */
|
||||
connecting: boolean;
|
||||
/** A faster stream that connects in the background to replace the shown one */
|
||||
upgrading?: CameraStreamType;
|
||||
/** The shown stream has sound */
|
||||
hasAudio: boolean;
|
||||
/** The app plays the shown stream in its own player, over the page */
|
||||
inApp?: boolean;
|
||||
}
|
||||
|
||||
export const computeCameraStreamStatus = (
|
||||
streams: CameraStream[],
|
||||
loaded: ReadonlySet<CameraStreamType>,
|
||||
hlsStreams?: CameraStreamTracks,
|
||||
webRtcStreams?: CameraStreamTracks
|
||||
): CameraStreamStatus => {
|
||||
const visible = streams.find((stream) => stream.visible);
|
||||
if (!visible) {
|
||||
return { connecting: true, hasAudio: false };
|
||||
}
|
||||
const hidden = streams.find((stream) => !stream.visible);
|
||||
const tracks =
|
||||
visible.type === STREAM_TYPE_HLS
|
||||
? hlsStreams
|
||||
: visible.type === STREAM_TYPE_WEB_RTC
|
||||
? webRtcStreams
|
||||
: undefined;
|
||||
const connecting = !loaded.has(visible.type);
|
||||
return {
|
||||
type: visible.type,
|
||||
connecting,
|
||||
// Only worth mentioning once the shown stream plays, before that the
|
||||
// whole player is connecting
|
||||
upgrading: hidden && !connecting ? hidden.type : undefined,
|
||||
hasAudio: !connecting && (tracks?.hasAudio ?? false),
|
||||
};
|
||||
};
|
||||
@@ -179,3 +179,26 @@ export const isRelatedItemsFilterUsed = (
|
||||
(key === filterName || filterName.includes(key)) && filter.items;
|
||||
return isUsed;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether an item with nothing assigned (no area, device, label, category or
|
||||
* assistant) passes the filters: only a "No area" selection keeps it, any
|
||||
* selected id leaves it out.
|
||||
*/
|
||||
export const filtersMatchUnassignedItem = (
|
||||
filters: DataTableFiltersValues
|
||||
): boolean =>
|
||||
Object.values(filters).every((value) => {
|
||||
if (!value) {
|
||||
return true;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return !value.length;
|
||||
}
|
||||
if ((value as FloorAreasFilterValue).no_area) {
|
||||
return true;
|
||||
}
|
||||
return Object.values(value).every(
|
||||
(selected) => !Array.isArray(selected) || !selected.length
|
||||
);
|
||||
});
|
||||
@@ -42,6 +42,7 @@ import type {
|
||||
StatisticValue,
|
||||
} from "./recorder";
|
||||
import {
|
||||
calculateStatisticSumGrowth,
|
||||
fetchStatistics,
|
||||
getDisplayUnit,
|
||||
getStatisticLabel,
|
||||
@@ -442,6 +443,38 @@ export interface EnergySourceByType {
|
||||
export const energySourcesByType = (prefs: EnergyPreferences) =>
|
||||
groupBy(prefs.energy_sources, (item) => item.type) as EnergySourceByType;
|
||||
|
||||
/** Import cost minus export compensation, or undefined without cost data. */
|
||||
export const calculateGridNetCost = (
|
||||
sources: GridSourceTypeEnergyPreference[],
|
||||
info: EnergyInfo,
|
||||
stats: Statistics
|
||||
): number | undefined => {
|
||||
let total: number | undefined;
|
||||
const add = (
|
||||
energyStatId: string | null,
|
||||
costStatId: string | null,
|
||||
sign: 1 | -1
|
||||
) => {
|
||||
if (!energyStatId) {
|
||||
return;
|
||||
}
|
||||
const statId = costStatId || info.cost_sensors[energyStatId];
|
||||
if (!statId) {
|
||||
return;
|
||||
}
|
||||
const cost = calculateStatisticSumGrowth(stats[statId]);
|
||||
if (calculateStatisticSumGrowth(stats[energyStatId]) === null && !cost) {
|
||||
return;
|
||||
}
|
||||
total = (total ?? 0) + sign * (cost ?? 0);
|
||||
};
|
||||
for (const source of sources) {
|
||||
add(source.stat_energy_from, source.stat_cost, 1);
|
||||
add(source.stat_energy_to, source.stat_compensation, -1);
|
||||
}
|
||||
return total;
|
||||
};
|
||||
|
||||
const ENERGY_DEVICE_NAME = [
|
||||
{ type: "parent_device" },
|
||||
{ type: "device" },
|
||||
|
||||
+27
-1
@@ -5,7 +5,12 @@ import type {
|
||||
HassEntityBase,
|
||||
} from "home-assistant-js-websocket";
|
||||
import { computeDomain } from "../common/entity/compute_domain";
|
||||
import type { ExtEntityRegistryEntry } from "./entity/entity_registry";
|
||||
import { computeStateDomain } from "../common/entity/compute_state_domain";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import type {
|
||||
EntityRegistryDisplayEntry,
|
||||
ExtEntityRegistryEntry,
|
||||
} from "./entity/entity_registry";
|
||||
|
||||
interface GroupEntityAttributes extends HassEntityAttributeBase {
|
||||
entity_id: string[];
|
||||
@@ -40,6 +45,27 @@ export const computeGroupMemberIds = (
|
||||
return Array.isArray(ids) ? ids : undefined;
|
||||
};
|
||||
|
||||
export type GroupMemberEntry = EntityRegistryDisplayEntry &
|
||||
Required<Pick<EntityRegistryDisplayEntry, "platform" | "translation_key">>;
|
||||
|
||||
/**
|
||||
* Registry entries of the members of a group in the domain of the group that
|
||||
* have translations, or an empty list if it is not a group.
|
||||
*/
|
||||
export const computeGroupMemberEntries = (
|
||||
stateObj: HassEntity,
|
||||
entities: HomeAssistant["entities"]
|
||||
): GroupMemberEntry[] => {
|
||||
const domain = computeStateDomain(stateObj);
|
||||
return (computeGroupMemberIds(stateObj) ?? [])
|
||||
.filter((id) => computeDomain(id) === domain)
|
||||
.map((id) => entities[id] as EntityRegistryDisplayEntry | undefined)
|
||||
.filter(
|
||||
(entry): entry is GroupMemberEntry =>
|
||||
!!entry?.translation_key && !!entry.platform
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Drops groups that have a member in `entityIds`, at any depth (a hidden
|
||||
* group in between still counts). A group with no listed member stays, so
|
||||
|
||||
@@ -75,6 +75,7 @@ import type {
|
||||
import { mdiHomeAssistant } from "../resources/home-assistant-logo-svg";
|
||||
import { callWS } from "../util/websocket";
|
||||
import { getConditionDomain, getConditionObjectId } from "./condition";
|
||||
import { computeGroupMemberEntries } from "./group";
|
||||
import { getTriggerDomain, getTriggerObjectId } from "./trigger";
|
||||
|
||||
/** Icon to use when no icon specified for service. */
|
||||
@@ -576,6 +577,38 @@ export const attributeIcon = async (
|
||||
);
|
||||
}
|
||||
}
|
||||
// A group has no icons for the values of its members, for example the
|
||||
// effects of a light group, so use the icon of a member for that value.
|
||||
if (!icon && value !== undefined) {
|
||||
for (const member of computeGroupMemberEntries(state, entities)) {
|
||||
let memberIcons: PlatformIcons | undefined;
|
||||
try {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
memberIcons = await getPlatformIcons(
|
||||
hassConfig,
|
||||
hassConnection,
|
||||
member.platform
|
||||
);
|
||||
} catch {
|
||||
// The icons of a member are optional, so try the other fallbacks
|
||||
continue;
|
||||
}
|
||||
const memberTranslations =
|
||||
memberIcons?.[domain]?.[member.translation_key]?.state_attributes?.[
|
||||
attribute
|
||||
];
|
||||
// The default icon of a member is not an icon for this value
|
||||
icon =
|
||||
memberTranslations &&
|
||||
getIconFromTranslations(value, {
|
||||
...memberTranslations,
|
||||
default: undefined,
|
||||
});
|
||||
if (icon) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!icon) {
|
||||
const entityComponentIcons = await getComponentIcons(
|
||||
hassConnection,
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import type { LocalizeKeys } from "../common/translations/localize";
|
||||
import type { PageNavigation } from "../layouts/hass-tabs-subpage";
|
||||
import type { HomeAssistant, PanelInfo } from "../types";
|
||||
import { MARKETPLACE_NAME } from "../common/translations/name-placeholders";
|
||||
|
||||
export const APP_PANEL = "app";
|
||||
export const HOME_PANEL = "home";
|
||||
@@ -68,6 +69,10 @@ export const getPanelTitle = (
|
||||
hass: Pick<HomeAssistant, "localize">,
|
||||
panel: PanelInfo
|
||||
): string | undefined => {
|
||||
if (panel.url_path === "marketplace") {
|
||||
return MARKETPLACE_NAME;
|
||||
}
|
||||
|
||||
const translationKey = getPanelNameTranslationKey(panel);
|
||||
|
||||
return hass.localize(translationKey) || panel.title || undefined;
|
||||
|
||||
@@ -18,11 +18,7 @@ import type { FuseWeightedKey } from "../resources/fuseMultiTerm";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import type { HassioAddonInfo } from "./hassio/addon";
|
||||
import { domainToName } from "./integration";
|
||||
import {
|
||||
getPanelIcon,
|
||||
getPanelNameTranslationKey,
|
||||
SYSTEM_PANELS,
|
||||
} from "./panel";
|
||||
import { getPanelIcon, getPanelTitle, SYSTEM_PANELS } from "./panel";
|
||||
|
||||
export interface NavigationComboBoxItem extends PickerComboBoxItem {
|
||||
path: string;
|
||||
@@ -59,10 +55,9 @@ const generateNavigationPanelCommands = (
|
||||
Object.entries(panels)
|
||||
.filter(([panelKey]) => !SYSTEM_PANELS.includes(panelKey))
|
||||
.map(([_panelKey, panel]) => {
|
||||
const translationKey = getPanelNameTranslationKey(panel);
|
||||
const icon = getPanelIcon(panel) || "mdi:view-dashboard";
|
||||
|
||||
const primary = localize(translationKey) || panel.title || panel.url_path;
|
||||
const primary = getPanelTitle({ localize }, panel) || panel.url_path;
|
||||
|
||||
const panelApp = apps?.find(({ slug }) => slug === panel.url_path);
|
||||
|
||||
|
||||
@@ -50,3 +50,54 @@ export const subscribeThemes = (
|
||||
conn,
|
||||
onChange
|
||||
);
|
||||
|
||||
/** `none`: the theme has no modes and fixed colors, applied on the light base. */
|
||||
export type ThemeModeSupport = "both" | "light" | "dark" | "none";
|
||||
|
||||
export const getThemeModeSupport = (theme: Theme): ThemeModeSupport => {
|
||||
const modes = theme.modes;
|
||||
const hasLight = !!modes && "light" in modes;
|
||||
const hasDark = !!modes && "dark" in modes;
|
||||
if (hasLight && hasDark) {
|
||||
return "both";
|
||||
}
|
||||
if (hasDark) {
|
||||
return "dark";
|
||||
}
|
||||
if (hasLight) {
|
||||
return "light";
|
||||
}
|
||||
return "none";
|
||||
};
|
||||
|
||||
export const getThemeVariables = (
|
||||
theme: Theme,
|
||||
darkMode: boolean
|
||||
): Partial<ThemeVars> => {
|
||||
const { modes, ...baseVariables } = theme;
|
||||
return {
|
||||
...baseVariables,
|
||||
...(darkMode ? modes?.dark : modes?.light),
|
||||
};
|
||||
};
|
||||
|
||||
/** Setting any primary palette key counts as setting the primary color. */
|
||||
export const themeDefinesColor = (
|
||||
themeVariables: Partial<ThemeVars>,
|
||||
color: "primary" | "accent"
|
||||
): boolean => {
|
||||
if (color === "accent") {
|
||||
return "accent-color" in themeVariables;
|
||||
}
|
||||
return (
|
||||
"primary-color" in themeVariables ||
|
||||
themeDefinesPrimaryPalette(themeVariables)
|
||||
);
|
||||
};
|
||||
|
||||
export const themeDefinesPrimaryPalette = (
|
||||
themeVariables: Partial<ThemeVars>
|
||||
): boolean =>
|
||||
Object.keys(themeVariables).some((key) =>
|
||||
key.startsWith("ha-color-primary-")
|
||||
);
|
||||
@@ -0,0 +1,203 @@
|
||||
import {
|
||||
mdiFilmstrip,
|
||||
mdiImageMultipleOutline,
|
||||
mdiLightningBolt,
|
||||
} from "@mdi/js";
|
||||
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 { CAMERA_STREAM_TYPE_NAMES } from "../../components/camera/ha-camera-stream-badge";
|
||||
import "../../components/ha-adaptive-dialog";
|
||||
import "../../components/ha-alert";
|
||||
import "../../components/ha-expansion-panel";
|
||||
import "../../components/ha-svg-icon";
|
||||
import "../../components/item/ha-list-item-base";
|
||||
import "../../components/list/ha-list-base";
|
||||
import {
|
||||
MJPEG_STREAM,
|
||||
STREAM_TYPE_HLS,
|
||||
STREAM_TYPE_WEB_RTC,
|
||||
type CameraStreamType,
|
||||
type StreamType,
|
||||
} from "../../data/camera-streams";
|
||||
import { haStyleDialog, haStyleDialogFixedTop } from "../../resources/styles";
|
||||
import { DialogMixin } from "../dialog-mixin";
|
||||
import type { CameraStreamInfoDialogParams } from "./show-dialog-camera-stream-info";
|
||||
|
||||
// Ordered from the fastest to the most compatible
|
||||
const STREAM_TYPES: { type: CameraStreamType; icon: string }[] = [
|
||||
{ type: STREAM_TYPE_WEB_RTC, icon: mdiLightningBolt },
|
||||
{ type: STREAM_TYPE_HLS, icon: mdiFilmstrip },
|
||||
{ type: MJPEG_STREAM, icon: mdiImageMultipleOutline },
|
||||
];
|
||||
|
||||
@customElement("dialog-camera-stream-info")
|
||||
class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
|
||||
LitElement
|
||||
) {
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
protected render() {
|
||||
if (!this.params) {
|
||||
return nothing;
|
||||
}
|
||||
const { status, supportedTypes } = this.params;
|
||||
// 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
|
||||
const mjpegInUse = status.type === MJPEG_STREAM;
|
||||
const videoTypes = STREAM_TYPES.filter(({ type }) => type !== MJPEG_STREAM);
|
||||
const isSupported = (type: CameraStreamType) =>
|
||||
!supportedTypes || supportedTypes.includes(type as StreamType);
|
||||
const supported = stillImagesOnly
|
||||
? []
|
||||
: videoTypes.filter(({ type }) => isSupported(type));
|
||||
const unsupported = stillImagesOnly
|
||||
? []
|
||||
: videoTypes.filter(({ type }) => !isSupported(type));
|
||||
const mjpeg = STREAM_TYPES.find(({ type }) => type === MJPEG_STREAM)!;
|
||||
|
||||
return html`
|
||||
<ha-adaptive-dialog
|
||||
open
|
||||
width="medium"
|
||||
.headerTitle=${this._localize("ui.dialogs.camera_stream_info.title")}
|
||||
>
|
||||
<p>
|
||||
${this._localize(
|
||||
stillImagesOnly
|
||||
? "ui.dialogs.camera_stream_info.still_images_only"
|
||||
: "ui.dialogs.camera_stream_info.intro"
|
||||
)}
|
||||
</p>
|
||||
${
|
||||
mjpegInUse && !stillImagesOnly
|
||||
? html`<ha-alert alert-type="info">
|
||||
${this._localize("ui.dialogs.camera_stream_info.fallback_in_use")}
|
||||
</ha-alert>`
|
||||
: nothing
|
||||
}
|
||||
<ha-list-base>
|
||||
${mjpegInUse ? this._renderType(mjpeg) : nothing}
|
||||
${supported.map((item) => this._renderType(item))}
|
||||
</ha-list-base>
|
||||
${
|
||||
unsupported.length
|
||||
? html`
|
||||
<ha-expansion-panel
|
||||
outlined
|
||||
.header=${this._localize(
|
||||
"ui.dialogs.camera_stream_info.not_supported_count",
|
||||
{ count: unsupported.length }
|
||||
)}
|
||||
>
|
||||
<ha-list-base>
|
||||
${unsupported.map((item) => this._renderType(item))}
|
||||
</ha-list-base>
|
||||
</ha-expansion-panel>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
</ha-adaptive-dialog>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderType({
|
||||
type,
|
||||
icon,
|
||||
}: {
|
||||
type: CameraStreamType;
|
||||
icon: string;
|
||||
}) {
|
||||
const { status } = this.params!;
|
||||
const current = !status.connecting && status.type === type;
|
||||
const upgrading = status.upgrading === type;
|
||||
return html`
|
||||
<ha-list-item-base
|
||||
.headline=${CAMERA_STREAM_TYPE_NAMES[type]}
|
||||
.supportingText=${this._localize(
|
||||
`ui.dialogs.camera_stream_info.description.${type}`
|
||||
)}
|
||||
wrap-supporting-text
|
||||
>
|
||||
<ha-svg-icon slot="start" .path=${icon}></ha-svg-icon>
|
||||
${
|
||||
current
|
||||
? html`<span slot="end" class="tag current"
|
||||
>${this._localize("ui.dialogs.camera_stream_info.in_use")}</span
|
||||
>`
|
||||
: upgrading
|
||||
? html`<span slot="end" class="tag"
|
||||
>${this._localize(
|
||||
"ui.dialogs.camera_stream_info.connecting"
|
||||
)}</span
|
||||
>`
|
||||
: nothing
|
||||
}
|
||||
</ha-list-item-base>
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = [
|
||||
haStyleDialog,
|
||||
// At the top like the more info dialog it opens from
|
||||
haStyleDialogFixedTop,
|
||||
css`
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
|
||||
ha-alert {
|
||||
display: block;
|
||||
margin-top: var(--ha-space-4);
|
||||
}
|
||||
|
||||
ha-list-base {
|
||||
margin-top: var(--ha-space-2);
|
||||
}
|
||||
|
||||
ha-list-item-base {
|
||||
--ha-row-item-padding-inline: 0;
|
||||
}
|
||||
|
||||
ha-expansion-panel {
|
||||
display: block;
|
||||
margin-top: var(--ha-space-6);
|
||||
--expansion-panel-summary-padding: 0 var(--ha-space-4);
|
||||
--expansion-panel-content-padding: 0 var(--ha-space-4);
|
||||
}
|
||||
|
||||
ha-list-item-base ha-svg-icon {
|
||||
flex: none;
|
||||
padding: var(--ha-space-2);
|
||||
border-radius: var(--ha-border-radius-circle);
|
||||
background-color: var(--ha-color-fill-neutral-quiet-resting);
|
||||
color: var(--primary-text-color);
|
||||
}
|
||||
|
||||
.tag {
|
||||
font-size: var(--ha-font-size-xs);
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
padding: 2px var(--ha-space-2);
|
||||
border-radius: var(--ha-border-radius-pill);
|
||||
background-color: var(--ha-color-fill-neutral-quiet-resting);
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
|
||||
.tag.current {
|
||||
background-color: var(--ha-color-fill-success-quiet-resting);
|
||||
color: var(--ha-color-on-success-quiet);
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"dialog-camera-stream-info": DialogCameraStreamInfo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import type { CameraStreamStatus, StreamType } from "../../data/camera-streams";
|
||||
|
||||
export interface CameraStreamInfoDialogParams {
|
||||
status: CameraStreamStatus;
|
||||
/** The stream types the camera supports, undefined while unknown */
|
||||
supportedTypes?: StreamType[];
|
||||
}
|
||||
|
||||
export const showCameraStreamInfoDialog = (
|
||||
element: HTMLElement,
|
||||
params: CameraStreamInfoDialogParams
|
||||
) =>
|
||||
fireEvent(element, "show-dialog", {
|
||||
dialogTag: "dialog-camera-stream-info",
|
||||
dialogImport: () => import("./dialog-camera-stream-info"),
|
||||
dialogParams: params,
|
||||
});
|
||||
@@ -9,11 +9,9 @@ import { consumeLocalize } from "../../../common/decorators/consume-context-entr
|
||||
import type { HASSDomEvent } from "../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-button";
|
||||
import "../../../components/ha-camera-stream";
|
||||
import type {
|
||||
CameraStreamType,
|
||||
HaCameraStream,
|
||||
} from "../../../components/ha-camera-stream";
|
||||
import "../../../components/camera/ha-camera-player";
|
||||
import type { HaCameraPlayer } from "../../../components/camera/ha-camera-player";
|
||||
import type { CameraStreamType } from "../../../components/ha-camera-stream";
|
||||
import "../../../components/ha-spinner";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import "../../../components/ha-tooltip";
|
||||
@@ -54,7 +52,7 @@ class MoreInfoCamera extends LitElement {
|
||||
|
||||
@state() private _supportsTwoWayAudio = false;
|
||||
|
||||
@query("ha-camera-stream") private _cameraStream?: HaCameraStream;
|
||||
@query("ha-camera-player") private _cameraStream?: HaCameraPlayer;
|
||||
|
||||
@query(".microphone-meter") private _microphoneMeter?: HTMLElement;
|
||||
|
||||
@@ -122,14 +120,14 @@ class MoreInfoCamera extends LitElement {
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-camera-stream
|
||||
<ha-camera-player
|
||||
.stateObj=${this.stateObj}
|
||||
allow-exoplayer
|
||||
controls
|
||||
keep-awake
|
||||
@microphone-changed=${this._microphoneChanged}
|
||||
@stream-type-changed=${this._streamTypeChanged}
|
||||
@camera-capabilities-changed=${this._capabilitiesChanged}
|
||||
></ha-camera-stream>
|
||||
></ha-camera-player>
|
||||
${this._supportsTwoWayAudio ? this._renderMicrophoneButton() : nothing}
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { html } from "lit";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import { storage } from "../common/decorators/storage";
|
||||
import { isNavigationClick } from "../common/dom/is-navigation-click";
|
||||
import { whenDocumentVisible } from "../common/dom/when-document-visible";
|
||||
import { handleHistoryPop, navigate } from "../common/navigate";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { decodeMoreInfoUrl } from "../common/url/more-info-query-params";
|
||||
@@ -78,6 +79,8 @@ export class HomeAssistantAppEl extends QuickBarMixin(HassElement) {
|
||||
|
||||
private _visiblePromiseResolve?: () => void;
|
||||
|
||||
private _cancelVisibilityRecovery?: () => void;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const path = redirectLegacyToolsPath(curPath());
|
||||
@@ -426,7 +429,9 @@ export class HomeAssistantAppEl extends QuickBarMixin(HassElement) {
|
||||
}
|
||||
}, 300000);
|
||||
}
|
||||
window.addEventListener("focus", () => this._onVisible(), { once: true });
|
||||
this._cancelVisibilityRecovery = whenDocumentVisible(() =>
|
||||
this._onVisible()
|
||||
);
|
||||
}
|
||||
|
||||
private _suspendApp() {
|
||||
@@ -438,6 +443,8 @@ export class HomeAssistantAppEl extends QuickBarMixin(HassElement) {
|
||||
}
|
||||
|
||||
private _onVisible() {
|
||||
this._cancelVisibilityRecovery?.();
|
||||
this._cancelVisibilityRecovery = undefined;
|
||||
// Clear timer to close the connection
|
||||
if (this._hiddenTimeout) {
|
||||
clearTimeout(this._hiddenTimeout);
|
||||
|
||||
@@ -75,13 +75,37 @@ export class ChildPanelReady implements ReactiveController {
|
||||
export class PanelReady {
|
||||
public ready?: Promise<void>;
|
||||
|
||||
private _resolveReady?: () => void;
|
||||
|
||||
public track(element: HTMLElement, waitForReady = false) {
|
||||
this.ready = waitForReady
|
||||
? new Promise((resolve) => {
|
||||
element.addEventListener("hass-panel-ready", () => resolve(), {
|
||||
once: true,
|
||||
});
|
||||
})
|
||||
: undefined;
|
||||
// A panel replaced before it was ready, such as a dashboard that redirects
|
||||
// to another, would never get there. Whoever waits on it waits for the
|
||||
// panel that took its place instead.
|
||||
const resolveReplaced = this._resolveReady;
|
||||
this._resolveReady = undefined;
|
||||
|
||||
if (!waitForReady) {
|
||||
this.ready = undefined;
|
||||
resolveReplaced?.();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.ready = new Promise((resolve) => {
|
||||
this._resolveReady = resolve;
|
||||
element.addEventListener(
|
||||
"hass-panel-ready",
|
||||
() => {
|
||||
if (this._resolveReady === resolve) {
|
||||
resolve();
|
||||
}
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
|
||||
if (resolveReplaced) {
|
||||
void this.ready.then(resolveReplaced);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
} from "@mdi/js";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { haLora } from "../../resources/ha-icons";
|
||||
import { MARKETPLACE_NAME } from "../../common/translations/name-placeholders";
|
||||
import type { PageNavigation } from "../../layouts/hass-tabs-subpage";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { mdiMqttLogo } from "../../resources/mqtt-logo-svg";
|
||||
@@ -92,6 +93,7 @@ export const configSections: Record<string, PageNavigation[]> = {
|
||||
},
|
||||
{
|
||||
path: "/marketplace",
|
||||
name: MARKETPLACE_NAME,
|
||||
translationKey: "marketplace",
|
||||
iconPath: mdiStore,
|
||||
iconColor: "#7C4DFF",
|
||||
|
||||
@@ -85,6 +85,7 @@ import type {
|
||||
DataTableFiltersValue,
|
||||
DataTableFiltersValues,
|
||||
} from "../../../data/data_table_filters";
|
||||
import { filtersMatchUnassignedItem } from "../../../data/data_table_filters";
|
||||
import {
|
||||
fetchDiagnosticHandlers,
|
||||
getConfigEntryDiagnosticsDownloadUrl,
|
||||
@@ -540,7 +541,8 @@ export class HaConfigHelpers extends SubscribeMixin(LitElement) {
|
||||
entityReg: EntityRegistryEntry[],
|
||||
categoryReg?: CategoryRegistryEntry[],
|
||||
labelReg?: LabelRegistryEntry[],
|
||||
filteredStateItems?: string[] | null
|
||||
filteredStateItems?: string[] | null,
|
||||
includeUnassigned = true
|
||||
): HelperItem[] => {
|
||||
if (filteredStateItems === null) {
|
||||
return [];
|
||||
@@ -613,11 +615,15 @@ export class HaConfigHelpers extends SubscribeMixin(LitElement) {
|
||||
}));
|
||||
|
||||
return [...states, ...entries, ...disabledItems]
|
||||
.filter((item) =>
|
||||
filteredStateItems
|
||||
? filteredStateItems?.includes(item.entity_id)
|
||||
: true
|
||||
)
|
||||
.filter((item) => {
|
||||
if (!filteredStateItems) {
|
||||
return true;
|
||||
}
|
||||
// A config entry that has no entity yet has nothing assigned
|
||||
return item.entity_id
|
||||
? filteredStateItems.includes(item.entity_id)
|
||||
: includeUnassigned;
|
||||
})
|
||||
.map((item) => {
|
||||
const entityRegEntry =
|
||||
entityRegistryByEntityId(entityReg)[item.entity_id];
|
||||
@@ -688,7 +694,8 @@ export class HaConfigHelpers extends SubscribeMixin(LitElement) {
|
||||
this._entityReg,
|
||||
this._categories,
|
||||
this._labels,
|
||||
this._filteredHelperEntityIds
|
||||
this._filteredHelperEntityIds,
|
||||
filtersMatchUnassignedItem(this._filters)
|
||||
);
|
||||
return html`
|
||||
<hass-tabs-subpage-data-table
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
} from "../../../../data/context";
|
||||
import type { EnergyData, EnergySourceByType } from "../../../../data/energy";
|
||||
import {
|
||||
calculateGridNetCost,
|
||||
energySourcesByType,
|
||||
getBatteryEnergyStatIds,
|
||||
getBatteryName,
|
||||
@@ -362,15 +363,11 @@ export class HuiEnergySourcesTableCard
|
||||
}
|
||||
|
||||
let totalGrid = 0;
|
||||
let totalGridCost = 0;
|
||||
let gridImportIdx = 0;
|
||||
let gridExportIdx = 0;
|
||||
let totalBattery = 0;
|
||||
|
||||
let hasGridCost = false;
|
||||
|
||||
let totalGridCompare = 0;
|
||||
let totalGridCostCompare = 0;
|
||||
let totalBatteryCompare = 0;
|
||||
|
||||
const totals = {
|
||||
@@ -477,6 +474,21 @@ export class HuiEnergySourcesTableCard
|
||||
|
||||
const compare = this._data.statsCompare !== undefined;
|
||||
|
||||
const gridCost = types.grid
|
||||
? calculateGridNetCost(types.grid, this._data.info, this._data.stats)
|
||||
: undefined;
|
||||
const gridCostCompare =
|
||||
compare && types.grid
|
||||
? calculateGridNetCost(
|
||||
types.grid,
|
||||
this._data.info,
|
||||
this._data.statsCompare
|
||||
)
|
||||
: undefined;
|
||||
const hasGridCost = gridCost !== undefined || gridCostCompare !== undefined;
|
||||
const totalGridCost = gridCost ?? 0;
|
||||
const totalGridCostCompare = gridCostCompare ?? 0;
|
||||
|
||||
const _extractStatData = (
|
||||
statId: string,
|
||||
costStatId: string | null
|
||||
@@ -889,12 +901,6 @@ export class HuiEnergySourcesTableCard
|
||||
totalGrid += energy;
|
||||
totalGridCompare += energyCompare;
|
||||
|
||||
if (cost_stat) {
|
||||
hasGridCost = true;
|
||||
totalGridCost += cost;
|
||||
totalGridCostCompare += costCompare;
|
||||
}
|
||||
|
||||
if (showOnlyTotals) {
|
||||
return nothing;
|
||||
}
|
||||
@@ -951,12 +957,6 @@ export class HuiEnergySourcesTableCard
|
||||
totalGrid -= energy;
|
||||
totalGridCompare -= energyCompare;
|
||||
|
||||
if (cost_stat) {
|
||||
hasGridCost = true;
|
||||
totalGridCost -= cost;
|
||||
totalGridCostCompare -= costCompare;
|
||||
}
|
||||
|
||||
if (showOnlyTotals) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ import type {
|
||||
GridSourceTypeEnergyPreference,
|
||||
} from "../../../../data/energy";
|
||||
import {
|
||||
calculateGridNetCost,
|
||||
computeConsumptionData,
|
||||
energySourcesByType,
|
||||
getBatteryEnergyStatIds,
|
||||
@@ -131,6 +132,8 @@ export class HuiEnergyUsageGraphCard
|
||||
|
||||
@state() private _total?: number;
|
||||
|
||||
@state() private _totalCost?: number;
|
||||
|
||||
private _data?: EnergyData;
|
||||
|
||||
@state()
|
||||
@@ -186,24 +189,48 @@ export class HuiEnergyUsageGraphCard
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const totalCost =
|
||||
this._totalCost !== undefined && this._hassConfig.currency
|
||||
? formatNumber(this._totalCost, this._i18n.locale, {
|
||||
style: "currency",
|
||||
currency: this._hassConfig.currency,
|
||||
})
|
||||
: undefined;
|
||||
|
||||
return html`
|
||||
<ha-card>
|
||||
${
|
||||
this._config.title
|
||||
? html` <div class="card-header">
|
||||
<span>${this._config.title}</span>
|
||||
${
|
||||
this._total
|
||||
? html`<hui-energy-graph-chip
|
||||
.tooltip=${this._formatTotal(this._total)}
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.energy_usage_graph.total_usage",
|
||||
{ num: formatNumber(this._total, this._i18n.locale) }
|
||||
)}
|
||||
</hui-energy-graph-chip>`
|
||||
: nothing
|
||||
}
|
||||
<div class="chips">
|
||||
${
|
||||
this._total
|
||||
? html`<hui-energy-graph-chip
|
||||
.tooltip=${this._formatTotal(this._total)}
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.energy_usage_graph.total_usage",
|
||||
{
|
||||
num: formatNumber(this._total, this._i18n.locale),
|
||||
}
|
||||
)}
|
||||
</hui-energy-graph-chip>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
totalCost
|
||||
? html`<hui-energy-graph-chip
|
||||
.tooltip=${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.energy_usage_graph.total_cost",
|
||||
{ cost: totalCost }
|
||||
)}
|
||||
>
|
||||
${totalCost}
|
||||
</hui-energy-graph-chip>`
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
@@ -603,6 +630,11 @@ export class HuiEnergyUsageGraphCard
|
||||
this._chartData = datasets;
|
||||
this._legendData = this._getLegendData(datasets);
|
||||
this._total = this._processTotal(consumption);
|
||||
this._totalCost = calculateGridNetCost(
|
||||
energySourcesByType(energyData.prefs).grid ?? [],
|
||||
energyData.info,
|
||||
energyData.stats
|
||||
);
|
||||
}
|
||||
|
||||
private _getLegendData(
|
||||
@@ -907,6 +939,12 @@ export class HuiEnergyUsageGraphCard
|
||||
align-items: center;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
.chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: var(--ha-space-2);
|
||||
}
|
||||
.content {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { PictureElementsCardConfig } from "../types";
|
||||
import type { ElementPosition } from "./movable-element";
|
||||
|
||||
// Connects the picture-elements card editor with the card in its preview, so
|
||||
// that clicks and drags on the preview edit the config. It is attached to the
|
||||
@@ -15,9 +16,8 @@ const MAX_HAND_OVERS = 10;
|
||||
// Positions are in percent of the image.
|
||||
export interface PictureElementsEditorHandlers {
|
||||
selectElement: (index: number) => void;
|
||||
moveElement: (index: number, left: number, top: number) => void;
|
||||
// A click on the image outside of any element.
|
||||
clickImage: (x: number, y: number) => void;
|
||||
// Along the sides the element is placed from, like `{ right, top }`.
|
||||
moveElement: (index: number, position: ElementPosition) => void;
|
||||
}
|
||||
|
||||
export class PictureElementsEditorBridge extends EventTarget {
|
||||
|
||||
@@ -4,7 +4,8 @@ import type {
|
||||
LovelaceElementConfig,
|
||||
} from "../../elements/types";
|
||||
import type { PictureElementsEditorBridge } from "./editor-bridge";
|
||||
import { isMovableElement } from "./movable-element";
|
||||
import type { ElementAnchors, ElementPosition } from "./movable-element";
|
||||
import { elementAnchors, isMovableElement } from "./movable-element";
|
||||
|
||||
// How far (px) a press has to move before it counts as a drag.
|
||||
const DRAG_THRESHOLD = 4;
|
||||
@@ -21,16 +22,27 @@ export interface EditorPreviewTarget {
|
||||
configs?: LovelaceElementConfig[];
|
||||
}
|
||||
|
||||
// Where a movable element is, in percent of the image: its distances from the
|
||||
// sides it is placed from, and its rendered center. The card's default
|
||||
// transform centers it on its left/top point only, not on its right/bottom one.
|
||||
interface Placement {
|
||||
anchors: ElementAnchors;
|
||||
x: number;
|
||||
y: number;
|
||||
centerX: number;
|
||||
centerY: number;
|
||||
}
|
||||
|
||||
// A press on the preview, which ends as a click or a drag.
|
||||
interface Press {
|
||||
pointerId: number;
|
||||
clientX: number;
|
||||
clientY: number;
|
||||
index?: number;
|
||||
// Start position (percent) of a movable element.
|
||||
start?: { left: number; top: number };
|
||||
// Start position of a movable element.
|
||||
start?: Placement;
|
||||
// Current position (percent) once an element is dragged.
|
||||
moved?: { left: number; top: number };
|
||||
moved?: ElementPosition;
|
||||
// The pointer left the threshold, so the press is no click.
|
||||
dragged?: boolean;
|
||||
}
|
||||
@@ -226,15 +238,35 @@ export class PictureElementsEditorPreviewController implements ReactiveControlle
|
||||
);
|
||||
}
|
||||
|
||||
// The element's left/top in percent, as laid out.
|
||||
private _position(root: HTMLElement, index: number): Press["start"] {
|
||||
if (!root.offsetWidth || !root.offsetHeight) {
|
||||
// Where the element is, as laid out. Undefined while it isn't rendered (like
|
||||
// display: none), as it then has no layout to take it from.
|
||||
private _position(root: HTMLElement, index: number): Placement | undefined {
|
||||
const { elements, configs } = this._target();
|
||||
const element = elements?.[index];
|
||||
const anchors = configs?.[index] && elementAnchors(configs[index]);
|
||||
if (!element || !anchors || !element.getClientRects().length) {
|
||||
return undefined;
|
||||
}
|
||||
const style = getComputedStyle(this._target().elements![index]);
|
||||
// The computed sides are layout px, while the rects are visual px, which
|
||||
// differ under an ancestor's scale() or zoom. Both sizes are fractional,
|
||||
// unlike offsetWidth/offsetHeight.
|
||||
const rootStyle = getComputedStyle(root);
|
||||
const width = parseFloat(rootStyle.width);
|
||||
const height = parseFloat(rootStyle.height);
|
||||
const rootRect = root.getBoundingClientRect();
|
||||
if (!width || !height || !rootRect.width || !rootRect.height) {
|
||||
return undefined;
|
||||
}
|
||||
const style = getComputedStyle(element);
|
||||
const rect = element.getBoundingClientRect();
|
||||
return {
|
||||
left: (parseFloat(style.left) / root.offsetWidth) * 100,
|
||||
top: (parseFloat(style.top) / root.offsetHeight) * 100,
|
||||
anchors,
|
||||
x: (parseFloat(style[anchors.x]) / width) * 100,
|
||||
y: (parseFloat(style[anchors.y]) / height) * 100,
|
||||
centerX:
|
||||
((rect.left + rect.width / 2 - rootRect.left) / rootRect.width) * 100,
|
||||
centerY:
|
||||
((rect.top + rect.height / 2 - rootRect.top) / rootRect.height) * 100,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -260,13 +292,15 @@ export class PictureElementsEditorPreviewController implements ReactiveControlle
|
||||
}
|
||||
const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
|
||||
const wasMoved = !!press.moved;
|
||||
press.moved = {
|
||||
left: clampPercent(press.start.left + (dx / rect.width) * 100),
|
||||
top: clampPercent(press.start.top + (dy / rect.height) * 100),
|
||||
};
|
||||
press.moved = movedPosition(
|
||||
press.start,
|
||||
(dx / rect.width) * 100,
|
||||
(dy / rect.height) * 100
|
||||
);
|
||||
const element = this._target().elements?.[press.index];
|
||||
element?.style.setProperty("left", `${press.moved.left}%`);
|
||||
element?.style.setProperty("top", `${press.moved.top}%`);
|
||||
for (const [prop, value] of Object.entries(press.moved)) {
|
||||
element?.style.setProperty(prop, `${value}%`);
|
||||
}
|
||||
if (!wasMoved) {
|
||||
this._host.requestUpdate();
|
||||
}
|
||||
@@ -278,30 +312,54 @@ export class PictureElementsEditorPreviewController implements ReactiveControlle
|
||||
return;
|
||||
}
|
||||
const editor = this._editor;
|
||||
if (!editor) {
|
||||
// The visual editor went away, or the config changed the element's sides.
|
||||
if (!editor || (press.moved && !this._sameAnchors(press))) {
|
||||
this.pointerCancel(ev);
|
||||
return;
|
||||
}
|
||||
this._endPress();
|
||||
if (press.index !== undefined && press.moved) {
|
||||
editor.handlers.moveElement(
|
||||
press.index,
|
||||
press.moved.left,
|
||||
press.moved.top
|
||||
);
|
||||
editor.handlers.moveElement(press.index, press.moved);
|
||||
} else if (press.dragged) {
|
||||
// A drag that moved nothing is no click.
|
||||
} else if (press.index !== undefined) {
|
||||
editor.handlers.selectElement(press.index);
|
||||
} else {
|
||||
const rect = (ev.currentTarget as HTMLElement).getBoundingClientRect();
|
||||
editor.handlers.clickImage(
|
||||
clampPercent(((ev.clientX - rect.left) / rect.width) * 100),
|
||||
clampPercent(((ev.clientY - rect.top) / rect.height) * 100)
|
||||
);
|
||||
this._placeSelected(ev, editor);
|
||||
}
|
||||
};
|
||||
|
||||
// Whether the config places the element from the sides the press started
|
||||
// from.
|
||||
private _sameAnchors({ index, start }: Press): boolean {
|
||||
const config =
|
||||
index === undefined ? undefined : this._target().configs?.[index];
|
||||
const anchors = config && elementAnchors(config);
|
||||
return anchors?.x === start?.anchors.x && anchors?.y === start?.anchors.y;
|
||||
}
|
||||
|
||||
// Moves the center of the selected element to a click on the image.
|
||||
private _placeSelected(
|
||||
ev: PointerEvent,
|
||||
editor: PictureElementsEditorBridge
|
||||
): void {
|
||||
const root = ev.currentTarget as HTMLElement;
|
||||
const index = editor.selectedIndex;
|
||||
const start = index === undefined ? undefined : this._position(root, index);
|
||||
if (index === undefined || !start) {
|
||||
return;
|
||||
}
|
||||
const rect = root.getBoundingClientRect();
|
||||
editor.handlers.moveElement(
|
||||
index,
|
||||
movedPosition(
|
||||
start,
|
||||
((ev.clientX - rect.left) / rect.width) * 100 - start.centerX,
|
||||
((ev.clientY - rect.top) / rect.height) * 100 - start.centerY
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Also bound to lostpointercapture.
|
||||
public pointerCancel = (ev: PointerEvent): void => {
|
||||
const press = this._press;
|
||||
@@ -316,7 +374,7 @@ export class PictureElementsEditorPreviewController implements ReactiveControlle
|
||||
const { elements, configs } = this._target();
|
||||
const element = elements?.[press.index];
|
||||
const style = configs?.[press.index]?.style;
|
||||
for (const prop of ["left", "top"]) {
|
||||
for (const prop of Object.keys(press.moved)) {
|
||||
if (style?.[prop] != null && style[prop] !== "") {
|
||||
element?.style.setProperty(prop, style[prop]);
|
||||
} else {
|
||||
@@ -379,6 +437,22 @@ export class PictureElementsEditorPreviewController implements ReactiveControlle
|
||||
const clampPercent = (value: number): number =>
|
||||
Math.min(100, Math.max(0, value));
|
||||
|
||||
// The element's position once its center moved by dx/dy (percent), which is
|
||||
// kept on the image.
|
||||
const movedPosition = (
|
||||
start: Placement,
|
||||
dx: number,
|
||||
dy: number
|
||||
): ElementPosition => {
|
||||
const moveX = clampPercent(start.centerX + dx) - start.centerX;
|
||||
const moveY = clampPercent(start.centerY + dy) - start.centerY;
|
||||
// Right and bottom distances shrink as the element moves right or down.
|
||||
return {
|
||||
[start.anchors.x]: start.x + (start.anchors.x === "left" ? moveX : -moveX),
|
||||
[start.anchors.y]: start.y + (start.anchors.y === "top" ? moveY : -moveY),
|
||||
};
|
||||
};
|
||||
|
||||
const isEditable = (node: EventTarget | undefined): boolean =>
|
||||
node instanceof HTMLInputElement ||
|
||||
node instanceof HTMLTextAreaElement ||
|
||||
|
||||
@@ -3,37 +3,110 @@ import type { LovelaceElementConfig } from "../../elements/types";
|
||||
// A percentage, or a unitless zero.
|
||||
const POSITION = /^([+-]?(\d+(\.\d*)?|\.\d+)%|0)$/;
|
||||
|
||||
// Whether the editor can move the element by writing percent `left`/`top`.
|
||||
// Other placements (another `position`, `right`/`bottom`/`inset*`, px or
|
||||
// calc() values) are left alone rather than converted. Conditional elements
|
||||
// only wrap their children.
|
||||
export const isMovableElement = (config: LovelaceElementConfig): boolean => {
|
||||
const SIDES = ["left", "right", "top", "bottom"];
|
||||
|
||||
// The sides of the image an element is placed from.
|
||||
export interface ElementAnchors {
|
||||
x: "left" | "right";
|
||||
y: "top" | "bottom";
|
||||
}
|
||||
|
||||
// Distances in percent of the image, keyed by the side they are taken from.
|
||||
export type ElementPosition = Partial<
|
||||
Record<ElementAnchors["x"] | ElementAnchors["y"], number>
|
||||
>;
|
||||
|
||||
// The sides the editor can move the element along by writing percent values
|
||||
// to them: per axis the one the style sets, else left/top. Other placements
|
||||
// (another `position`, both sides of an axis, `inset*`, px or calc() values)
|
||||
// are left alone rather than converted. Conditional elements only wrap their
|
||||
// children.
|
||||
export const elementAnchors = (
|
||||
config: LovelaceElementConfig
|
||||
): ElementAnchors | undefined => {
|
||||
const style: unknown = config.style ?? {};
|
||||
if (
|
||||
config.type === "conditional" ||
|
||||
typeof style !== "object" ||
|
||||
Array.isArray(style)
|
||||
) {
|
||||
return false;
|
||||
return undefined;
|
||||
}
|
||||
const sides = new Set<string>();
|
||||
// Sides with an empty key in another case. The card applies the keys in
|
||||
// order, so such a key can remove the side the lowercase key sets.
|
||||
const cleared = new Set<string>();
|
||||
// YAML can hold numbers or null here, and CSS ignores the key case.
|
||||
for (const [key, raw] of Object.entries(style as Record<string, unknown>)) {
|
||||
const prop = key.toLowerCase();
|
||||
const value = raw == null ? "" : String(raw).trim().toLowerCase();
|
||||
if (prop === "left" || prop === "top") {
|
||||
if (key !== prop || (value && !POSITION.test(value))) {
|
||||
return false;
|
||||
if (SIDES.includes(prop)) {
|
||||
// An empty right or bottom is ignored in any key case.
|
||||
if (
|
||||
(key !== prop && (value || prop === "left" || prop === "top")) ||
|
||||
(value && !POSITION.test(value))
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
if (value) {
|
||||
sides.add(prop);
|
||||
} else if (key !== prop) {
|
||||
cleared.add(prop);
|
||||
}
|
||||
} else if (prop === "position") {
|
||||
if (value && value !== "absolute") {
|
||||
return false;
|
||||
return undefined;
|
||||
}
|
||||
} else if (prop.startsWith("inset")) {
|
||||
// The card applies the keys in order, so an empty inset removes the
|
||||
// sides the keys before it set.
|
||||
if (value || (prop === "inset" && sides.size)) {
|
||||
return undefined;
|
||||
}
|
||||
} else if (
|
||||
(prop === "right" || prop === "bottom" || prop.startsWith("inset")) &&
|
||||
value
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
if (
|
||||
(sides.has("left") && sides.has("right")) ||
|
||||
(sides.has("top") && sides.has("bottom")) ||
|
||||
[...cleared].some((side) => sides.has(side))
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
x: sides.has("right") ? "right" : "left",
|
||||
y: sides.has("bottom") ? "bottom" : "top",
|
||||
};
|
||||
};
|
||||
|
||||
export const isMovableElement = (config: LovelaceElementConfig): boolean =>
|
||||
elementAnchors(config) !== undefined;
|
||||
|
||||
// The element's style with the position written to the sides it is placed
|
||||
// from, rounded to 0.1 %. Undefined when it can't be moved there.
|
||||
export const movedStyle = (
|
||||
config: LovelaceElementConfig,
|
||||
position: ElementPosition
|
||||
): Record<string, string> | undefined => {
|
||||
const anchors = elementAnchors(config);
|
||||
const x = anchors && position[anchors.x];
|
||||
const y = anchors && position[anchors.y];
|
||||
if (!anchors || x === undefined || y === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const round = (value: number) => Math.round(value * 10) / 10;
|
||||
const style = { ...config.style };
|
||||
const keys = Object.keys(style);
|
||||
// The card applies the keys in order, so a side before an empty inset goes
|
||||
// behind it, or the inset removes it again. Others keep their place.
|
||||
for (const side of [anchors.x, anchors.y]) {
|
||||
const later = keys.slice(keys.indexOf(side) + 1);
|
||||
if (later.some((key) => key.toLowerCase() === "inset")) {
|
||||
delete style[side];
|
||||
}
|
||||
}
|
||||
return {
|
||||
...style,
|
||||
[anchors.x]: `${round(x)}%`,
|
||||
[anchors.y]: `${round(y)}%`,
|
||||
};
|
||||
};
|
||||
@@ -26,7 +26,11 @@ import {
|
||||
PICTURE_ELEMENTS_EDITOR_BRIDGE,
|
||||
PictureElementsEditorBridge,
|
||||
} from "../../cards/picture-elements/editor-bridge";
|
||||
import { isMovableElement } from "../../cards/picture-elements/movable-element";
|
||||
import type { ElementPosition } from "../../cards/picture-elements/movable-element";
|
||||
import {
|
||||
isMovableElement,
|
||||
movedStyle,
|
||||
} from "../../cards/picture-elements/movable-element";
|
||||
import type { PictureElementsCardConfig } from "../../cards/types";
|
||||
import type { LovelaceCardEditor } from "../../types";
|
||||
import "../hui-sub-element-editor";
|
||||
@@ -81,16 +85,7 @@ export class HuiPictureElementsCardEditor
|
||||
|
||||
private _bridge = new PictureElementsEditorBridge({
|
||||
selectElement: (index) => this._selectElement(index),
|
||||
moveElement: (index, left, top) =>
|
||||
this._setElementPosition(index, left, top),
|
||||
clickImage: (x, y) => {
|
||||
if (
|
||||
this._subElementEditorConfig?.type === "element" &&
|
||||
this._subElementEditorConfig.index !== undefined
|
||||
) {
|
||||
this._setElementPosition(this._subElementEditorConfig.index, x, y);
|
||||
}
|
||||
},
|
||||
moveElement: (index, position) => this._setElementPosition(index, position),
|
||||
});
|
||||
|
||||
public connectedCallback(): void {
|
||||
@@ -147,21 +142,14 @@ export class HuiPictureElementsCardEditor
|
||||
this._subElementEditorConfig = { index, type: "element", elementConfig };
|
||||
}
|
||||
|
||||
// left/top are in percent of the image.
|
||||
private _setElementPosition(index: number, left: number, top: number): void {
|
||||
// The position is in percent of the image.
|
||||
private _setElementPosition(index: number, position: ElementPosition): void {
|
||||
const elementConfig = this._config?.elements[index];
|
||||
if (!elementConfig || !isMovableElement(elementConfig)) {
|
||||
const style = elementConfig && movedStyle(elementConfig, position);
|
||||
if (!elementConfig || !style) {
|
||||
return;
|
||||
}
|
||||
const round = (value: number) => Math.round(value * 10) / 10;
|
||||
const newElement: LovelaceElementConfig = {
|
||||
...elementConfig,
|
||||
style: {
|
||||
...elementConfig.style,
|
||||
left: `${round(left)}%`,
|
||||
top: `${round(top)}%`,
|
||||
},
|
||||
};
|
||||
const newElement: LovelaceElementConfig = { ...elementConfig, style };
|
||||
const elements = this._config!.elements.concat();
|
||||
elements[index] = newElement;
|
||||
this._config = { ...this._config!, elements };
|
||||
|
||||
@@ -97,6 +97,7 @@ import {
|
||||
markdownWithRepositoryContext,
|
||||
repositoryUrl,
|
||||
} from "../tools/markdown";
|
||||
import { MARKETPLACE_NAME } from "../../../common/translations/name-placeholders";
|
||||
|
||||
// Repository pages live at /<id> below /repository, my links at /repository itself.
|
||||
const repositoryIdFromRoute = (route: Route): string => route.path.substring(1);
|
||||
@@ -495,7 +496,7 @@ export class HaMarketplaceRepositoryDashboard extends LitElement {
|
||||
<hass-subpage
|
||||
.narrow=${this.narrow}
|
||||
back-path="/marketplace"
|
||||
.header=${this._i18n.localize("ui.panel.marketplace.title")}
|
||||
.header=${MARKETPLACE_NAME}
|
||||
>
|
||||
<ha-dropdown
|
||||
slot="toolbar-icon"
|
||||
|
||||
+67
-27
@@ -17,7 +17,6 @@
|
||||
"climate": "Climate",
|
||||
"home": "Overview",
|
||||
"maintenance": "Maintenance",
|
||||
"marketplace": "Marketplace",
|
||||
"notfound": "Page not found"
|
||||
},
|
||||
"state": {
|
||||
@@ -1378,6 +1377,21 @@
|
||||
"select_row": "Select {name}",
|
||||
"select_row_generic": "Select row"
|
||||
},
|
||||
"camera-player": {
|
||||
"play": "Play",
|
||||
"mute": "Mute",
|
||||
"unmute": "Unmute",
|
||||
"picture_in_picture": "Picture in picture",
|
||||
"exit_picture_in_picture": "Exit picture in picture",
|
||||
"fullscreen": "Full screen",
|
||||
"exit_fullscreen": "Exit full screen",
|
||||
"reset_zoom": "Reset zoom",
|
||||
"zoom_hint": "Use {modifier} + scroll to zoom",
|
||||
"connecting": "Connecting",
|
||||
"stream_info": "Streaming with {type}. Show connection details",
|
||||
"stream_info_connecting": "Connecting to the camera. Show connection details",
|
||||
"stream_info_upgrading": "Streaming with {type}, connecting with {upgrading} in the background. Show connection details"
|
||||
},
|
||||
"web-rtc-player": {
|
||||
"not_supported": "WebRTC is not supported in this browser.",
|
||||
"start_failed": "Failed to start the WebRTC stream: {message}",
|
||||
@@ -1735,6 +1749,9 @@
|
||||
"show": "Show {label}",
|
||||
"hide": "Hide {label}"
|
||||
},
|
||||
"list-item-option": {
|
||||
"partly_selected": "Partly selected"
|
||||
},
|
||||
"form-optional-actions": {
|
||||
"add": "Add interaction"
|
||||
},
|
||||
@@ -2811,6 +2828,20 @@
|
||||
"skip": "Skip and finish"
|
||||
}
|
||||
},
|
||||
"camera_stream_info": {
|
||||
"title": "Stream connection",
|
||||
"intro": "Home Assistant starts with the connection that works most reliably and switches to a faster one as soon as it is ready.",
|
||||
"still_images_only": "This camera has no video stream, so it shows a series of still images.",
|
||||
"fallback_in_use": "The video streams of this camera could not be started, so still images are shown instead.",
|
||||
"in_use": "In use",
|
||||
"connecting": "Connecting",
|
||||
"not_supported_count": "Not supported by this camera ({count})",
|
||||
"description": {
|
||||
"web_rtc": "Real-time video with the lowest delay, usually below a second. The video takes the most direct way from the camera to your device, which can need extra network setup when you are away from home. Needed to talk to the camera.",
|
||||
"hls": "The video is sent in short pieces through Home Assistant. It works on almost every network and device, but is a few seconds behind. Used while WebRTC connects, or when WebRTC is not available.",
|
||||
"mjpeg": "A series of still images, used when the camera has no video stream or the other connections failed. It has no sound."
|
||||
}
|
||||
},
|
||||
"shortcuts": {
|
||||
"title": "Shortcuts",
|
||||
"enable_shortcuts_hint": "For keyboard shortcuts to work, make sure you have them enabled in your {user_profile}.",
|
||||
@@ -3085,7 +3116,6 @@
|
||||
"secondary": "Run extra applications next to Home Assistant"
|
||||
},
|
||||
"marketplace": {
|
||||
"main": "Marketplace",
|
||||
"secondary": "Install community integrations, dashboard content, themes, and templates"
|
||||
},
|
||||
"dashboards": {
|
||||
@@ -8153,7 +8183,7 @@
|
||||
"restart_confirm": "Restart Home Assistant to finish removing this integration",
|
||||
"marketplace_uninstall": {
|
||||
"title": "Also uninstall {name}?",
|
||||
"text": "{name} came from the Marketplace. Its files stay on your system, and the Marketplace keeps checking for updates until you uninstall it.",
|
||||
"text": "{name} came from the {marketplace}. Its files stay on your system, and the {marketplace} keeps checking for updates until you uninstall it.",
|
||||
"confirm": "Uninstall",
|
||||
"dismiss": "Keep",
|
||||
"failed": "Uninstall failed. Check the Home Assistant logs for details."
|
||||
@@ -10427,6 +10457,7 @@
|
||||
"energy_usage_graph": {
|
||||
"total_consumed": "Total {num} kWh",
|
||||
"total_usage": "{num} kWh",
|
||||
"total_cost": "Net grid cost {cost}",
|
||||
"combined_from_grid": "Grid",
|
||||
"consumed_solar": "Solar",
|
||||
"consumed_battery": "Battery",
|
||||
@@ -12785,7 +12816,17 @@
|
||||
"migrate_success": "Theme settings migrated.",
|
||||
"migrate_failed": "Failed to migrate theme settings.",
|
||||
"theme_mode": "Theme mode",
|
||||
"mode_set_by_theme": {
|
||||
"light": "\"{theme}\" only has a light mode.",
|
||||
"dark": "\"{theme}\" only has a dark mode.",
|
||||
"none": "\"{theme}\" has fixed colors and doesn't switch between light and dark mode."
|
||||
},
|
||||
"colors": "Custom colors",
|
||||
"colors_set_by_theme": {
|
||||
"both": "Both colors are set by \"{theme}\".",
|
||||
"primary": "The primary color is set by \"{theme}\".",
|
||||
"accent": "The accent color is set by \"{theme}\"."
|
||||
},
|
||||
"dark_mode": {
|
||||
"auto": "Auto",
|
||||
"light": "Light",
|
||||
@@ -13350,12 +13391,11 @@
|
||||
"error_no_data": "You need to select some data sources first."
|
||||
},
|
||||
"marketplace": {
|
||||
"title": "Marketplace",
|
||||
"not_loaded": "The Marketplace is not available. It does not load in recovery mode or when it failed to start, check the Home Assistant logs for more information.",
|
||||
"load_failed": "The Marketplace could not load its data: {error}",
|
||||
"not_loaded": "The {marketplace} is not available. It does not load in recovery mode or when it failed to start, check the Home Assistant logs for more information.",
|
||||
"load_failed": "The {marketplace} could not load its data: {error}",
|
||||
"warning": {
|
||||
"title": "Before you install from the Marketplace",
|
||||
"intro": "Marketplace items are made by community contributors and are not reviewed by the Home\u00a0Assistant project. Treat them like plugins for any other software.",
|
||||
"title": "Before you install from the {marketplace}",
|
||||
"intro": "{marketplace} items are made by community contributors and are not reviewed by the Home\u00a0Assistant project. Treat them like plugins for any other software.",
|
||||
"risks_title": "Anything you install can",
|
||||
"risks": {
|
||||
"access": "Access and control everything in Home\u00a0Assistant",
|
||||
@@ -13391,23 +13431,23 @@
|
||||
},
|
||||
"dashboard": {
|
||||
"search": "Search {number} {number, plural,\n one {repository}\n other {repositories}\n}",
|
||||
"empty_header": "Nothing in the Marketplace yet",
|
||||
"empty_text": "The Marketplace gets its list from the community catalog, which could not be reached yet. The list shows up here once it loads.",
|
||||
"empty_header": "Nothing in the {marketplace} yet",
|
||||
"empty_text": "The {marketplace} gets its list from the community catalog, which could not be reached yet. The list shows up here once it loads.",
|
||||
"no_data": "No repositories matching search and filters",
|
||||
"repository_not_found": "Repository not found"
|
||||
},
|
||||
"entry": {
|
||||
"disabled": "The Marketplace is disabled. Enable it on the integration page to use it.",
|
||||
"disabled": "The {marketplace} is disabled. Enable it on the integration page to use it.",
|
||||
"open_integration": "Open integration page",
|
||||
"failed": "The Marketplace could not be loaded, check the Home Assistant logs for more information.",
|
||||
"failed_reason": "The Marketplace could not be loaded: {reason}",
|
||||
"retrying": "The Marketplace could not start yet, retrying in a moment"
|
||||
"failed": "The {marketplace} could not be loaded, check the Home Assistant logs for more information.",
|
||||
"failed_reason": "The {marketplace} could not be loaded: {reason}",
|
||||
"retrying": "The {marketplace} could not start yet, retrying in a moment"
|
||||
},
|
||||
"github": {
|
||||
"connect": "Connect GitHub",
|
||||
"add_repository_needs_github": "Connect GitHub to add the custom repository {repository}, then open the link again.",
|
||||
"rate_limited_title": "GitHub limit reached",
|
||||
"rate_limited": "GitHub limits how often the Marketplace can reach it without a GitHub connection. Try again later, or connect GitHub for a higher limit."
|
||||
"rate_limited": "GitHub limits how often the {marketplace} can reach it without a GitHub connection. Try again later, or connect GitHub for a higher limit."
|
||||
},
|
||||
"column": {
|
||||
"name": "Repository name",
|
||||
@@ -13428,7 +13468,7 @@
|
||||
"error": "An unknown error occurred",
|
||||
"repository_not_found": "Repository {repository} not found",
|
||||
"add_repository_title": "Add custom repository",
|
||||
"add_repository_description": "Add the custom repository {repository} to the Marketplace?"
|
||||
"add_repository_description": "Add the custom repository {repository} to the {marketplace}?"
|
||||
},
|
||||
"filters": {
|
||||
"status": "Status",
|
||||
@@ -13437,7 +13477,7 @@
|
||||
},
|
||||
"dialog_custom_repositories": {
|
||||
"title": "Add from a GitHub link",
|
||||
"intro": "Add something that is not in the Marketplace yet, straight from its page on GitHub. Like everything in the Marketplace, it is made by the community and not tested or reviewed by the Home Assistant project.",
|
||||
"intro": "Add something that is not in the {marketplace} yet, straight from its page on GitHub. Like everything in the {marketplace}, it is made by the community and not tested or reviewed by the Home Assistant project.",
|
||||
"link": "GitHub link",
|
||||
"link_helper": "The address of its page on GitHub, like https://github.com/owner/name",
|
||||
"type": "Type",
|
||||
@@ -13452,10 +13492,10 @@
|
||||
"github": "GitHub repository",
|
||||
"no_repositories": "You have not added any repositories from a link yet.",
|
||||
"remove_title": "Remove {name} from the list?",
|
||||
"remove_text": "It no longer shows in the Marketplace. You can add it again later.",
|
||||
"remove_text": "It no longer shows in the {marketplace}. You can add it again later.",
|
||||
"remove_installed": "Uninstall it first",
|
||||
"remove_selected_title": "Remove selected repositories?",
|
||||
"remove_selected_text": "{count, plural,\n one {The selected repository no longer shows in the Marketplace. You can add it again later.}\n other {The {count} selected repositories no longer show in the Marketplace. You can add them again later.}\n}",
|
||||
"remove_selected_text": "{count, plural,\n one {The selected repository no longer shows in the {marketplace}. You can add it again later.}\n other {The {count} selected repositories no longer show in the {marketplace}. You can add them again later.}\n}",
|
||||
"remove_failed_title": "Remove failed",
|
||||
"remove_failed": "Some repositories could not be removed."
|
||||
},
|
||||
@@ -13589,9 +13629,9 @@
|
||||
},
|
||||
"uninstall": {
|
||||
"title": "Uninstall {name}?",
|
||||
"message": "This removes the files the Marketplace installed for it.",
|
||||
"message": "This removes the files the {marketplace} installed for it.",
|
||||
"selected_title": "Uninstall selected repositories?",
|
||||
"selected": "{count, plural,\n one {The selected repository will be uninstalled. This removes the files the Marketplace installed for it.}\n other {The {count} selected repositories will be uninstalled. This removes the files the Marketplace installed for them.}\n}",
|
||||
"selected": "{count, plural,\n one {The selected repository will be uninstalled. This removes the files the {marketplace} installed for it.}\n other {The {count} selected repositories will be uninstalled. This removes the files the {marketplace} installed for them.}\n}",
|
||||
"selected_in_use": "{count, plural, one {The selected repository} other {The {count} selected repositories}} will be uninstalled. {in_use, plural, one {The setup of one of them} other {The setups of # of them}} will be deleted with their devices and entities. This cannot be undone.",
|
||||
"check_failed_title": "Unable to check repositories",
|
||||
"check_failed": "The setups of some selected repositories could not be verified.",
|
||||
@@ -13599,17 +13639,17 @@
|
||||
"failed": "Some repositories could not be uninstalled."
|
||||
},
|
||||
"disabled": {
|
||||
"title": "The Marketplace is disabled",
|
||||
"title": "The {marketplace} is disabled",
|
||||
"reason": {
|
||||
"invalid_token": "The GitHub connection no longer works. Reconfigure the Marketplace integration to connect GitHub again.",
|
||||
"rate_limit": "The GitHub API rate limit has been reached. The Marketplace works again once the limit resets.",
|
||||
"removed": "The Marketplace integration has been removed.",
|
||||
"unknown": "The Marketplace is unavailable, check the Home Assistant logs for more information."
|
||||
"invalid_token": "The GitHub connection no longer works. Reconfigure the {marketplace} integration to connect GitHub again.",
|
||||
"rate_limit": "The GitHub API rate limit has been reached. The {marketplace} works again once the limit resets.",
|
||||
"removed": "The {marketplace} integration has been removed.",
|
||||
"unknown": "The {marketplace} is unavailable, check the Home Assistant logs for more information."
|
||||
}
|
||||
},
|
||||
"in_use": {
|
||||
"title": "{name} is in use",
|
||||
"message": "{name} is still set up, and that setup runs on the files the Marketplace installed. Without them it would fail to load and leave its devices and entities behind. Delete it first, or let the Marketplace delete it and uninstall {name} for you.",
|
||||
"message": "{name} is still set up, and that setup runs on the files the {marketplace} installed. Without them it would fail to load and leave its devices and entities behind. Delete it first, or let the {marketplace} delete it and uninstall {name} for you.",
|
||||
"ignored": "Ignored",
|
||||
"view_integration": "View integration",
|
||||
"delete_and_uninstall": "Delete and uninstall",
|
||||
|
||||
@@ -40,4 +40,24 @@ describe("dropInvalidConditions", () => {
|
||||
]);
|
||||
expect(nested.conditions).toEqual([screen, undefined, 5]);
|
||||
});
|
||||
|
||||
it("wraps a single condition mapping in an array", () => {
|
||||
const condition = state as unknown as VisibilityCondition;
|
||||
expect(dropInvalidConditions(condition)).toEqual([state]);
|
||||
});
|
||||
|
||||
it("drops invalid children of a single condition mapping", () => {
|
||||
const condition = {
|
||||
condition: "or",
|
||||
conditions: [screen, null],
|
||||
} as unknown as VisibilityCondition;
|
||||
expect(dropInvalidConditions(condition)).toEqual([
|
||||
{ condition: "or", conditions: [screen] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops a single value that is not a condition object", () => {
|
||||
const condition = "screen" as unknown as VisibilityCondition;
|
||||
expect(dropInvalidConditions(condition)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
applyThemesOnElement,
|
||||
invalidateThemeCache,
|
||||
} from "../../../src/common/dom/apply_themes_on_element";
|
||||
import { normalizeLuminance } from "../../../src/common/color/palette";
|
||||
import type { Theme, Themes } from "../../../src/data/ws-themes";
|
||||
|
||||
const PICKED_PRIMARY = "#e91e63";
|
||||
const PICKED_ACCENT = "#4caf50";
|
||||
|
||||
// Themes from YAML are partial, the `Theme` type lists keys most themes set.
|
||||
const asTheme = (variables: object) => variables as Theme;
|
||||
|
||||
const makeThemes = (themes: Record<string, Theme>): Themes => ({
|
||||
default_theme: "default",
|
||||
default_dark_theme: null,
|
||||
themes,
|
||||
darkMode: false,
|
||||
theme: "default",
|
||||
});
|
||||
|
||||
const apply = (
|
||||
themes: Themes,
|
||||
theme: string,
|
||||
dark = false
|
||||
): CSSStyleDeclaration => {
|
||||
const element = document.createElement("div");
|
||||
applyThemesOnElement(
|
||||
element,
|
||||
themes,
|
||||
theme,
|
||||
{ primaryColor: PICKED_PRIMARY, accentColor: PICKED_ACCENT, dark },
|
||||
true
|
||||
);
|
||||
return element.style;
|
||||
};
|
||||
|
||||
describe("applyThemesOnElement user colors", () => {
|
||||
beforeEach(() => {
|
||||
invalidateThemeCache();
|
||||
});
|
||||
|
||||
it("applies picked colors and the primary palette to a theme that doesn't set them", () => {
|
||||
const style = apply(
|
||||
makeThemes({ oled: asTheme({ "primary-background-color": "#000000" }) }),
|
||||
"oled"
|
||||
);
|
||||
|
||||
expect(style.getPropertyValue("--primary-color")).toBe(PICKED_PRIMARY);
|
||||
expect(style.getPropertyValue("--accent-color")).toBe(PICKED_ACCENT);
|
||||
expect(style.getPropertyValue("--ha-color-primary-50")).not.toBe("");
|
||||
expect(style.getPropertyValue("--primary-background-color")).toBe(
|
||||
"#000000"
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a primary color set by the theme and still applies the picked accent", () => {
|
||||
const style = apply(
|
||||
makeThemes({ pink: asTheme({ "primary-color": "#ff00ff" }) }),
|
||||
"pink"
|
||||
);
|
||||
|
||||
expect(style.getPropertyValue("--primary-color")).toBe("#ff00ff");
|
||||
expect(style.getPropertyValue("--accent-color")).toBe(PICKED_ACCENT);
|
||||
});
|
||||
|
||||
it("treats a theme that sets primary palette keys as setting the primary color", () => {
|
||||
const style = apply(
|
||||
makeThemes({ palette: asTheme({ "ha-color-primary-40": "#123456" }) }),
|
||||
"palette"
|
||||
);
|
||||
|
||||
expect(style.getPropertyValue("--primary-color")).not.toBe(PICKED_PRIMARY);
|
||||
expect(style.getPropertyValue("--ha-color-primary-40")).toBe("#123456");
|
||||
});
|
||||
it("reads theme colors from the active mode", () => {
|
||||
const themes = makeThemes({
|
||||
modes: asTheme({
|
||||
modes: { light: {}, dark: { "primary-color": "#ff00ff" } },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(apply(themes, "modes").getPropertyValue("--primary-color")).toBe(
|
||||
PICKED_PRIMARY
|
||||
);
|
||||
expect(
|
||||
apply(themes, "modes", true).getPropertyValue("--primary-color")
|
||||
).toBe("#ff00ff");
|
||||
});
|
||||
|
||||
it("only tints the dark mode header for the default theme", () => {
|
||||
const themes = makeThemes({
|
||||
oled: asTheme({ modes: { light: {}, dark: {} } }),
|
||||
});
|
||||
|
||||
expect(
|
||||
apply(themes, "default", true).getPropertyValue(
|
||||
"--app-header-background-color"
|
||||
)
|
||||
).toMatch(/^#/);
|
||||
expect(
|
||||
apply(themes, "oled", true).getPropertyValue(
|
||||
"--app-header-background-color"
|
||||
)
|
||||
).toBe("var(--sidebar-background-color)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyThemesOnElement theme palette", () => {
|
||||
beforeEach(() => {
|
||||
invalidateThemeCache();
|
||||
});
|
||||
|
||||
const applyTheme = (theme: Theme): CSSStyleDeclaration => {
|
||||
const element = document.createElement("div");
|
||||
applyThemesOnElement(element, makeThemes({ custom: theme }), "custom");
|
||||
return element.style;
|
||||
};
|
||||
|
||||
it("generates the palette from the theme primary color", () => {
|
||||
const style = applyTheme(asTheme({ "primary-color": "#ff00ff" }));
|
||||
|
||||
expect(style.getPropertyValue("--ha-color-primary-50")).toBe(
|
||||
normalizeLuminance("#ff00ff")
|
||||
);
|
||||
expect(style.getPropertyValue("--ha-color-primary-05")).not.toBe("");
|
||||
expect(style.getPropertyValue("--ha-color-primary-90")).not.toBe("");
|
||||
expect(style.getPropertyValue("--dark-primary-color")).not.toBe("");
|
||||
});
|
||||
|
||||
it("parses named colors", () => {
|
||||
const style = applyTheme(asTheme({ "primary-color": "pink" }));
|
||||
|
||||
expect(style.getPropertyValue("--primary-color")).toBe("pink");
|
||||
expect(style.getPropertyValue("--ha-color-primary-50")).toBe(
|
||||
normalizeLuminance("#ffc0cb")
|
||||
);
|
||||
});
|
||||
|
||||
it("doesn't recolor state icons or text on primary", () => {
|
||||
const style = applyTheme(asTheme({ "primary-color": "#ff00ff" }));
|
||||
|
||||
expect(style.getPropertyValue("--state-icon-color")).toBe("");
|
||||
expect(style.getPropertyValue("--text-primary-color")).toBe("");
|
||||
});
|
||||
|
||||
it("keeps palette keys and shades the theme sets itself", () => {
|
||||
const style = applyTheme(
|
||||
asTheme({
|
||||
"primary-color": "#ff00ff",
|
||||
"dark-primary-color": "#330033",
|
||||
})
|
||||
);
|
||||
|
||||
expect(style.getPropertyValue("--dark-primary-color")).toBe("#330033");
|
||||
expect(style.getPropertyValue("--ha-color-primary-50")).not.toBe("");
|
||||
});
|
||||
|
||||
it("keeps the palette readable for a near black theme color", () => {
|
||||
const style = applyTheme(asTheme({ "primary-color": "#111111" }));
|
||||
|
||||
expect(style.getPropertyValue("--primary-color")).toBe("#111111");
|
||||
expect(style.getPropertyValue("--ha-color-primary-50")).toBe(
|
||||
normalizeLuminance("#111111")
|
||||
);
|
||||
expect(style.getPropertyValue("--ha-color-primary-50")).not.toBe("#111111");
|
||||
});
|
||||
|
||||
it("doesn't generate anything when the theme sets part of the palette", () => {
|
||||
const style = applyTheme(
|
||||
asTheme({ "primary-color": "#ff00ff", "ha-color-primary-40": "#123456" })
|
||||
);
|
||||
|
||||
expect(style.getPropertyValue("--ha-color-primary-40")).toBe("#123456");
|
||||
expect(style.getPropertyValue("--ha-color-primary-50")).toBe("");
|
||||
});
|
||||
|
||||
it("skips colors it can't parse", () => {
|
||||
const style = applyTheme(asTheme({ "primary-color": "var(--my-color)" }));
|
||||
|
||||
expect(style.getPropertyValue("--primary-color")).toBe("var(--my-color)");
|
||||
expect(style.getPropertyValue("--ha-color-primary-50")).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { whenDocumentVisible } from "../../../src/common/dom/when-document-visible";
|
||||
|
||||
describe("whenDocumentVisible", () => {
|
||||
let hidden: boolean;
|
||||
let cancel: (() => void) | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
hidden = true;
|
||||
vi.spyOn(document, "hidden", "get").mockImplementation(() => hidden);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cancel?.();
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("runs the callback after thaw without lifecycle events", async () => {
|
||||
const recover = vi.fn();
|
||||
cancel = whenDocumentVisible(recover);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(360000);
|
||||
expect(recover).not.toHaveBeenCalled();
|
||||
|
||||
// The WebView changes visibility but emits no event when the screen wakes.
|
||||
hidden = false;
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(recover).toHaveBeenCalledTimes(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it.each(["visibilitychange", "resume", "focus"])(
|
||||
"recovers immediately on %s when visible",
|
||||
(type) => {
|
||||
const recover = vi.fn();
|
||||
cancel = whenDocumentVisible(recover);
|
||||
hidden = false;
|
||||
(type === "focus" ? window : document).dispatchEvent(new Event(type));
|
||||
expect(recover).toHaveBeenCalledTimes(1);
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(recover).toHaveBeenCalledTimes(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
}
|
||||
);
|
||||
|
||||
it("keeps reconnects suspended when a lifecycle event arrives while hidden", () => {
|
||||
const recover = vi.fn();
|
||||
cancel = whenDocumentVisible(recover);
|
||||
document.dispatchEvent(new Event("resume"));
|
||||
window.dispatchEvent(new Event("focus"));
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(recover).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("removes timers and listeners when cancelled", () => {
|
||||
const recover = vi.fn();
|
||||
cancel = whenDocumentVisible(recover);
|
||||
cancel();
|
||||
hidden = false;
|
||||
document.dispatchEvent(new Event("visibilitychange"));
|
||||
document.dispatchEvent(new Event("resume"));
|
||||
window.dispatchEvent(new Event("focus"));
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(recover).not.toHaveBeenCalled();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -253,6 +253,90 @@ describe("computeAttributeValueDisplay", () => {
|
||||
expect(result).toBe("Media Player Attribute Name");
|
||||
});
|
||||
|
||||
it("should return the translation of a group member", () => {
|
||||
const localize = (key: string) =>
|
||||
({
|
||||
"component.member_platform.entity.light.member_key.state_attributes.effect.state.candle":
|
||||
"Candle",
|
||||
"component.switch_platform.entity.switch.switch_key.state_attributes.effect.state.candle":
|
||||
"Switch candle",
|
||||
})[key] || "";
|
||||
const entities = {
|
||||
"light.group": { platform: "group" },
|
||||
"light.plain": { platform: "plain_platform" },
|
||||
"switch.member": {
|
||||
platform: "switch_platform",
|
||||
translation_key: "switch_key",
|
||||
},
|
||||
"light.member": {
|
||||
platform: "member_platform",
|
||||
translation_key: "member_key",
|
||||
},
|
||||
} as unknown as HomeAssistant["entities"];
|
||||
const stateObj = {
|
||||
entity_id: "light.group",
|
||||
attributes: {
|
||||
entity_id: ["light.plain", "switch.member", "light.member"],
|
||||
},
|
||||
} as unknown as HassEntityBase;
|
||||
|
||||
expect(
|
||||
computeAttributeValueDisplay(
|
||||
localize,
|
||||
stateObj,
|
||||
localeMock,
|
||||
configMock,
|
||||
entities,
|
||||
"effect",
|
||||
"candle"
|
||||
)
|
||||
).toBe("Candle");
|
||||
expect(
|
||||
computeAttributeValueDisplay(
|
||||
localize,
|
||||
stateObj,
|
||||
localeMock,
|
||||
configMock,
|
||||
entities,
|
||||
"effect",
|
||||
"fire"
|
||||
)
|
||||
).toBe("fire");
|
||||
});
|
||||
|
||||
it("should return the translation of a member in group_entities", () => {
|
||||
const localize = (key: string) =>
|
||||
({
|
||||
"component.member_platform.entity.light.member_key.state_attributes.effect.state.candle":
|
||||
"Candle",
|
||||
})[key] || "";
|
||||
const entities = {
|
||||
"light.integration_group": { platform: "integration_platform" },
|
||||
"light.member": {
|
||||
platform: "member_platform",
|
||||
translation_key: "member_key",
|
||||
},
|
||||
} as unknown as HomeAssistant["entities"];
|
||||
const stateObj = {
|
||||
entity_id: "light.integration_group",
|
||||
attributes: {
|
||||
group_entities: ["light.member"],
|
||||
},
|
||||
} as unknown as HassEntityBase;
|
||||
|
||||
expect(
|
||||
computeAttributeValueDisplay(
|
||||
localize,
|
||||
stateObj,
|
||||
localeMock,
|
||||
configMock,
|
||||
entities,
|
||||
"effect",
|
||||
"candle"
|
||||
)
|
||||
).toBe("Candle");
|
||||
});
|
||||
|
||||
it("should return attribute value", () => {
|
||||
const stateObj = {
|
||||
entity_id: "media_player.test",
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { computeLocalize } from "../../../src/common/translations/localize";
|
||||
|
||||
const localizeWith = (strings: Record<string, string>) =>
|
||||
computeLocalize<string>(document.createElement("div"), "en", {
|
||||
en: strings,
|
||||
});
|
||||
|
||||
describe("computeLocalize", () => {
|
||||
it("fills product names without the caller passing them", async () => {
|
||||
const localize = await localizeWith({
|
||||
key: "Nothing in the {marketplace} yet",
|
||||
});
|
||||
expect(localize("key")).toBe("Nothing in the Marketplace yet");
|
||||
});
|
||||
|
||||
it("keeps the names next to the caller's values", async () => {
|
||||
const localize = await localizeWith({
|
||||
key: "{name} came from the {marketplace}",
|
||||
});
|
||||
expect(localize("key", { name: "Card" })).toBe(
|
||||
"Card came from the Marketplace"
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -50,4 +50,22 @@ describe("parseAspectRatio", () => {
|
||||
const r = parseAspectRatio("mary:lamb");
|
||||
assert.equal(r, null);
|
||||
});
|
||||
|
||||
it("Skips non-string input", () => {
|
||||
// An unquoted `aspect_ratio: 16:9` in YAML is loaded as the number 969
|
||||
assert.equal(parseAspectRatio(969 as unknown as string), null);
|
||||
assert.equal(parseAspectRatio(1.78 as unknown as string), null);
|
||||
});
|
||||
|
||||
it("Parses values with surrounding whitespace", () => {
|
||||
assert.deepEqual(parseAspectRatio(" 16 : 9 "), ratio16by9);
|
||||
assert.deepEqual(parseAspectRatio(" 23 % "), { w: 100, h: 23 });
|
||||
});
|
||||
|
||||
it.each(["16/9", "16X9", "16x9x4", "16:9:4", "16x", "x9", "16abc", "23%x"])(
|
||||
"Skips unhandled input %s",
|
||||
(input) => {
|
||||
assert.equal(parseAspectRatio(input), null);
|
||||
}
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { throttle } from "../../../src/common/util/throttle";
|
||||
|
||||
describe("throttle", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({
|
||||
toFake: ["setTimeout", "clearTimeout", "Date"],
|
||||
shouldAdvanceTime: false,
|
||||
});
|
||||
vi.stubGlobal("window", {
|
||||
...window,
|
||||
setTimeout: globalThis.setTimeout,
|
||||
clearTimeout: globalThis.clearTimeout,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("calls on the leading edge and once more on the trailing edge", () => {
|
||||
const fn = vi.fn();
|
||||
const throttled = throttle(fn, 500);
|
||||
|
||||
throttled("a");
|
||||
expect(fn).toHaveBeenCalledTimes(1);
|
||||
expect(fn).toHaveBeenLastCalledWith("a");
|
||||
|
||||
throttled("b");
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(fn).toHaveBeenCalledTimes(2);
|
||||
expect(fn).toHaveBeenLastCalledWith("b");
|
||||
});
|
||||
|
||||
it("uses the latest arguments for the trailing call", () => {
|
||||
const fn = vi.fn();
|
||||
const throttled = throttle(fn, 500);
|
||||
|
||||
throttled("a");
|
||||
throttled("b");
|
||||
vi.advanceTimersByTime(100);
|
||||
throttled("c");
|
||||
vi.advanceTimersByTime(100);
|
||||
throttled("d");
|
||||
|
||||
vi.advanceTimersByTime(300);
|
||||
expect(fn).toHaveBeenCalledTimes(2);
|
||||
expect(fn).toHaveBeenNthCalledWith(1, "a");
|
||||
expect(fn).toHaveBeenNthCalledWith(2, "d");
|
||||
});
|
||||
|
||||
it("uses the latest arguments when leading is disabled", () => {
|
||||
const fn = vi.fn();
|
||||
const throttled = throttle(fn, 500, false);
|
||||
|
||||
throttled("a");
|
||||
throttled("b");
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(fn).toHaveBeenCalledTimes(1);
|
||||
expect(fn).toHaveBeenLastCalledWith("b");
|
||||
});
|
||||
|
||||
it("does not call on the trailing edge when trailing is disabled", () => {
|
||||
const fn = vi.fn();
|
||||
const throttled = throttle(fn, 500, true, false);
|
||||
|
||||
throttled("a");
|
||||
throttled("b");
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(fn).toHaveBeenCalledTimes(1);
|
||||
expect(fn).toHaveBeenLastCalledWith("a");
|
||||
});
|
||||
|
||||
it("drops the pending trailing call on cancel", () => {
|
||||
const fn = vi.fn();
|
||||
const throttled = throttle(fn, 500);
|
||||
|
||||
throttled("a");
|
||||
throttled("b");
|
||||
throttled.cancel();
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(fn).toHaveBeenCalledTimes(1);
|
||||
|
||||
throttled("c");
|
||||
expect(fn).toHaveBeenCalledTimes(2);
|
||||
expect(fn).toHaveBeenLastCalledWith("c");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
clampZoomPan,
|
||||
panBy,
|
||||
ZOOM_PAN_IDENTITY,
|
||||
zoomAtPoint,
|
||||
} from "../../../src/components/camera/zoom-pan";
|
||||
|
||||
const size = { width: 400, height: 300 };
|
||||
|
||||
// A wrong transform shows black bars next to the picture, or zooms away from
|
||||
// what the user pointed at
|
||||
describe("zoomAtPoint", () => {
|
||||
it("keeps the point under the cursor in place", () => {
|
||||
const zoomed = zoomAtPoint(ZOOM_PAN_IDENTITY, 2, { x: 100, y: 75 }, size);
|
||||
expect(zoomed).toEqual({ scale: 2, x: -100, y: -75 });
|
||||
// The content point under the cursor stays at the same screen position
|
||||
expect((100 - zoomed.x) / zoomed.scale).toBe(100 / 1);
|
||||
});
|
||||
|
||||
it("does not zoom out further than the whole picture", () => {
|
||||
const zoomed = zoomAtPoint(
|
||||
{ scale: 2, x: -100, y: -75 },
|
||||
0.5,
|
||||
{ x: 0, y: 0 },
|
||||
size
|
||||
);
|
||||
expect(zoomed).toEqual(ZOOM_PAN_IDENTITY);
|
||||
});
|
||||
|
||||
it("stops at the maximum zoom", () => {
|
||||
expect(
|
||||
zoomAtPoint(ZOOM_PAN_IDENTITY, 50, { x: 0, y: 0 }, size, 4).scale
|
||||
).toBe(4);
|
||||
});
|
||||
|
||||
it("keeps the picture covering the viewport at the edges", () => {
|
||||
// Zooming at the bottom right corner can't move the picture past it
|
||||
expect(zoomAtPoint(ZOOM_PAN_IDENTITY, 2, { x: 400, y: 300 }, size)).toEqual(
|
||||
{ scale: 2, x: -400, y: -300 }
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("panBy", () => {
|
||||
it("pans within the zoomed in picture", () => {
|
||||
expect(panBy({ scale: 2, x: -100, y: -100 }, 50, -20, size)).toEqual({
|
||||
scale: 2,
|
||||
x: -50,
|
||||
y: -120,
|
||||
});
|
||||
});
|
||||
|
||||
it("stops at the edges", () => {
|
||||
expect(panBy({ scale: 2, x: -100, y: -100 }, 500, -500, size)).toEqual({
|
||||
scale: 2,
|
||||
x: 0,
|
||||
y: -300,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not pan when not zoomed in", () => {
|
||||
expect(panBy(ZOOM_PAN_IDENTITY, 50, 50, size)).toEqual(ZOOM_PAN_IDENTITY);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clampZoomPan", () => {
|
||||
it("resets below the original size", () => {
|
||||
expect(clampZoomPan({ scale: 0.8, x: 10, y: 10 }, size)).toEqual(
|
||||
ZOOM_PAN_IDENTITY
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -412,12 +412,12 @@ exports[`downSampleLineData > large scale digest is stable 1`] = `
|
||||
96.917,
|
||||
],
|
||||
"last": [
|
||||
1707066870000,
|
||||
220.635,
|
||||
1707067170000,
|
||||
203.318,
|
||||
],
|
||||
"numberCount": 3336,
|
||||
"numberSum": "2.84488807401e+15",
|
||||
"size": 1668,
|
||||
"numberCount": 3338,
|
||||
"numberSum": "2.84659514118e+15",
|
||||
"size": 1669,
|
||||
"type": "array",
|
||||
}
|
||||
`;
|
||||
@@ -1046,6 +1046,10 @@ exports[`downSampleLineData > min/max mode matches characterization snapshot 1`]
|
||||
1704076140000,
|
||||
43.606,
|
||||
],
|
||||
[
|
||||
1704076170000,
|
||||
46.641,
|
||||
],
|
||||
]
|
||||
`;
|
||||
|
||||
|
||||
@@ -216,7 +216,11 @@ describe("downSampleLineData", () => {
|
||||
result.forEach(([x, y]) => {
|
||||
const values = framed.get(Math.floor(x / FRAME));
|
||||
expect(values).toBeDefined();
|
||||
expect([Math.min(...values!), Math.max(...values!)]).toContain(y);
|
||||
expect([
|
||||
Math.min(...values!),
|
||||
Math.max(...values!),
|
||||
values![values!.length - 1],
|
||||
]).toContain(y);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -259,6 +263,7 @@ describe("downSampleLineData", () => {
|
||||
expect(downSampleLineData(points, 3)).toEqual([
|
||||
[FIXED_EPOCH_MS + 1_000, 10],
|
||||
[FIXED_EPOCH_MS + 2_000, 90],
|
||||
[FIXED_EPOCH_MS + 3_000, 60],
|
||||
[FIXED_EPOCH_MS + 30_000, 55],
|
||||
[FIXED_EPOCH_MS + 31_000, 45],
|
||||
]);
|
||||
@@ -300,6 +305,43 @@ describe("downSampleLineData", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a frame's last value when the next point is frames away", () => {
|
||||
// Step lines hold the last value until the next point. Dropping the
|
||||
// final 0 held the 5.9 peak for an hour (#56062).
|
||||
const start = FIXED_EPOCH_MS - (FIXED_EPOCH_MS % 300_000);
|
||||
const points: GappedPoint[] = [
|
||||
[start + 2_000, 0],
|
||||
[start + 7_000, 5.9],
|
||||
[start + 10_000, 0],
|
||||
[start + 16_000, 3.2],
|
||||
[start + 46_000, 3.7],
|
||||
[start + 76_000, 3.3],
|
||||
[start + 106_000, 0],
|
||||
[start + 3_600_000, null],
|
||||
[start + 3_600_400, 0],
|
||||
];
|
||||
expect(downSampleLineData(points, 8)).toEqual([
|
||||
[start + 2_000, 0],
|
||||
[start + 7_000, 5.9],
|
||||
[start + 106_000, 0],
|
||||
[start + 3_600_400, 0],
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not repeat a frame's minimum when it shares its x with the max", () => {
|
||||
const points: GappedPoint[] = [
|
||||
[FIXED_EPOCH_MS, 90],
|
||||
[FIXED_EPOCH_MS, 10],
|
||||
[FIXED_EPOCH_MS + 30_000, 55],
|
||||
[FIXED_EPOCH_MS + 31_000, 45],
|
||||
];
|
||||
expect(downSampleLineData(points, 3)).toEqual([
|
||||
[FIXED_EPOCH_MS, 10],
|
||||
[FIXED_EPOCH_MS + 30_000, 55],
|
||||
[FIXED_EPOCH_MS + 31_000, 45],
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a gap marker whose frame holds no values", () => {
|
||||
const points: GappedPoint[] = [
|
||||
[FIXED_EPOCH_MS, 50],
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { computeLocationSelectorValue } from "../../../src/components/ha-selector/compute-location-selector-value";
|
||||
|
||||
describe("computeLocationSelectorValue", () => {
|
||||
it("rounds an edited radius", () => {
|
||||
expect(
|
||||
computeLocationSelectorValue(
|
||||
{ location: { radius: true } },
|
||||
{ latitude: 1, longitude: 2, radius: 600.4 }
|
||||
)
|
||||
).toEqual({ latitude: 1, longitude: 2, radius: 600 });
|
||||
});
|
||||
|
||||
it("falls back to the default radius the map shows", () => {
|
||||
expect(
|
||||
computeLocationSelectorValue(
|
||||
{ location: { radius: true } },
|
||||
{ latitude: 3, longitude: 2 }
|
||||
)
|
||||
).toEqual({ latitude: 3, longitude: 2, radius: 1000 });
|
||||
});
|
||||
|
||||
it("leaves out a radius the user cleared", () => {
|
||||
expect(
|
||||
computeLocationSelectorValue(
|
||||
{ location: { radius: true } },
|
||||
{ latitude: 3, longitude: 2, radius: undefined }
|
||||
)
|
||||
).toEqual({ latitude: 3, longitude: 2 });
|
||||
});
|
||||
|
||||
it("keeps a read-only radius unrounded", () => {
|
||||
expect(
|
||||
computeLocationSelectorValue(
|
||||
{ location: { radius: true, radius_readonly: true } },
|
||||
{ latitude: 3, longitude: 2, radius: 65.5 }
|
||||
)
|
||||
).toEqual({ latitude: 3, longitude: 2, radius: 65.5 });
|
||||
});
|
||||
|
||||
it("leaves out the radius when the selector has none", () => {
|
||||
expect(
|
||||
computeLocationSelectorValue(
|
||||
{ location: {} },
|
||||
{ latitude: 3, longitude: 2, radius: 500 }
|
||||
)
|
||||
).toEqual({ latitude: 3, longitude: 2 });
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
computeCameraStreamStatus,
|
||||
selectCameraStreams,
|
||||
type CameraStreamSelectionOptions,
|
||||
} from "../../src/data/camera-streams";
|
||||
@@ -43,3 +44,57 @@ describe("selectCameraStreams", () => {
|
||||
expect(select({ webRtcStreams: failed, hlsStreams: failed })).toBe("mjpeg");
|
||||
});
|
||||
});
|
||||
|
||||
// The badge over the player tells the user how the stream is connected
|
||||
describe("computeCameraStreamStatus", () => {
|
||||
const hlsLoading = [
|
||||
{ type: "hls" as const, visible: true },
|
||||
{ type: "web_rtc" as const, visible: false },
|
||||
];
|
||||
|
||||
it("connects until the shown stream plays", () => {
|
||||
expect(computeCameraStreamStatus([], new Set())).toEqual({
|
||||
connecting: true,
|
||||
hasAudio: false,
|
||||
});
|
||||
expect(computeCameraStreamStatus(hlsLoading, new Set(), ok)).toEqual({
|
||||
type: "hls",
|
||||
connecting: true,
|
||||
upgrading: undefined,
|
||||
hasAudio: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows WebRTC connecting in the background while HLS plays", () => {
|
||||
expect(computeCameraStreamStatus(hlsLoading, new Set(["hls"]), ok)).toEqual(
|
||||
{
|
||||
type: "hls",
|
||||
connecting: false,
|
||||
upgrading: "web_rtc",
|
||||
hasAudio: true,
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
it("takes the sound of the shown stream", () => {
|
||||
expect(
|
||||
computeCameraStreamStatus(
|
||||
[{ type: "web_rtc", visible: true }],
|
||||
new Set(["web_rtc"]),
|
||||
ok,
|
||||
silent
|
||||
)
|
||||
).toEqual({
|
||||
type: "web_rtc",
|
||||
connecting: false,
|
||||
upgrading: undefined,
|
||||
hasAudio: false,
|
||||
});
|
||||
expect(
|
||||
computeCameraStreamStatus(
|
||||
[{ type: "mjpeg", visible: true }],
|
||||
new Set(["mjpeg"])
|
||||
).hasAudio
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { filtersMatchUnassignedItem } from "../../src/data/data_table_filters";
|
||||
|
||||
describe("filtersMatchUnassignedItem", () => {
|
||||
it("matches when no filter has a selection", () => {
|
||||
expect(filtersMatchUnassignedItem({})).toBe(true);
|
||||
expect(
|
||||
filtersMatchUnassignedItem({
|
||||
"ha-filter-labels": [],
|
||||
"ha-filter-devices": undefined,
|
||||
"ha-filter-floor-areas": {},
|
||||
})
|
||||
).toBe(true);
|
||||
expect(
|
||||
filtersMatchUnassignedItem({
|
||||
"ha-filter-floor-areas": { areas: [], floors: [], no_area: false },
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("matches a No area selection, also next to selected areas", () => {
|
||||
expect(
|
||||
filtersMatchUnassignedItem({ "ha-filter-floor-areas": { no_area: true } })
|
||||
).toBe(true);
|
||||
expect(
|
||||
filtersMatchUnassignedItem({
|
||||
"ha-filter-floor-areas": { areas: ["kitchen"], no_area: true },
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves the item out when an id is selected", () => {
|
||||
expect(filtersMatchUnassignedItem({ "ha-filter-labels": ["energy"] })).toBe(
|
||||
false
|
||||
);
|
||||
expect(
|
||||
filtersMatchUnassignedItem({
|
||||
"ha-filter-floor-areas": { floors: ["ground"] },
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("needs every filter to match", () => {
|
||||
expect(
|
||||
filtersMatchUnassignedItem({
|
||||
"ha-filter-floor-areas": { no_area: true },
|
||||
"ha-filter-categories": ["lights"],
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
TimeZone,
|
||||
} from "../../src/data/translation";
|
||||
import {
|
||||
calculateGridNetCost,
|
||||
computeConsumptionSingle,
|
||||
computeEnergyLabel,
|
||||
computeEnergyDeviceLabels,
|
||||
@@ -32,6 +33,7 @@ import {
|
||||
import type {
|
||||
EnergyData,
|
||||
EnergyPreferences,
|
||||
GridSourceTypeEnergyPreference,
|
||||
EnergySource,
|
||||
EnergySumData,
|
||||
} from "../../src/data/energy";
|
||||
@@ -2868,3 +2870,75 @@ describe("computeConsumptionData with a home meter", () => {
|
||||
assert.equal(consumption.used_grid[1], baseline.used_grid[1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("calculateGridNetCost", () => {
|
||||
const grid = (
|
||||
overrides: Partial<GridSourceTypeEnergyPreference>
|
||||
): GridSourceTypeEnergyPreference => ({
|
||||
type: "grid",
|
||||
stat_energy_from: "sensor.import",
|
||||
stat_energy_to: "sensor.export",
|
||||
stat_cost: null,
|
||||
entity_energy_price: null,
|
||||
number_energy_price: null,
|
||||
stat_compensation: null,
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
cost_adjustment_day: 0,
|
||||
...overrides,
|
||||
});
|
||||
const series = (...changes: (number | null)[]) =>
|
||||
changes.map((change, i) => ({ start: i, end: i + 1, change }));
|
||||
const info = {
|
||||
cost_sensors: {
|
||||
"sensor.import": "sensor.import_cost",
|
||||
"sensor.export": "sensor.export_compensation",
|
||||
},
|
||||
solar_forecast_domains: [],
|
||||
};
|
||||
|
||||
it("subtracts export compensation from import cost", () => {
|
||||
assert.equal(
|
||||
calculateGridNetCost([grid({})], info, {
|
||||
"sensor.import": series(2, 3),
|
||||
"sensor.import_cost": series(1, 1.5),
|
||||
"sensor.export": series(4),
|
||||
"sensor.export_compensation": series(0.5),
|
||||
}),
|
||||
2
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers configured cost statistics over generated cost sensors", () => {
|
||||
assert.equal(
|
||||
calculateGridNetCost(
|
||||
[grid({ stat_cost: "sensor.my_cost", stat_energy_to: null })],
|
||||
info,
|
||||
{
|
||||
"sensor.import": series(2),
|
||||
"sensor.import_cost": series(9),
|
||||
"sensor.my_cost": series(1.25),
|
||||
}
|
||||
),
|
||||
1.25
|
||||
);
|
||||
});
|
||||
|
||||
it("returns undefined without cost statistics or period data", () => {
|
||||
assert.isUndefined(
|
||||
calculateGridNetCost(
|
||||
[grid({})],
|
||||
{ ...info, cost_sensors: {} },
|
||||
{
|
||||
"sensor.import": series(2),
|
||||
}
|
||||
)
|
||||
);
|
||||
assert.isUndefined(
|
||||
calculateGridNetCost([grid({})], info, {
|
||||
"sensor.import": series(null),
|
||||
"sensor.import_cost": series(null),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
computeGroupMemberEntries,
|
||||
computeGroupMemberIds,
|
||||
filterGroupsWithListedMembers,
|
||||
} from "../../src/data/group";
|
||||
import type { HomeAssistant } from "../../src/types";
|
||||
|
||||
const entity = (
|
||||
entity_id: string,
|
||||
@@ -74,6 +76,52 @@ describe("computeGroupMemberIds", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeGroupMemberEntries", () => {
|
||||
const entities = {
|
||||
"light.member": {
|
||||
entity_id: "light.member",
|
||||
platform: "member_platform",
|
||||
translation_key: "member_key",
|
||||
},
|
||||
"light.no_platform": {
|
||||
entity_id: "light.no_platform",
|
||||
translation_key: "member_key",
|
||||
},
|
||||
"light.no_translation_key": {
|
||||
entity_id: "light.no_translation_key",
|
||||
platform: "member_platform",
|
||||
},
|
||||
"switch.member": {
|
||||
entity_id: "switch.member",
|
||||
platform: "member_platform",
|
||||
translation_key: "member_key",
|
||||
},
|
||||
} as unknown as HomeAssistant["entities"];
|
||||
|
||||
it("keeps same-domain members with translations", () => {
|
||||
expect(
|
||||
computeGroupMemberEntries(
|
||||
entity("light.group", {
|
||||
entity_id: [
|
||||
"light.member",
|
||||
"light.no_platform",
|
||||
"light.no_translation_key",
|
||||
"light.unknown",
|
||||
"switch.member",
|
||||
],
|
||||
}),
|
||||
entities
|
||||
)
|
||||
).toEqual([entities["light.member"]]);
|
||||
});
|
||||
|
||||
it("not a group: no members", () => {
|
||||
expect(computeGroupMemberEntries(entity("light.lamp"), entities)).toEqual(
|
||||
[]
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterGroupsWithListedMembers", () => {
|
||||
const lamp = entity("light.lamp");
|
||||
const ceiling = entity("light.ceiling");
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { HomeAssistant } from "../../src/types";
|
||||
|
||||
vi.hoisted(() => {
|
||||
Object.assign(globalThis, { __BACKWARDS_COMPAT__: false });
|
||||
});
|
||||
|
||||
const { attributeIcon } = await import("../../src/data/icons");
|
||||
|
||||
const ICONS = {
|
||||
entity: {
|
||||
member_platform: {
|
||||
light: {
|
||||
member_key: {
|
||||
state_attributes: {
|
||||
effect: {
|
||||
default: "mdi:member-default",
|
||||
state: { candle: "mdi:candle" },
|
||||
},
|
||||
level: {
|
||||
default: "mdi:member-default",
|
||||
range: { "0": "mdi:level-low", "50": "mdi:level-high" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
entity_component: {
|
||||
light: {
|
||||
_: {
|
||||
default: "mdi:lightbulb",
|
||||
state_attributes: {
|
||||
effect: { default: "mdi:circle-medium", state: {} },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const connection = {
|
||||
haVersion: "2026.11.0",
|
||||
sendMessagePromise: async (message: {
|
||||
category: "entity" | "entity_component";
|
||||
integration?: string;
|
||||
}) => {
|
||||
if (message.integration === "failing_platform") {
|
||||
throw new Error("Icons not available");
|
||||
}
|
||||
return { resources: ICONS[message.category] };
|
||||
},
|
||||
} as unknown as HomeAssistant["connection"];
|
||||
|
||||
const config = {
|
||||
components: ["light", "member_platform", "failing_platform"],
|
||||
} as unknown as HomeAssistant["config"];
|
||||
|
||||
const entities = {
|
||||
"light.group": { platform: "group" },
|
||||
"light.member": {
|
||||
platform: "member_platform",
|
||||
translation_key: "member_key",
|
||||
},
|
||||
"light.failing_member": {
|
||||
platform: "failing_platform",
|
||||
translation_key: "failing_key",
|
||||
},
|
||||
} as unknown as HomeAssistant["entities"];
|
||||
|
||||
const groupState = {
|
||||
entity_id: "light.group",
|
||||
attributes: { entity_id: ["light.member"] },
|
||||
} as unknown as HassEntity;
|
||||
|
||||
describe("attributeIcon", () => {
|
||||
it("uses the icon of a group member for the value", async () => {
|
||||
expect(
|
||||
await attributeIcon(
|
||||
config,
|
||||
connection,
|
||||
entities,
|
||||
groupState,
|
||||
"effect",
|
||||
"candle"
|
||||
)
|
||||
).toBe("mdi:candle");
|
||||
});
|
||||
|
||||
it("does not use the default icon of a group member", async () => {
|
||||
expect(
|
||||
await attributeIcon(
|
||||
config,
|
||||
connection,
|
||||
entities,
|
||||
groupState,
|
||||
"effect",
|
||||
"fire"
|
||||
)
|
||||
).toBe("mdi:circle-medium");
|
||||
});
|
||||
|
||||
it("uses the range icon of a group member for a numeric value", async () => {
|
||||
expect(
|
||||
await attributeIcon(
|
||||
config,
|
||||
connection,
|
||||
entities,
|
||||
groupState,
|
||||
"level",
|
||||
"60"
|
||||
)
|
||||
).toBe("mdi:level-high");
|
||||
});
|
||||
|
||||
it("continues when the icons of a group member fail to load", async () => {
|
||||
const state = {
|
||||
entity_id: "light.group",
|
||||
attributes: { entity_id: ["light.failing_member", "light.member"] },
|
||||
} as unknown as HassEntity;
|
||||
|
||||
expect(
|
||||
await attributeIcon(
|
||||
config,
|
||||
connection,
|
||||
entities,
|
||||
state,
|
||||
"effect",
|
||||
"candle"
|
||||
)
|
||||
).toBe("mdi:candle");
|
||||
expect(
|
||||
await attributeIcon(config, connection, entities, state, "effect", "fire")
|
||||
).toBe("mdi:circle-medium");
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ class TestRouter extends HassRouterPage {
|
||||
routes: {
|
||||
immediate: { tag: "test-immediate-panel" },
|
||||
deferred: { tag: "test-deferred-panel", waitForReady: true },
|
||||
redirected: { tag: "test-redirected-panel", waitForReady: true },
|
||||
loaded: {
|
||||
tag: "test-loaded-panel",
|
||||
load: () => loadedPanelImport,
|
||||
@@ -29,6 +30,10 @@ class DeferredPanel extends ReactiveElement {
|
||||
@state() public loaded = false;
|
||||
}
|
||||
|
||||
class RedirectedPanel extends HTMLElement {}
|
||||
|
||||
customElements.define("test-redirected-panel", RedirectedPanel);
|
||||
|
||||
let resolveLoadedPanelImport: () => void;
|
||||
const loadedPanelImport = new Promise<void>((resolve) => {
|
||||
resolveLoadedPanelImport = resolve;
|
||||
@@ -237,6 +242,34 @@ describe("HassRouterPage panel readiness", () => {
|
||||
panelIsReady(element.lastElementChild as HTMLElement);
|
||||
await expect(element.rendered).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("waits for the panel that replaces one before it was ready", async () => {
|
||||
const element = await mountRouter("/deferred");
|
||||
let ready = false;
|
||||
element.rendered.then(() => {
|
||||
ready = true;
|
||||
});
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, 0);
|
||||
});
|
||||
|
||||
// The panel redirects, as a dashboard can, before it is ready, so it
|
||||
// never will be
|
||||
element.route = { prefix: "", path: "/redirected" };
|
||||
await element.updateComplete;
|
||||
expect(ready).toBe(false);
|
||||
|
||||
const redirected = element.querySelector("test-redirected-panel");
|
||||
|
||||
if (!redirected) {
|
||||
throw new Error("The redirected panel was not created");
|
||||
}
|
||||
|
||||
panelIsReady(redirected);
|
||||
await vi.waitFor(() => {
|
||||
expect(ready).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("HassRouterPage update propagation during load", () => {
|
||||
@@ -492,6 +525,7 @@ declare global {
|
||||
"test-router": TestRouter;
|
||||
"test-immediate-panel": ImmediatePanel;
|
||||
"test-deferred-panel": DeferredPanel;
|
||||
"test-redirected-panel": RedirectedPanel;
|
||||
"test-loaded-panel": LoadedPanel;
|
||||
"test-prop-router": PropRouter;
|
||||
"test-prop-panel": PropPanel;
|
||||
|
||||
@@ -10,7 +10,6 @@ const makeBridge = () =>
|
||||
new PictureElementsEditorBridge({
|
||||
selectElement: vi.fn(),
|
||||
moveElement: vi.fn(),
|
||||
clickImage: vi.fn(),
|
||||
});
|
||||
|
||||
describe("PictureElementsEditorBridge", () => {
|
||||
|
||||
@@ -7,13 +7,16 @@ import type {
|
||||
} from "../../../../../src/panels/lovelace/elements/types";
|
||||
|
||||
// The image is 400x300 px; elements are placed by inline left/top in px, which
|
||||
// is what getComputedStyle reports for them.
|
||||
// is what getComputedStyle reports for them. jsdom has no layout, so the
|
||||
// image's computed size comes from its inline size as well.
|
||||
const setup = ({
|
||||
configs = [{ type: "icon" }] as LovelaceElementConfig[],
|
||||
active = true,
|
||||
selectedIndex = undefined as number | undefined,
|
||||
} = {}) => {
|
||||
const root = document.createElement("div");
|
||||
root.style.width = "400px";
|
||||
root.style.height = "300px";
|
||||
root.getBoundingClientRect = () => new DOMRect(0, 0, 400, 300);
|
||||
Object.defineProperty(root, "offsetWidth", { value: 400 });
|
||||
Object.defineProperty(root, "offsetHeight", { value: 300 });
|
||||
@@ -25,6 +28,9 @@ const setup = ({
|
||||
el.style.left = "100px";
|
||||
el.style.top = "60px";
|
||||
el.getBoundingClientRect = () => new DOMRect(88, 48, 24, 24);
|
||||
// Rendered, unlike in jsdom.
|
||||
el.getClientRects = () =>
|
||||
[el.getBoundingClientRect()] as unknown as DOMRectList;
|
||||
root.appendChild(el);
|
||||
return el;
|
||||
});
|
||||
@@ -44,7 +50,6 @@ const setup = ({
|
||||
const handlers = {
|
||||
selectElement: vi.fn(),
|
||||
moveElement: vi.fn(),
|
||||
clickImage: vi.fn(),
|
||||
};
|
||||
const bridge = new PictureElementsEditorBridge(handlers);
|
||||
bridge.setState(active, selectedIndex);
|
||||
@@ -134,7 +139,7 @@ describe("PictureElementsEditorPreviewController", () => {
|
||||
const { elements, handlers, gesture } = setup();
|
||||
gesture(elements[0], [100, 60], [140, 90]);
|
||||
// +40px of 400px and +30px of 300px from 25%/20%.
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, 35, 30);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, { left: 35, top: 30 });
|
||||
expect(elements[0].style.left).toBe("35%");
|
||||
expect(handlers.selectElement).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -142,7 +147,104 @@ describe("PictureElementsEditorPreviewController", () => {
|
||||
it("keeps a dragged element on the image", () => {
|
||||
const { elements, handlers, gesture } = setup();
|
||||
gesture(elements[0], [100, 60], [-500, 900]);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, 0, 100);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, { left: 0, top: 100 });
|
||||
});
|
||||
|
||||
describe("elements placed from the right or bottom", () => {
|
||||
// 300px from the right and 240px from the bottom, where left/top put it.
|
||||
// The card's transform centers an element on its left/top point only, so
|
||||
// from the right or bottom its center is its own size further left or up.
|
||||
const setupFrom = (style: Record<string, string>) => {
|
||||
const test = setup({ configs: [{ type: "icon", style }] });
|
||||
const element = test.elements[0];
|
||||
element.style.right = "300px";
|
||||
element.style.bottom = "240px";
|
||||
element.getBoundingClientRect = () =>
|
||||
new DOMRect(style.right ? 64 : 88, style.bottom ? 24 : 48, 24, 24);
|
||||
return test;
|
||||
};
|
||||
|
||||
it.each([
|
||||
[
|
||||
{ right: "75%", bottom: "80%" },
|
||||
{ right: 65, bottom: 70 },
|
||||
],
|
||||
[
|
||||
{ left: "25%", bottom: "80%" },
|
||||
{ left: 35, bottom: 70 },
|
||||
],
|
||||
[
|
||||
{ right: "75%", top: "20%" },
|
||||
{ right: 65, top: 30 },
|
||||
],
|
||||
])("moves an element styled %j along its sides", (style, moved) => {
|
||||
const { elements, handlers, gesture } = setupFrom(style);
|
||||
// +40px of 400px and +30px of 300px.
|
||||
gesture(elements[0], [100, 60], [140, 90]);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, moved);
|
||||
for (const [prop, value] of Object.entries(moved)) {
|
||||
expect(elements[0].style.getPropertyValue(prop)).toBe(`${value}%`);
|
||||
}
|
||||
});
|
||||
|
||||
// The center goes from 19%/12% to the top left or bottom right corner.
|
||||
it.each([
|
||||
[[-500, -500], { right: 94, bottom: 92 }],
|
||||
[[900, 900], { right: -6, bottom: -8 }],
|
||||
])(
|
||||
"keeps the center of an element dragged to %j on the image",
|
||||
(to, moved) => {
|
||||
const { elements, handlers, gesture } = setupFrom({
|
||||
right: "75%",
|
||||
bottom: "80%",
|
||||
});
|
||||
gesture(elements[0], [100, 60], to as [number, number]);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, moved);
|
||||
}
|
||||
);
|
||||
|
||||
it("moves an element placed past a side of the image", () => {
|
||||
const { elements, handlers, gesture } = setupFrom({
|
||||
right: "-5%",
|
||||
top: "20%",
|
||||
});
|
||||
// 20px past the right side, which puts its center 4px inside.
|
||||
elements[0].style.right = "-20px";
|
||||
elements[0].getBoundingClientRect = () => new DOMRect(384, 48, 24, 24);
|
||||
gesture(elements[0], [396, 60], [388, 60]);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, {
|
||||
right: -3,
|
||||
top: 20,
|
||||
});
|
||||
});
|
||||
|
||||
it("moves the element's center to a click on the image", () => {
|
||||
const { root, bridge, handlers, gesture } = setupFrom({
|
||||
right: "75%",
|
||||
bottom: "80%",
|
||||
});
|
||||
bridge.setState(true, 0);
|
||||
// From 19%/12% to 50%/25%.
|
||||
gesture(root, [200, 75]);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, {
|
||||
right: 44,
|
||||
bottom: 67,
|
||||
});
|
||||
});
|
||||
|
||||
it("puts an element back when the drag is cancelled", () => {
|
||||
const { root, elements, pointer } = setupFrom({
|
||||
right: "75%",
|
||||
bottom: "80%",
|
||||
});
|
||||
pointer("pointerdown", elements[0], 100, 60);
|
||||
pointer("pointermove", root, 140, 90);
|
||||
pointer("pointercancel", root, 140, 90);
|
||||
expect(elements[0].style.right).toBe("75%");
|
||||
expect(elements[0].style.bottom).toBe("80%");
|
||||
expect(elements[0].style.left).toBe("100px");
|
||||
expect(elements[0].style.top).toBe("60px");
|
||||
});
|
||||
});
|
||||
|
||||
it("only drags a large overlay once it is selected", () => {
|
||||
@@ -154,14 +256,14 @@ describe("PictureElementsEditorPreviewController", () => {
|
||||
|
||||
bridge.setState(true, 0);
|
||||
gesture(elements[0], [100, 60], [140, 90]);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, 35, 30);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, { left: 35, top: 30 });
|
||||
});
|
||||
|
||||
it("never drags elements it can't write back", () => {
|
||||
const { elements, handlers, gesture } = setup({
|
||||
configs: [
|
||||
{ type: "conditional" },
|
||||
{ type: "icon", style: { right: "5%" } },
|
||||
{ type: "icon", style: { left: "5%", right: "5%" } },
|
||||
{ type: "icon", style: { left: "100px" } },
|
||||
],
|
||||
});
|
||||
@@ -196,6 +298,20 @@ describe("PictureElementsEditorPreviewController", () => {
|
||||
expect(handlers.moveElement).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("puts an element back whose sides changed during the drag", () => {
|
||||
const configs: LovelaceElementConfig[] = [
|
||||
{ type: "icon", style: { left: "25%", top: "20%" } },
|
||||
];
|
||||
const { root, elements, handlers, pointer } = setup({ configs });
|
||||
pointer("pointerdown", elements[0], 100, 60);
|
||||
pointer("pointermove", root, 140, 90);
|
||||
configs[0] = { type: "icon", style: { right: "75%", top: "20%" } };
|
||||
pointer("pointerup", root, 140, 90);
|
||||
expect(handlers.moveElement).not.toHaveBeenCalled();
|
||||
expect(elements[0].style.left).toBe("");
|
||||
expect(elements[0].style.top).toBe("20%");
|
||||
});
|
||||
|
||||
it("puts an element placed at a YAML zero back when cancelled", () => {
|
||||
const { root, elements, pointer } = setup({
|
||||
configs: [{ type: "icon", style: { left: 0 as never, top: "20%" } }],
|
||||
@@ -230,16 +346,117 @@ describe("PictureElementsEditorPreviewController", () => {
|
||||
expect(handlers.moveElement).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports a click on the image in percent", () => {
|
||||
const { root, handlers, gesture } = setup();
|
||||
it("moves the selected element's center to a click on the image", () => {
|
||||
const { root, bridge, handlers, gesture } = setup();
|
||||
gesture(root, [200, 75]);
|
||||
expect(handlers.clickImage).toHaveBeenCalledWith(50, 25);
|
||||
expect(handlers.moveElement).not.toHaveBeenCalled();
|
||||
|
||||
bridge.setState(true, 0);
|
||||
gesture(root, [200, 75]);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, { left: 50, top: 25 });
|
||||
});
|
||||
|
||||
describe("an image with a fractional size", () => {
|
||||
// Its height is its width times the aspect ratio, while offsetWidth and
|
||||
// offsetHeight stay rounded to 400x300. The element is at 25%/25%.
|
||||
const setupFractional = (selectedIndex?: number) => {
|
||||
const test = setup({ selectedIndex });
|
||||
test.root.style.width = "399.5px";
|
||||
test.root.style.height = "300.5px";
|
||||
test.root.getBoundingClientRect = () => new DOMRect(0, 0, 399.5, 300.5);
|
||||
const element = test.elements[0];
|
||||
element.style.left = "99.875px";
|
||||
element.style.top = "75.125px";
|
||||
element.getBoundingClientRect = () => new DOMRect(87.875, 63.125, 24, 24);
|
||||
return test;
|
||||
};
|
||||
|
||||
it("moves the selected element's center exactly to a click", () => {
|
||||
const { root, handlers, gesture } = setupFractional(0);
|
||||
gesture(root, [99.875, 75.125]);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, {
|
||||
left: 25,
|
||||
top: 25,
|
||||
});
|
||||
});
|
||||
|
||||
it("stops a dragged element exactly at a side of the image", () => {
|
||||
const { elements, handlers, gesture } = setupFractional();
|
||||
gesture(elements[0], [99.875, 75.125], [-500, 75.125]);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, {
|
||||
left: 0,
|
||||
top: 25,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("an image scaled by an ancestor", () => {
|
||||
// Laid out at 400x300 px but shown at 320x240 px, like under scale(0.8).
|
||||
// The element's computed left/top stay in layout px (25%/20%), while its
|
||||
// rect is scaled like the image's.
|
||||
const setupScaled = (selectedIndex?: number) => {
|
||||
const test = setup({
|
||||
configs: [{ type: "icon", style: { left: "25%", top: "20%" } }],
|
||||
selectedIndex,
|
||||
});
|
||||
test.root.getBoundingClientRect = () => new DOMRect(0, 0, 320, 240);
|
||||
test.elements[0].getBoundingClientRect = () =>
|
||||
new DOMRect(72, 40, 16, 16);
|
||||
return test;
|
||||
};
|
||||
|
||||
it("moves the selected element's center to a click", () => {
|
||||
const { root, handlers, gesture } = setupScaled(0);
|
||||
gesture(root, [160, 120]);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, {
|
||||
left: 50,
|
||||
top: 50,
|
||||
});
|
||||
});
|
||||
|
||||
it("moves a dragged element by the pointer delta", () => {
|
||||
const { elements, handlers, gesture } = setupScaled();
|
||||
// +40 of 320 visual px.
|
||||
gesture(elements[0], [80, 48], [120, 48]);
|
||||
expect(handlers.moveElement).toHaveBeenCalledWith(0, {
|
||||
left: 37.5,
|
||||
top: 20,
|
||||
});
|
||||
expect(elements[0].style.left).toBe("37.5%");
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves elements alone while the image has no height", () => {
|
||||
const { root, elements, handlers, gesture } = setup({ selectedIndex: 0 });
|
||||
root.style.height = "0px";
|
||||
root.getBoundingClientRect = () => new DOMRect(0, 0, 400, 0);
|
||||
gesture(elements[0], [100, 60], [140, 90]);
|
||||
gesture(root, [200, 0]);
|
||||
expect(handlers.moveElement).not.toHaveBeenCalled();
|
||||
expect(elements[0].style.left).toBe("100px");
|
||||
});
|
||||
|
||||
it("leaves a selected element alone while it is hidden", () => {
|
||||
const { root, elements, handlers, gesture } = setup({
|
||||
configs: [{ type: "icon", style: { left: "50%", top: "50%" } }],
|
||||
selectedIndex: 0,
|
||||
});
|
||||
// With display: none it has no layout, and its computed left/top stay in
|
||||
// percent.
|
||||
elements[0].style.left = "50%";
|
||||
elements[0].style.top = "50%";
|
||||
elements[0].getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
|
||||
elements[0].getClientRects = () => [] as unknown as DOMRectList;
|
||||
gesture(root, [200, 75]);
|
||||
gesture(elements[0], [0, 0], [40, 30]);
|
||||
expect(handlers.moveElement).not.toHaveBeenCalled();
|
||||
expect(elements[0].style.left).toBe("50%");
|
||||
});
|
||||
|
||||
it("ignores a drag across the image", () => {
|
||||
const { root, handlers, gesture } = setup();
|
||||
const { root, handlers, gesture } = setup({ selectedIndex: 0 });
|
||||
gesture(root, [200, 75], [500, -20]);
|
||||
expect(handlers.clickImage).not.toHaveBeenCalled();
|
||||
expect(handlers.moveElement).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores ctrl-clicks, which open the context menu on macOS", () => {
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isMovableElement } from "../../../../../src/panels/lovelace/cards/picture-elements/movable-element";
|
||||
import {
|
||||
elementAnchors,
|
||||
isMovableElement,
|
||||
movedStyle,
|
||||
} from "../../../../../src/panels/lovelace/cards/picture-elements/movable-element";
|
||||
|
||||
// Styles as YAML can produce them, not only strings.
|
||||
const styled = (style: Record<string, unknown>) =>
|
||||
@@ -13,19 +17,37 @@ describe("isMovableElement", () => {
|
||||
[{ left: 0, top: null }],
|
||||
[{ position: "Absolute" }],
|
||||
[{ transform: "translate(-50%, -50%)" }],
|
||||
[{ right: "5%" }],
|
||||
[{ bottom: 0 }],
|
||||
[{ left: "", right: "5%", top: null, bottom: "10%" }],
|
||||
[{ Right: "", Bottom: null }],
|
||||
[{ right: "", Right: "", top: "5%" }],
|
||||
// The card removes the sides at the empty inset, before it sets them.
|
||||
[{ inset: "" }],
|
||||
[{ Inset: null, right: "5%", bottom: "10%" }],
|
||||
[{ inset: "", left: "12.3%", top: "20%" }],
|
||||
])("moves an element styled %j", (style) => {
|
||||
expect(styled(style)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ position: "relative" }],
|
||||
[{ right: "5%" }],
|
||||
[{ bottom: 0 }],
|
||||
[{ left: "10%", right: "5%" }],
|
||||
[{ top: 0, bottom: "5%" }],
|
||||
[{ right: "5px" }],
|
||||
[{ Bottom: "5%" }],
|
||||
[{ inset: "0" }],
|
||||
[{ "inset-inline-start": "10%" }],
|
||||
[{ left: "120px" }],
|
||||
[{ top: "calc(50% - 10px)" }],
|
||||
[{ Left: "10%" }],
|
||||
[{ Top: "" }],
|
||||
// Depending on the key order, the empty key removes the side again.
|
||||
[{ right: "5%", Right: "" }],
|
||||
[{ Bottom: null, bottom: "5%" }],
|
||||
// The empty inset removes the sides again.
|
||||
[{ right: "10%", bottom: "20%", inset: "" }],
|
||||
[{ left: "10%", Inset: null }],
|
||||
])("leaves an element styled %j alone", (style) => {
|
||||
expect(styled(style)).toBe(false);
|
||||
});
|
||||
@@ -43,3 +65,107 @@ describe("isMovableElement", () => {
|
||||
expect(isMovableElement({ type: "conditional" })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("elementAnchors", () => {
|
||||
it.each([
|
||||
[{}, { x: "left", y: "top" }],
|
||||
[
|
||||
{ right: "5%", bottom: "10%" },
|
||||
{ x: "right", y: "bottom" },
|
||||
],
|
||||
[
|
||||
{ left: "5%", bottom: "10%" },
|
||||
{ x: "left", y: "bottom" },
|
||||
],
|
||||
[
|
||||
{ right: "5%", top: "10%" },
|
||||
{ x: "right", y: "top" },
|
||||
],
|
||||
])("places an element styled %j from %j", (style, anchors) => {
|
||||
expect(elementAnchors({ type: "icon", style })).toEqual(anchors);
|
||||
});
|
||||
});
|
||||
|
||||
describe("movedStyle", () => {
|
||||
// A spot on the image, from all of its sides.
|
||||
const SPOT = { left: 12.34, right: 87.66, top: 20, bottom: 80 };
|
||||
|
||||
it.each([
|
||||
[{ color: "red" }, { color: "red", left: "12.3%", top: "20%" }],
|
||||
[
|
||||
{ right: "5%", bottom: "5%" },
|
||||
{ right: "87.7%", bottom: "80%" },
|
||||
],
|
||||
[
|
||||
{ left: "5%", bottom: "5%" },
|
||||
{ left: "12.3%", bottom: "80%" },
|
||||
],
|
||||
[
|
||||
{ right: "5%", top: "5%" },
|
||||
{ right: "87.7%", top: "20%" },
|
||||
],
|
||||
])("moves an element styled %j along its sides", (style, moved) => {
|
||||
expect(movedStyle({ type: "icon", style }, SPOT)).toEqual(moved);
|
||||
});
|
||||
|
||||
const moved = (style: Record<string, unknown>) =>
|
||||
movedStyle({ type: "icon", style: style as Record<string, string> }, SPOT)!;
|
||||
|
||||
it.each([
|
||||
[
|
||||
{ top: "", inset: "", right: "5%" },
|
||||
{ right: "87.7%", top: "20%" },
|
||||
],
|
||||
[
|
||||
{ left: "", inset: "", top: "5%" },
|
||||
{ left: "12.3%", top: "20%" },
|
||||
],
|
||||
[
|
||||
{ left: "", top: null, Inset: null, color: "red" },
|
||||
{ left: "12.3%", top: "20%" },
|
||||
],
|
||||
])("keeps the sides of %j behind the empty inset", (style, sides) => {
|
||||
// Set key by key like the card does.
|
||||
const element = document.createElement("div");
|
||||
for (const [prop, value] of Object.entries(moved(style))) {
|
||||
element.style.setProperty(prop, value);
|
||||
}
|
||||
for (const [side, value] of Object.entries(sides)) {
|
||||
expect(element.style.getPropertyValue(side)).toBe(value);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
{ left: "5%", color: "red", top: "5%" },
|
||||
[
|
||||
["left", "12.3%"],
|
||||
["color", "red"],
|
||||
["top", "20%"],
|
||||
],
|
||||
],
|
||||
[
|
||||
{ inset: "", bottom: "5%", color: "red", right: "5%" },
|
||||
[
|
||||
["inset", ""],
|
||||
["bottom", "80%"],
|
||||
["color", "red"],
|
||||
["right", "87.7%"],
|
||||
],
|
||||
],
|
||||
])("keeps the key order of %j", (style, entries) => {
|
||||
expect(Object.entries(moved(style))).toEqual(entries);
|
||||
});
|
||||
|
||||
it("leaves an element alone that it can't move there", () => {
|
||||
const style = { left: "5%", right: "5%" };
|
||||
expect(movedStyle({ type: "icon", style }, SPOT)).toBeUndefined();
|
||||
// The element no longer uses the sides the position was taken from.
|
||||
expect(
|
||||
movedStyle(
|
||||
{ type: "icon", style: { right: "5%" } },
|
||||
{ left: 10, top: 20 }
|
||||
)
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -809,7 +809,7 @@ describe("ha-marketplace-repository-dashboard", () => {
|
||||
|
||||
const subpage = page.shadowRoot!.querySelector("hass-subpage") as
|
||||
(HTMLElement & { header: string }) | null;
|
||||
expect(subpage!.header).toBe("ui.panel.marketplace.title");
|
||||
expect(subpage!.header).toBe("Marketplace");
|
||||
expect(page.shadowRoot!.querySelector(".summary h1")!.textContent).toBe(
|
||||
"Repository 1"
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { IntlMessageFormat } from "intl-messageformat";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { NAME_PLACEHOLDERS } from "../../../src/common/translations/name-placeholders";
|
||||
import en from "../../../src/translations/en.json";
|
||||
|
||||
type TranslationNode = string | { [key: string]: TranslationNode };
|
||||
@@ -13,7 +14,10 @@ const format = (key: string, values: Record<string, string | number>) => {
|
||||
typeof translations === "object" ? translations[part] : undefined,
|
||||
en as TranslationNode
|
||||
);
|
||||
return new IntlMessageFormat(message as string, "en").format(values);
|
||||
return new IntlMessageFormat(message as string, "en").format({
|
||||
...NAME_PLACEHOLDERS,
|
||||
...values,
|
||||
});
|
||||
};
|
||||
|
||||
describe("Marketplace strings", () => {
|
||||
|
||||
Reference in new issue
Block a user