mirror of
https://github.com/home-assistant/frontend.git
synced 2026-11-17 02:12:47 +00:00
Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d08b734afd | ||
|
|
4d1fc1225d | ||
|
|
18bcddaa20 | ||
|
|
ca576fadf5 | ||
|
|
aea1ac4ac8 | ||
|
|
6e1fe2846e | ||
|
|
17202283b4 | ||
|
|
0c8323c4f6 | ||
|
|
a2a523d5e5 | ||
|
|
b379c0d311 | ||
|
|
4dc975ec23 | ||
|
|
84294d7a8f | ||
|
|
e5838446c8 | ||
|
|
53f000e492 | ||
|
|
c452e8e4ff | ||
|
|
e80b07893d | ||
|
|
c801a52e67 | ||
|
|
8ac2712e31 | ||
|
|
f7f15ae4a8 | ||
|
|
e66733186e | ||
|
|
1e7bdbbcc8 | ||
|
|
7292db76bf | ||
|
|
9d997fbe4c | ||
|
|
05d11c25c2 |
No files matched your search
@@ -50,7 +50,9 @@ const convertToJSON = async (
|
||||
const encodedData = localeData.match(
|
||||
/JSON\.parse\((?<data>"(?:[^"\\]|\\.)*")\)/
|
||||
)?.groups?.data;
|
||||
localeData = firstBlock.match(dataRegex)?.groups?.data;
|
||||
localeData =
|
||||
localeData.match(/\}\)\((?<data>\{.*\})\)\s*;?\s*$/s)?.groups?.data ??
|
||||
firstBlock.match(dataRegex)?.groups?.data;
|
||||
if (!localeData && !encodedData) {
|
||||
throw Error(`Failed to extract data for language ${lang} from ${pkg}`);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
stat_rate: "sensor.power_grid",
|
||||
cost_adjustment_day: 0,
|
||||
},
|
||||
{
|
||||
type: "grid",
|
||||
@@ -34,7 +33,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
stat_rate: "sensor.power_grid_return",
|
||||
cost_adjustment_day: 0,
|
||||
},
|
||||
{
|
||||
type: "solar",
|
||||
|
||||
@@ -187,6 +187,139 @@ const ENTITIES = [
|
||||
current_tilt_position: 70,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.shade",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Shade",
|
||||
device_class: "shade",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 60,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.shutter",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Shutter",
|
||||
device_class: "shutter",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 40,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.awning",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Awning",
|
||||
device_class: "awning",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 70,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.curtain",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Curtain",
|
||||
device_class: "curtain",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 50,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.door",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Door",
|
||||
device_class: "door",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 30,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.gate",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Gate",
|
||||
device_class: "gate",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 30,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.window",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Window",
|
||||
device_class: "window",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 50,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.garage",
|
||||
state: "closed",
|
||||
attributes: {
|
||||
friendly_name: "Garage door",
|
||||
device_class: "garage",
|
||||
supported_features: CoverEntityFeature.OPEN + CoverEntityFeature.CLOSE,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.unknown",
|
||||
state: "unknown",
|
||||
attributes: {
|
||||
friendly_name: "Unknown position",
|
||||
device_class: "shade",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.unavailable",
|
||||
state: "unavailable",
|
||||
attributes: {
|
||||
friendly_name: "Unavailable",
|
||||
device_class: "shutter",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@customElement("demo-more-info-cover")
|
||||
|
||||
+8
-8
@@ -48,21 +48,21 @@
|
||||
"@codemirror/lang-python": "6.2.1",
|
||||
"@codemirror/lang-yaml": "6.1.3",
|
||||
"@codemirror/language": "6.13.1",
|
||||
"@codemirror/lint": "6.9.7",
|
||||
"@codemirror/lint": "6.9.8",
|
||||
"@codemirror/search": "6.7.2",
|
||||
"@codemirror/state": "6.7.6",
|
||||
"@codemirror/view": "6.43.15",
|
||||
"@date-fns/tz": "1.5.0",
|
||||
"@egjs/hammerjs": "2.0.17",
|
||||
"@formatjs/intl-datetimeformat": "8.0.3",
|
||||
"@formatjs/intl-displaynames": "8.0.2",
|
||||
"@formatjs/intl-displaynames": "8.0.3",
|
||||
"@formatjs/intl-durationformat": "0.12.4",
|
||||
"@formatjs/intl-getcanonicallocales": "3.3.1",
|
||||
"@formatjs/intl-listformat": "9.0.2",
|
||||
"@formatjs/intl-listformat": "9.0.3",
|
||||
"@formatjs/intl-locale": "5.4.3",
|
||||
"@formatjs/intl-numberformat": "10.0.3",
|
||||
"@formatjs/intl-pluralrules": "7.0.3",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.2",
|
||||
"@formatjs/intl-numberformat": "10.0.4",
|
||||
"@formatjs/intl-pluralrules": "7.0.4",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.3",
|
||||
"@home-assistant/webawesome": "3.14.0-ha.2",
|
||||
"@lezer/common": "1.5.5",
|
||||
"@lezer/highlight": "1.2.5",
|
||||
@@ -195,7 +195,7 @@
|
||||
"gulp-rename": "2.1.0",
|
||||
"html-minifier-terser": "7.2.0",
|
||||
"husky": "9.1.7",
|
||||
"jsdom": "31.0.0",
|
||||
"jsdom": "31.0.1",
|
||||
"jszip": "3.10.2",
|
||||
"license-checker-rseidelsohn": "5.0.1",
|
||||
"lightningcss": "1.33.0",
|
||||
@@ -208,7 +208,7 @@
|
||||
"pinst": "3.0.0",
|
||||
"prettier": "3.10.1",
|
||||
"rspack-manifest-plugin": "5.2.2",
|
||||
"serve": "14.2.7",
|
||||
"serve": "14.2.8",
|
||||
"sinon": "22.1.0",
|
||||
"tar": "7.5.23",
|
||||
"terser-webpack-plugin": "5.6.1",
|
||||
|
||||
Generated
+56
-49
@@ -213,8 +213,8 @@ importers:
|
||||
specifier: 6.13.1
|
||||
version: 6.13.1
|
||||
'@codemirror/lint':
|
||||
specifier: 6.9.7
|
||||
version: 6.9.7
|
||||
specifier: 6.9.8
|
||||
version: 6.9.8
|
||||
'@codemirror/search':
|
||||
specifier: 6.7.2
|
||||
version: 6.7.2
|
||||
@@ -234,8 +234,8 @@ importers:
|
||||
specifier: 8.0.3
|
||||
version: 8.0.3
|
||||
'@formatjs/intl-displaynames':
|
||||
specifier: 8.0.2
|
||||
version: 8.0.2
|
||||
specifier: 8.0.3
|
||||
version: 8.0.3
|
||||
'@formatjs/intl-durationformat':
|
||||
specifier: 0.12.4
|
||||
version: 0.12.4
|
||||
@@ -243,20 +243,20 @@ importers:
|
||||
specifier: 3.3.1
|
||||
version: 3.3.1
|
||||
'@formatjs/intl-listformat':
|
||||
specifier: 9.0.2
|
||||
version: 9.0.2
|
||||
specifier: 9.0.3
|
||||
version: 9.0.3
|
||||
'@formatjs/intl-locale':
|
||||
specifier: 5.4.3
|
||||
version: 5.4.3
|
||||
'@formatjs/intl-numberformat':
|
||||
specifier: 10.0.3
|
||||
version: 10.0.3
|
||||
specifier: 10.0.4
|
||||
version: 10.0.4
|
||||
'@formatjs/intl-pluralrules':
|
||||
specifier: 7.0.3
|
||||
version: 7.0.3
|
||||
specifier: 7.0.4
|
||||
version: 7.0.4
|
||||
'@formatjs/intl-relativetimeformat':
|
||||
specifier: 13.0.2
|
||||
version: 13.0.2
|
||||
specifier: 13.0.3
|
||||
version: 13.0.3
|
||||
'@home-assistant/webawesome':
|
||||
specifier: 3.14.0-ha.2
|
||||
version: 3.14.0-ha.2(@floating-ui/[email protected])(@types/[email protected])
|
||||
@@ -649,8 +649,8 @@ importers:
|
||||
specifier: 9.1.7
|
||||
version: 9.1.7
|
||||
jsdom:
|
||||
specifier: 31.0.0
|
||||
version: 31.0.0
|
||||
specifier: 31.0.1
|
||||
version: 31.0.1
|
||||
jszip:
|
||||
specifier: 3.10.2
|
||||
version: 3.10.2
|
||||
@@ -688,8 +688,8 @@ importers:
|
||||
specifier: 5.2.2
|
||||
version: 5.2.2(@rspack/[email protected](@swc/[email protected]))
|
||||
serve:
|
||||
specifier: 14.2.7
|
||||
version: 14.2.7([email protected])
|
||||
specifier: 14.2.8
|
||||
version: 14.2.8([email protected])
|
||||
sinon:
|
||||
specifier: 22.1.0
|
||||
version: 22.1.0
|
||||
@@ -716,7 +716,7 @@ importers:
|
||||
version: 6.1.1([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]))
|
||||
vitest:
|
||||
specifier: 5.1.0
|
||||
version: 5.1.0(@types/[email protected])(@vitest/[email protected])([email protected].0)([email protected](@types/[email protected])([email protected])([email protected]))
|
||||
version: 5.1.0(@types/[email protected])(@vitest/[email protected])([email protected].1)([email protected](@types/[email protected])([email protected])([email protected]))
|
||||
webpack-stats-plugin:
|
||||
specifier: 1.1.3
|
||||
version: 1.1.3
|
||||
@@ -1852,8 +1852,8 @@ packages:
|
||||
'@codemirror/[email protected]':
|
||||
resolution: {integrity: sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==}
|
||||
|
||||
'@codemirror/[email protected].7':
|
||||
resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==}
|
||||
'@codemirror/[email protected].8':
|
||||
resolution: {integrity: sha512-qNvtcE73xUto/D1RvtgSRI4A1Hg8ekxlvtZpjHpdpisLBnhyu82EUEJMEgaxkjuQCA8vqnrylENWKOsEDCOHcw==}
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
resolution: {integrity: sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==}
|
||||
@@ -2042,8 +2042,8 @@ packages:
|
||||
'@formatjs/[email protected]':
|
||||
resolution: {integrity: sha512-LQed+WhJBlceMJ4Zbe7dDe7Wn15le9t5HXfOFGdJYM/MGDyn56LTHlSzPzFjsJA0rvyp4FjN28jRQiMwtsji6A==}
|
||||
|
||||
'@formatjs/[email protected].2':
|
||||
resolution: {integrity: sha512-9gayLdxgPhzw2UT2nbWBhrRN+7T2xy/cvvrEVFClRLzg1DSJJdXtdYRcbbQ8cdCRlC1O3dQag+bUeW+Kt9bRWA==}
|
||||
'@formatjs/[email protected].3':
|
||||
resolution: {integrity: sha512-UhKG1OwrbQzZNKIcmZu+/JR5SOxE25RWmUzxaNfQ04AJ4OwxNkTvAbVX0ojnkm0i8Qs4E8ElIoBdA6F8XTkJXw==}
|
||||
|
||||
'@formatjs/[email protected]':
|
||||
resolution: {integrity: sha512-EjUHL8isAQOqXuLxGllgsfIQdLrLNo8iCOQHMqUNY4Fvl52hw6TEP0n9tPnOmQWb5wTUa92NeqyGmwhjQ2lvHA==}
|
||||
@@ -2051,8 +2051,8 @@ packages:
|
||||
'@formatjs/[email protected]':
|
||||
resolution: {integrity: sha512-GkXdVwb/4Y9qJaZ19BguPv2i9Vr+z5MrlmFa/9HR7WK2tMcCWZathuGhn7W/V3sFqUdAVB3uvmGuOxXwc61DJQ==}
|
||||
|
||||
'@formatjs/[email protected].2':
|
||||
resolution: {integrity: sha512-Qfsm6eyPyD6y7AgRyiOTJVaq0IBClDXQCm0/6vT3CRiwn89npdoUv3kTuwDykGDs1igLoTPWLBdMR81HIP4qQg==}
|
||||
'@formatjs/[email protected].3':
|
||||
resolution: {integrity: sha512-XamK+7ie16gbBp51AH+K97NfwCoECk36jEbBO9m7HaInoLbG1F3P8M22enKtkifsi/cH9gjp4igFaYtY23h0uA==}
|
||||
|
||||
'@formatjs/[email protected]':
|
||||
resolution: {integrity: sha512-YdxSbfDifRIew7mukcwITPlhkomfHCcSzzbjEJqOGbod4wrfdUN7SmiZQU2Lr8zs/q/15ntZsthJ8NsW3P30mA==}
|
||||
@@ -2063,14 +2063,14 @@ packages:
|
||||
'@formatjs/[email protected]':
|
||||
resolution: {integrity: sha512-ePEgLgVCqi2BBFnTMWPfIghu6FkbZnnBVhO2sSxvLfrdFw7wCHAHiDoM2h4NRgjbaY7+B7HgOLZGkK187pZTZg==}
|
||||
|
||||
'@formatjs/[email protected].3':
|
||||
resolution: {integrity: sha512-Hi/3S+Iru5RIYNkiTJwqCmERsNwNacu3k+anfCcp7Nzn9hxhCpAuhjr6I9Y6CVUs/1D3fGSgfnJTXGukot5aBg==}
|
||||
'@formatjs/[email protected].4':
|
||||
resolution: {integrity: sha512-rQzbAgJcG/RPMR4xbFxMA33HnvXJtStYR0gGY1vcb/6JGmhZcauGE7g5Vch+EOtZkiitloSkHgU5JXmQpTTggg==}
|
||||
|
||||
'@formatjs/[email protected].3':
|
||||
resolution: {integrity: sha512-moK0Ee0ddD8d8tZnoZ1JDUdNLBURXT5NMG4cnvYQY2bTYLphPhZk2KxgD78y6+lL69J4ihpQJleI+K5KlE39gw==}
|
||||
'@formatjs/[email protected].4':
|
||||
resolution: {integrity: sha512-EeQ8YUs1QOpYLUiNHkHfR1rsOMtQUBQXEQwR9WmJRWfzvVXeYZ7vBeMARtlb2KuHUgdmfXjoin5oNn68hjyrEQ==}
|
||||
|
||||
'@formatjs/[email protected].2':
|
||||
resolution: {integrity: sha512-g7AVCP/0r49+h4R1qnQcNpq78JoEIthwp+QtHv9VkHw1c0bEegmhuz1t03DEr2u5nqP4HE//yAFjQtrv66b67A==}
|
||||
'@formatjs/[email protected].3':
|
||||
resolution: {integrity: sha512-5nyIp4F/59A5hcfU6lZphSslpildVSirqudWfygBENGdGSHmggZVjhoad458XWEgtUd6d0JoiwsiUBFLfbqJ9Q==}
|
||||
|
||||
'@formatjs/[email protected]':
|
||||
resolution: {integrity: sha512-+9TU+8tqsUqobFzQJEvfQ8Yukt1PYgL5WxYi/yW+hWVNx422wEo/TlVRLvIfdYqlVS048jfyu8piNagfhOV+2A==}
|
||||
@@ -4561,8 +4561,8 @@ packages:
|
||||
resolution: {integrity: sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==}
|
||||
engines: {node: '>= 0.6'}
|
||||
|
||||
[email protected].1:
|
||||
resolution: {integrity: sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==}
|
||||
[email protected].2:
|
||||
resolution: {integrity: sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==}
|
||||
engines: {node: '>= 0.8.0'}
|
||||
|
||||
[email protected]:
|
||||
@@ -4764,6 +4764,10 @@ packages:
|
||||
resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==}
|
||||
engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-DtCOLG98P007x7wiiOmfI0fi3eIKyWiLTGJ2MDnVi/E04lWGbf+JzrRHMm0rgIIZJGtHpKpbVgLWHrv8xXpc3Q==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
@@ -5863,8 +5867,8 @@ packages:
|
||||
resolution: {integrity: sha512-paNr4LFIFPjeeSmwNYdrb8FafLLG/Cr2Af3GjbsHJ5CxIjH4r0c2emlmRdAtpPAieP1gRVzk6buBbVP5gBMGAg==}
|
||||
hasBin: true
|
||||
|
||||
[email protected].0:
|
||||
resolution: {integrity: sha512-xAkhD9z1eyFC5+QUi9K24CaZJgdCQ2GOGLW1GdVDoQvkp/AxEH9TQ0pAplPOlIiV92hfcgnFOADZypbjgbBT6Q==}
|
||||
[email protected].1:
|
||||
resolution: {integrity: sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g==}
|
||||
engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0}
|
||||
peerDependencies:
|
||||
'@napi-rs/canvas': ^1.0.13
|
||||
@@ -7050,8 +7054,8 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-CinAq1xWb0vR3twAv9evEU8cNWkXCb9kd5ePAHUKJBkOsUpR1wt/CvGdeca7vqumL1U5cSaeVQ6zZMxiJ3yWsg==}
|
||||
|
||||
[email protected].7:
|
||||
resolution: {integrity: sha512-mTJ9LAyBwHhO2T/PNaI0oWxmKl7FFuJ+ZEHKL1rRO69fWV1Y4qcsFB3gpuD2HfHvJCwvJq5ChibjjAGe0wc0vw==}
|
||||
[email protected].8:
|
||||
resolution: {integrity: sha512-7or7YqR3zXwHhiBGj40l9yODyQY146O+hXKaEAfQYQkcvHtMDdX95K96xr50qL9EjXScyYVJb1NIgVE8F0i5cA==}
|
||||
engines: {node: '>= 14'}
|
||||
hasBin: true
|
||||
|
||||
@@ -9493,7 +9497,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.4
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/lint': 6.9.7
|
||||
'@codemirror/lint': 6.9.8
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.15
|
||||
'@lezer/common': 1.5.5
|
||||
@@ -9538,7 +9542,7 @@ snapshots:
|
||||
'@lezer/lr': 1.4.10
|
||||
style-mod: 4.1.3
|
||||
|
||||
'@codemirror/[email protected].7':
|
||||
'@codemirror/[email protected].8':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.15
|
||||
@@ -9800,7 +9804,7 @@ snapshots:
|
||||
'@formatjs/bigdecimal': 0.2.10
|
||||
'@formatjs/intl-localematcher': 0.10.1
|
||||
|
||||
'@formatjs/[email protected].2':
|
||||
'@formatjs/[email protected].3':
|
||||
dependencies:
|
||||
'@formatjs/intl-localematcher': 0.10.1
|
||||
|
||||
@@ -9811,7 +9815,7 @@ snapshots:
|
||||
|
||||
'@formatjs/[email protected]': {}
|
||||
|
||||
'@formatjs/[email protected].2':
|
||||
'@formatjs/[email protected].3':
|
||||
dependencies:
|
||||
'@formatjs/intl-localematcher': 0.10.1
|
||||
|
||||
@@ -9828,17 +9832,17 @@ snapshots:
|
||||
dependencies:
|
||||
tslib: 2.9.1
|
||||
|
||||
'@formatjs/[email protected].3':
|
||||
'@formatjs/[email protected].4':
|
||||
dependencies:
|
||||
'@formatjs/bigdecimal': 0.2.10
|
||||
'@formatjs/intl-localematcher': 0.10.1
|
||||
|
||||
'@formatjs/[email protected].3':
|
||||
'@formatjs/[email protected].4':
|
||||
dependencies:
|
||||
'@formatjs/bigdecimal': 0.2.10
|
||||
'@formatjs/intl-localematcher': 0.10.1
|
||||
|
||||
'@formatjs/[email protected].2':
|
||||
'@formatjs/[email protected].3':
|
||||
dependencies:
|
||||
'@formatjs/intl-localematcher': 0.10.1
|
||||
|
||||
@@ -11693,7 +11697,7 @@ snapshots:
|
||||
obug: 3.0.0
|
||||
std-env: 4.3.0
|
||||
tinyrainbow: 3.2.0
|
||||
vitest: 5.1.0(@types/[email protected])(@vitest/[email protected])([email protected].0)([email protected](@types/[email protected])([email protected])([email protected]))
|
||||
vitest: 5.1.0(@types/[email protected])(@vitest/[email protected])([email protected].1)([email protected](@types/[email protected])([email protected])([email protected]))
|
||||
|
||||
'@vitest/[email protected]': {}
|
||||
|
||||
@@ -12333,11 +12337,12 @@ snapshots:
|
||||
dependencies:
|
||||
mime-db: 1.54.0
|
||||
|
||||
[email protected].1([email protected]):
|
||||
[email protected].2([email protected]):
|
||||
dependencies:
|
||||
bytes: 3.1.2
|
||||
compressible: 2.0.18
|
||||
debug: 2.6.9([email protected])
|
||||
destroy: 1.2.0
|
||||
negotiator: 0.6.4
|
||||
on-headers: 1.1.0
|
||||
safe-buffer: 5.2.1
|
||||
@@ -12528,6 +12533,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
@@ -13775,7 +13782,7 @@ snapshots:
|
||||
dependencies:
|
||||
argparse: 3.0.3
|
||||
|
||||
[email protected].0:
|
||||
[email protected].1:
|
||||
dependencies:
|
||||
'@exodus/bytes': 1.16.0
|
||||
bcp-47: 2.1.2
|
||||
@@ -15086,7 +15093,7 @@ snapshots:
|
||||
path-to-regexp: 3.3.0
|
||||
range-parser: 1.2.0
|
||||
|
||||
[email protected].7([email protected]):
|
||||
[email protected].8([email protected]):
|
||||
dependencies:
|
||||
'@zeit/schemas': 2.36.0
|
||||
ajv: 8.18.0
|
||||
@@ -15094,7 +15101,7 @@ snapshots:
|
||||
boxen: 7.0.0
|
||||
chalk: 5.0.1
|
||||
chalk-template: 0.4.0
|
||||
compression: 1.8.1([email protected])
|
||||
compression: 1.8.2([email protected])
|
||||
is-port-reachable: 4.0.0
|
||||
serve-handler: 6.1.7
|
||||
tinyclip: 0.1.15
|
||||
@@ -15928,7 +15935,7 @@ snapshots:
|
||||
terser: 5.50.0
|
||||
yaml: 2.9.1
|
||||
|
||||
[email protected](@types/[email protected])(@vitest/[email protected])([email protected].0)([email protected](@types/[email protected])([email protected])([email protected])):
|
||||
[email protected](@types/[email protected])(@vitest/[email protected])([email protected].1)([email protected](@types/[email protected])([email protected])([email protected])):
|
||||
dependencies:
|
||||
'@types/chai': 5.2.3
|
||||
'@vitest/mocker': 5.1.0([email protected](@types/[email protected])([email protected])([email protected]))
|
||||
@@ -15947,7 +15954,7 @@ snapshots:
|
||||
optionalDependencies:
|
||||
'@types/node': 24.19.2
|
||||
'@vitest/coverage-v8': 5.1.0([email protected])
|
||||
jsdom: 31.0.0
|
||||
jsdom: 31.0.1
|
||||
transitivePeerDependencies:
|
||||
- msw
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
interface EntityWithColorTemp {
|
||||
attributes?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const finiteRange = (
|
||||
min: unknown,
|
||||
max: unknown
|
||||
): { min: number; max: number } | undefined => {
|
||||
if (typeof min !== "number" || typeof max !== "number") {
|
||||
return undefined;
|
||||
}
|
||||
if (!Number.isFinite(min) || !Number.isFinite(max) || min > max) {
|
||||
return undefined;
|
||||
}
|
||||
return { min, max };
|
||||
};
|
||||
|
||||
/**
|
||||
* Kelvin bounds reported by the given entity states.
|
||||
*
|
||||
* Several lights use the overlap of their ranges, because one
|
||||
* `color_temp_kelvin` value is sent to every target. When the ranges do not
|
||||
* overlap, the result spans the widest range so it still has a valid min and
|
||||
* max. Entities without a finite range are ignored. Returns undefined when
|
||||
* nothing reports a range, so the caller keeps the selector min and max.
|
||||
*/
|
||||
export const kelvinRangeFromEntityStates = (
|
||||
states: Readonly<Record<string, EntityWithColorTemp | undefined>> | undefined
|
||||
): { min: number; max: number } | undefined => {
|
||||
if (!states) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const ranges: { min: number; max: number }[] = [];
|
||||
for (const state of Object.values(states)) {
|
||||
const range = finiteRange(
|
||||
state?.attributes?.min_color_temp_kelvin,
|
||||
state?.attributes?.max_color_temp_kelvin
|
||||
);
|
||||
if (range) {
|
||||
ranges.push(range);
|
||||
}
|
||||
}
|
||||
if (!ranges.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let min = Math.max(...ranges.map((range) => range.min));
|
||||
let max = Math.min(...ranges.map((range) => range.max));
|
||||
if (min > max) {
|
||||
min = Math.min(...ranges.map((range) => range.min));
|
||||
max = Math.max(...ranges.map((range) => range.max));
|
||||
}
|
||||
return { min, max };
|
||||
};
|
||||
@@ -3,6 +3,7 @@ const SWIPE_LOCKED_COMPONENTS = new Set([
|
||||
"ha-slider",
|
||||
"ha-control-switch",
|
||||
"ha-control-circular-slider",
|
||||
"ha-state-control-cover",
|
||||
"ha-hs-color-picker",
|
||||
"ha-map",
|
||||
// Charts pan and pinch-zoom on touch
|
||||
|
||||
@@ -4,16 +4,23 @@ import {
|
||||
mdiArrowDown,
|
||||
mdiArrowExpandHorizontal,
|
||||
mdiArrowUp,
|
||||
mdiDoorClosed,
|
||||
mdiDoorOpen,
|
||||
mdiGate,
|
||||
mdiGateOpen,
|
||||
} from "@mdi/js";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
|
||||
export const computeOpenIcon = (stateObj: HassEntity): string => {
|
||||
switch (stateObj.attributes.device_class) {
|
||||
case "awning":
|
||||
case "door":
|
||||
return mdiDoorOpen;
|
||||
case "gate":
|
||||
return mdiGateOpen;
|
||||
case "curtain":
|
||||
return mdiArrowExpandHorizontal;
|
||||
case "awning":
|
||||
return mdiArrowDown;
|
||||
default:
|
||||
return mdiArrowUp;
|
||||
}
|
||||
@@ -21,11 +28,14 @@ export const computeOpenIcon = (stateObj: HassEntity): string => {
|
||||
|
||||
export const computeCloseIcon = (stateObj: HassEntity): string => {
|
||||
switch (stateObj.attributes.device_class) {
|
||||
case "awning":
|
||||
case "door":
|
||||
return mdiDoorClosed;
|
||||
case "gate":
|
||||
return mdiGate;
|
||||
case "curtain":
|
||||
return mdiArrowCollapseHorizontal;
|
||||
case "awning":
|
||||
return mdiArrowUp;
|
||||
default:
|
||||
return mdiArrowDown;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ interface MinMaxFrame {
|
||||
maxPoint: Point;
|
||||
maxX: number;
|
||||
maxY: number;
|
||||
lastX: number;
|
||||
gapPoint: Point | undefined;
|
||||
}
|
||||
|
||||
@@ -68,6 +69,7 @@ function newFrame(
|
||||
maxPoint: point,
|
||||
maxX: x,
|
||||
maxY: y,
|
||||
lastX: x,
|
||||
gapPoint,
|
||||
};
|
||||
}
|
||||
@@ -174,6 +176,7 @@ export function downSampleLineData<
|
||||
if (!frame) {
|
||||
frames.set(frameIndex, newFrame(point, x, y, undefined));
|
||||
} else if (frame.hasValue) {
|
||||
frame.lastX = x;
|
||||
// Match the original strict-less / strict-greater comparisons so the
|
||||
// first occurrence wins on ties.
|
||||
if (y < frame.minY) {
|
||||
@@ -189,6 +192,7 @@ export function downSampleLineData<
|
||||
} else {
|
||||
// the frame held nothing but a marker so far
|
||||
frame.hasValue = true;
|
||||
frame.lastX = x;
|
||||
frame.minPoint = point;
|
||||
frame.minX = x;
|
||||
frame.minY = y;
|
||||
@@ -213,11 +217,8 @@ export function downSampleLineData<
|
||||
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.
|
||||
// The kept points are exactly min and max, so comparing against the
|
||||
// later of the two catches that without any work on the ingest path. A
|
||||
// marker-only frame compares against its own x and always passes.
|
||||
const lastValueX = frame.minX > frame.maxX ? frame.minX : frame.maxX;
|
||||
if (Number(getPointData(frame.gapPoint)[0]) >= lastValueX) {
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +76,18 @@ export interface NetworkData {
|
||||
|
||||
const PHYSICS_DISABLE_THRESHOLD = 512;
|
||||
|
||||
const LAYOUT_ANIMATION_THRESHOLD = 100;
|
||||
|
||||
// Every event of a change of the legend selection, each with the whole
|
||||
// selection
|
||||
const LEGEND_SELECT_EVENTS = [
|
||||
"legendselectchanged",
|
||||
"legendselected",
|
||||
"legendunselected",
|
||||
"legendselectall",
|
||||
"legendinverseselect",
|
||||
];
|
||||
|
||||
const SELECTED_NODE_MAX_ZOOM = 2;
|
||||
|
||||
// Keeps neighbors clear of the search field, buttons and legend
|
||||
@@ -124,8 +136,22 @@ export class HaNetworkGraph extends LitElement {
|
||||
|
||||
@state() private _showLabels = true;
|
||||
|
||||
// Not reactive: a new series option starts the layout again, so a drop only
|
||||
// reaches the option with the next render
|
||||
private _nodePositions: Record<string, { x: number; y: number }> = {};
|
||||
|
||||
// Dragged nodes stay where they are dropped, the force layout moves the others
|
||||
private _pinnedNodes: string[] = [];
|
||||
|
||||
// Names of the legend categories that are switched off. Not reactive: the
|
||||
// legend lays the graph out itself, only the layout animation threshold
|
||||
// needs a render
|
||||
private _hiddenCategories: string[] = [];
|
||||
|
||||
private _dragNode?: string;
|
||||
|
||||
private _dragMoved = false;
|
||||
|
||||
private _followSelectedNode = false;
|
||||
|
||||
private _followedChart?: EChartsType;
|
||||
@@ -170,12 +196,15 @@ export class HaNetworkGraph extends LitElement {
|
||||
this._showLabels,
|
||||
isMobile,
|
||||
hasHighlightedNodes,
|
||||
this.selectedNode
|
||||
this.selectedNode,
|
||||
this._nodePositions,
|
||||
this._pinnedNodes,
|
||||
this._fewVisibleNodes()
|
||||
)}
|
||||
.options=${this._createOptions(this.data?.categories)}
|
||||
height="100%"
|
||||
.extraComponents=${[GraphChart]}
|
||||
@chart-setup=${this._updateFollowing}
|
||||
@chart-setup=${this._handleChartSetup}
|
||||
>
|
||||
<slot name="search" slot="search"></slot>
|
||||
<slot name="button" slot="button"></slot>
|
||||
@@ -273,7 +302,10 @@ export class HaNetworkGraph extends LitElement {
|
||||
showLabels: boolean,
|
||||
isMobile: boolean,
|
||||
hasHighlightedNodes?: boolean,
|
||||
selectedNode?: string
|
||||
selectedNode?: string,
|
||||
nodePositions: Record<string, { x: number; y: number }> = {},
|
||||
pinnedNodes: string[] = [],
|
||||
fewVisibleNodes = true
|
||||
) => ({
|
||||
id: "network",
|
||||
type: "graph",
|
||||
@@ -311,14 +343,15 @@ export class HaNetworkGraph extends LitElement {
|
||||
repulsion: [400, 600],
|
||||
edgeLength: [200, 350],
|
||||
gravity: 0.05,
|
||||
layoutAnimation: !reducedMotion && data.nodes.length < 100,
|
||||
layoutAnimation: !reducedMotion && fewVisibleNodes,
|
||||
},
|
||||
edgeSymbol: ["none", "arrow"],
|
||||
edgeSymbolSize: 10,
|
||||
data: this._getSeriesData(
|
||||
data.nodes,
|
||||
data.links,
|
||||
this._nodePositions,
|
||||
nodePositions,
|
||||
pinnedNodes,
|
||||
selectedNode
|
||||
),
|
||||
links: data.links.map((link) => ({
|
||||
@@ -334,11 +367,25 @@ export class HaNetworkGraph extends LitElement {
|
||||
deepEqual
|
||||
);
|
||||
|
||||
// The legend leaves the nodes of hidden categories out of the layout
|
||||
private _fewVisibleNodes() {
|
||||
const hidden = this._hiddenCategories;
|
||||
const visibleNodes = hidden.length
|
||||
? this.data.nodes.filter(
|
||||
(node) =>
|
||||
node.category === undefined ||
|
||||
!hidden.includes(this.data.categories?.[node.category]?.name ?? "")
|
||||
).length
|
||||
: this.data.nodes.length;
|
||||
return visibleNodes < LAYOUT_ANIMATION_THRESHOLD;
|
||||
}
|
||||
|
||||
private _getSeriesData = memoizeOne(
|
||||
(
|
||||
nodes: NetworkNode[],
|
||||
links: NetworkLink[],
|
||||
nodePositions: Record<string, { x: number; y: number }>,
|
||||
pinnedNodes: string[],
|
||||
selectedNode?: string
|
||||
) =>
|
||||
this._getPositionedNodes(nodes, links, nodePositions).map((node) => {
|
||||
@@ -355,7 +402,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
? { ...node.itemStyle, borderWidth: 3 }
|
||||
: node.itemStyle || {},
|
||||
label: selected ? { ...node.label, fontWeight: "bold" } : node.label,
|
||||
fixed: node.fixed,
|
||||
fixed: node.fixed || pinnedNodes.includes(node.id),
|
||||
x: node.x,
|
||||
y: node.y,
|
||||
} as NonNullable<GraphSeriesOption["data"]>[number];
|
||||
@@ -515,6 +562,90 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
private _handleChartSetup() {
|
||||
const chart = this._baseChart?.chart;
|
||||
chart?.on("mousedown", this._handleNodeMouseDown);
|
||||
chart?.getZr().on("drag", this._handleDrag);
|
||||
chart?.getZr().on("dragend", this._handleDragEnd);
|
||||
for (const event of LEGEND_SELECT_EVENTS) {
|
||||
chart?.on(event, this._handleLegendChange);
|
||||
}
|
||||
const legend = (
|
||||
chart?.getOption() as
|
||||
{ legend?: { selected?: Record<string, boolean> }[] } | undefined
|
||||
)?.legend?.[0];
|
||||
this._setHiddenCategories(legend?.selected ?? {});
|
||||
// A recreated chart, e.g. after a theme change, lacks the drops since the
|
||||
// last render
|
||||
this.requestUpdate();
|
||||
this._updateFollowing();
|
||||
}
|
||||
|
||||
private _handleLegendChange = (params: unknown) => {
|
||||
const fewVisibleNodes = this._fewVisibleNodes();
|
||||
this._setHiddenCategories(
|
||||
(params as { selected: Record<string, boolean> }).selected
|
||||
);
|
||||
if (this._fewVisibleNodes() !== fewVisibleNodes) {
|
||||
// The new series option lays out again from where the nodes are now
|
||||
this._saveNodePositions();
|
||||
this.requestUpdate();
|
||||
}
|
||||
};
|
||||
|
||||
private _setHiddenCategories(selected: Record<string, boolean>) {
|
||||
this._hiddenCategories = Object.keys(selected).filter(
|
||||
(name) => !selected[name]
|
||||
);
|
||||
}
|
||||
|
||||
private _handleNodeMouseDown = (params: {
|
||||
dataType?: string;
|
||||
data?: unknown;
|
||||
}) => {
|
||||
this._dragNode =
|
||||
params.dataType === "node" ? (params.data as NetworkNode).id : undefined;
|
||||
this._dragMoved = false;
|
||||
};
|
||||
|
||||
private _handleDrag = () => {
|
||||
this._dragMoved = true;
|
||||
};
|
||||
|
||||
private _handleDragEnd = () => {
|
||||
const id = this._dragNode;
|
||||
const moved = this._dragMoved;
|
||||
this._dragNode = undefined;
|
||||
this._dragMoved = false;
|
||||
// A click also ends a drag, which releases a pinned node in ECharts
|
||||
if (!id || (!moved && !this._pinnedNodes.includes(id))) {
|
||||
return;
|
||||
}
|
||||
this._pinNodeInChart(id);
|
||||
if (!this._pinnedNodes.includes(id)) {
|
||||
this._pinnedNodes = [...this._pinnedNodes, id];
|
||||
}
|
||||
this._saveNodePositions();
|
||||
};
|
||||
|
||||
// A new series option would start the layout again, so the pin goes into
|
||||
// the running force layout, and into the item option that ECharts lays out
|
||||
// from again, e.g. on a legend change
|
||||
private _pinNodeInChart(id: string) {
|
||||
const series = this._getGraphSeries();
|
||||
const node = series?.getGraph().getNodeById(id);
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
series.forceLayout?.setFixed(node.dataIndex);
|
||||
const [x, y] = node.getLayout();
|
||||
Object.assign(series.getData().getRawDataItem(node.dataIndex), {
|
||||
fixed: true,
|
||||
x,
|
||||
y,
|
||||
});
|
||||
}
|
||||
|
||||
private _updateFollowing() {
|
||||
const chart = this._followSelectedNode ? this._baseChart?.chart : undefined;
|
||||
if (chart !== this._followedChart) {
|
||||
@@ -550,10 +681,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
if (!chart) {
|
||||
return;
|
||||
}
|
||||
const series: any = chart
|
||||
// @ts-ignore private method but no other way to get the graph positions
|
||||
.getModel()
|
||||
.getSeriesByIndex(0);
|
||||
const series = this._getGraphSeries(chart);
|
||||
const node = series?.getGraph().getNodeById(this.selectedNode);
|
||||
const position: number[] | undefined = node?.getLayout();
|
||||
if (!position) {
|
||||
@@ -614,6 +742,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
|
||||
private _togglePhysics() {
|
||||
this._saveNodePositions();
|
||||
this._pinnedNodes = [];
|
||||
this._physicsEnabled = !this._physicsEnabled;
|
||||
}
|
||||
|
||||
@@ -622,26 +751,30 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
|
||||
private _saveNodePositions() {
|
||||
const positions = {};
|
||||
if (this._baseChart?.chart) {
|
||||
this._baseChart.chart
|
||||
// @ts-ignore private method but no other way to get the graph positions
|
||||
.getModel()
|
||||
.getSeriesByIndex(0)
|
||||
.getGraph()
|
||||
.eachNode((node: any) => {
|
||||
const layout = node.getLayout();
|
||||
if (layout) {
|
||||
positions[node.id] = {
|
||||
x: layout[0],
|
||||
y: layout[1],
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
// Nodes that are not drawn keep their earlier position
|
||||
const positions = { ...this._nodePositions };
|
||||
this._getGraphSeries()
|
||||
?.getGraph()
|
||||
.eachNode((node: any) => {
|
||||
const layout = node.getLayout();
|
||||
if (layout) {
|
||||
positions[node.id] = {
|
||||
x: layout[0],
|
||||
y: layout[1],
|
||||
};
|
||||
}
|
||||
});
|
||||
this._nodePositions = positions;
|
||||
}
|
||||
|
||||
private _getGraphSeries(chart = this._baseChart?.chart): any {
|
||||
if (!chart || chart.isDisposed()) {
|
||||
return undefined;
|
||||
}
|
||||
// @ts-ignore private method but no other way to get the graph
|
||||
return chart.getModel().getSeriesByIndex(0);
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
|
||||
@@ -35,24 +35,27 @@ function computeTimelineStateColor(
|
||||
|
||||
const domain = computeDomain(stateObj.entity_id);
|
||||
|
||||
// Zone states for person/device_tracker don't have specific CSS color variables,
|
||||
// so they all fall back to the same --state-person-active-color.
|
||||
// Only use a custom CSS variable if explicitly defined (e.g. --state-person-kitchen-color),
|
||||
// otherwise return undefined to get unique colors from the generic color handler.
|
||||
if (
|
||||
// Zone states would all share --state-person-active-color, so only an
|
||||
// exact state variable may color them, like states of uncolored domains.
|
||||
const isZoneState =
|
||||
(domain === "person" || domain === "device_tracker") &&
|
||||
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state)
|
||||
) {
|
||||
return computeCssValue(
|
||||
`--state-${domain}-${slugify(state, "_")}-color`,
|
||||
computedStyles
|
||||
);
|
||||
}
|
||||
|
||||
const properties = stateColorProperties(stateObj, state);
|
||||
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state);
|
||||
const properties = isZoneState
|
||||
? undefined
|
||||
: stateColorProperties(stateObj, state);
|
||||
|
||||
if (!properties) {
|
||||
return undefined;
|
||||
const stateKey = slugify(state, "_");
|
||||
const deviceClass = stateObj.attributes.device_class;
|
||||
return computeCssValue(
|
||||
[
|
||||
...(deviceClass
|
||||
? [`--state-${domain}-${deviceClass}-${stateKey}-color`]
|
||||
: []),
|
||||
`--state-${domain}-${stateKey}-color`,
|
||||
],
|
||||
computedStyles
|
||||
);
|
||||
}
|
||||
|
||||
const rgb = computeCssValue(properties, computedStyles);
|
||||
|
||||
@@ -52,7 +52,7 @@ class StateInfo extends LitElement {
|
||||
${
|
||||
this.inDialog
|
||||
? html`<div class="time-ago">
|
||||
<ha-tooltip for="relative-time">
|
||||
<ha-tooltip for="relative-time" trigger="hover focus click">
|
||||
<div class="row">
|
||||
<span class="column-name">
|
||||
${this._localize(
|
||||
|
||||
@@ -33,6 +33,8 @@ class HaConfigNavigationList extends LitElement {
|
||||
return html`
|
||||
<ha-list-item-button
|
||||
.href=${externalApp ? undefined : page.path}
|
||||
.headline=${page.name}
|
||||
.supportingText=${this.hasSecondary ? page.description : undefined}
|
||||
@click=${externalApp ? this._handleExternalApp : undefined}
|
||||
>
|
||||
<ha-svg-icon
|
||||
@@ -43,14 +45,6 @@ class HaConfigNavigationList extends LitElement {
|
||||
.secondaryPath=${page.iconSecondaryPath}
|
||||
.viewBox=${page.iconViewBox}
|
||||
></ha-svg-icon>
|
||||
<span slot="headline">${page.name}</span>
|
||||
${
|
||||
this.hasSecondary
|
||||
? html`<span slot="supporting-text"
|
||||
>${page.description}</span
|
||||
>`
|
||||
: ""
|
||||
}
|
||||
${
|
||||
!this.narrow
|
||||
? html`<ha-icon-next slot="end"></ha-icon-next>`
|
||||
|
||||
@@ -387,7 +387,7 @@ export class HaControlCircularSlider extends LitElement {
|
||||
}
|
||||
|
||||
private _handleKeyDown(e: KeyboardEvent) {
|
||||
if (!A11Y_KEY_CODES.has(e.code)) return;
|
||||
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
|
||||
e.preventDefault();
|
||||
if (this._lastSlider) {
|
||||
this.shadowRoot?.getElementById(this._lastSlider)?.focus();
|
||||
@@ -439,7 +439,7 @@ export class HaControlCircularSlider extends LitElement {
|
||||
}
|
||||
|
||||
private _handleKeyUp(e: KeyboardEvent) {
|
||||
if (!A11Y_KEY_CODES.has(e.code)) return;
|
||||
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
|
||||
this._activeSlider = (e.currentTarget as any).id as ActiveSlider;
|
||||
e.preventDefault();
|
||||
fireEvent(this, `${this._activeSlider}-changing`, {
|
||||
|
||||
@@ -26,7 +26,11 @@ export class HaHelpTooltip extends LitElement {
|
||||
protected render(): TemplateResult {
|
||||
return html`
|
||||
<ha-svg-icon id="svg-icon" .path=${mdiHelpCircleOutline}></ha-svg-icon>
|
||||
<ha-tooltip for="svg-icon" .placement=${this.position}>
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="svg-icon"
|
||||
.placement=${this.position}
|
||||
>
|
||||
${this.label}
|
||||
</ha-tooltip>
|
||||
`;
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { nextRender } from "../common/util/render-status";
|
||||
import { fetchStreamUrl } from "../data/camera";
|
||||
import { apiContext, configContext, connectionContext } from "../data/context";
|
||||
import { isExternal } from "../data/external";
|
||||
import "./ha-alert";
|
||||
|
||||
type HlsLite = Omit<
|
||||
@@ -71,7 +72,7 @@ class HaHLSPlayer extends LitElement {
|
||||
|
||||
@state() private _errorIsFatal = false;
|
||||
|
||||
@state() private _url!: string;
|
||||
private _url?: string;
|
||||
|
||||
private _hlsPolyfillInstance?: HlsLite;
|
||||
|
||||
@@ -81,12 +82,22 @@ class HaHLSPlayer extends LitElement {
|
||||
|
||||
private _hiddenCleanupTimeout?: number;
|
||||
|
||||
// Increased on every clean up, so a start that is still waiting on the
|
||||
// network knows it is outdated
|
||||
private _cleanUpCount = 0;
|
||||
|
||||
private _handleVisibilityChange = () => {
|
||||
if (document.pictureInPictureElement) {
|
||||
// video is playing in picture-in-picture mode, don't do anything
|
||||
return;
|
||||
}
|
||||
if (document.hidden) {
|
||||
if (isExternal) {
|
||||
// The companion apps pause JavaScript timers while in the background,
|
||||
// so a delayed clean up would not run until the app is opened again
|
||||
this._cleanUp();
|
||||
return;
|
||||
}
|
||||
this._hiddenCleanupTimeout = window.setTimeout(() => {
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
this._cleanUp();
|
||||
@@ -96,8 +107,7 @@ class HaHLSPlayer extends LitElement {
|
||||
clearTimeout(this._hiddenCleanupTimeout);
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
} else {
|
||||
this._resetError();
|
||||
this._startHls();
|
||||
this._restartHls();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -105,8 +115,7 @@ class HaHLSPlayer extends LitElement {
|
||||
super.connectedCallback();
|
||||
HaHLSPlayer.streamCount += 1;
|
||||
if (this.hasUpdated) {
|
||||
this._resetError();
|
||||
this._startHls();
|
||||
this._restartHls();
|
||||
}
|
||||
document.addEventListener("visibilitychange", this._handleVisibilityChange);
|
||||
}
|
||||
@@ -171,9 +180,22 @@ class HaHLSPlayer extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts the stream again, replacing a start that is still pending. */
|
||||
private _restartHls() {
|
||||
if (this.entityid) {
|
||||
// The stream URL stops working once the stream has been idle for a while
|
||||
this._getStreamUrlFromEntityId();
|
||||
return;
|
||||
}
|
||||
this._cleanUp();
|
||||
this._resetError();
|
||||
this._startHls();
|
||||
}
|
||||
|
||||
private async _getStreamUrlFromEntityId(): Promise<void> {
|
||||
this._cleanUp();
|
||||
this._resetError();
|
||||
this._url = undefined;
|
||||
|
||||
if (!isComponentLoaded(this._config.config, "stream")) {
|
||||
this._setFatalError("Streaming component is not loaded.");
|
||||
@@ -184,12 +206,18 @@ class HaHLSPlayer extends LitElement {
|
||||
if (!entityId) {
|
||||
return;
|
||||
}
|
||||
const cleanUpCount = this._cleanUpCount;
|
||||
try {
|
||||
const { url } = await fetchStreamUrl(
|
||||
{ callWS: this._api.callWS, hassUrl: this._connection.hassUrl },
|
||||
entityId
|
||||
);
|
||||
|
||||
if (cleanUpCount !== this._cleanUpCount) {
|
||||
// Removed, hidden or switched camera while fetching
|
||||
return;
|
||||
}
|
||||
|
||||
this._url = this._connection.hassUrl(url);
|
||||
this._cleanUp();
|
||||
this._resetError();
|
||||
@@ -199,8 +227,8 @@ class HaHLSPlayer extends LitElement {
|
||||
// eslint-disable-next-line
|
||||
console.error(err);
|
||||
|
||||
if (!this.isConnected || entityId !== this.entityid) {
|
||||
// Removed or switched camera while fetching, the result is outdated
|
||||
if (cleanUpCount !== this._cleanUpCount || entityId !== this.entityid) {
|
||||
// Removed, hidden or switched camera while fetching
|
||||
return;
|
||||
}
|
||||
fireEvent(this, "streams", { hasAudio: false, hasVideo: false });
|
||||
@@ -208,13 +236,18 @@ class HaHLSPlayer extends LitElement {
|
||||
}
|
||||
|
||||
private async _startHls(): Promise<void> {
|
||||
const masterPlaylistPromise = fetch(this._url);
|
||||
const url = this._url;
|
||||
if (!url) {
|
||||
return;
|
||||
}
|
||||
const cleanUpCount = this._cleanUpCount;
|
||||
const masterPlaylistPromise = fetch(url);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
const Hls: typeof HlsType = (await import("hls.js/dist/hls.light.mjs"))
|
||||
.default;
|
||||
|
||||
if (!this.isConnected) {
|
||||
if (cleanUpCount !== this._cleanUpCount || !this.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -236,7 +269,7 @@ class HaHLSPlayer extends LitElement {
|
||||
this.allowExoPlayer && this._config.auth.external?.config.hasExoPlayer;
|
||||
const masterPlaylist = await (await masterPlaylistPromise).text();
|
||||
|
||||
if (!this.isConnected) {
|
||||
if (cleanUpCount !== this._cleanUpCount || !this.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -252,9 +285,9 @@ class HaHLSPlayer extends LitElement {
|
||||
let playlist_url: string;
|
||||
if (match !== null && matchTwice === null) {
|
||||
// Only send the regular playlist url if we match exactly once
|
||||
playlist_url = new URL(match[3], this._url).href;
|
||||
playlist_url = new URL(match[3], url).href;
|
||||
} else {
|
||||
playlist_url = this._url;
|
||||
playlist_url = url;
|
||||
}
|
||||
|
||||
const codecs = match ? `${match[1]},${match[2]}` : undefined;
|
||||
@@ -392,12 +425,17 @@ class HaHLSPlayer extends LitElement {
|
||||
|
||||
private async _renderHLSNative(videoEl: HTMLVideoElement, url: string) {
|
||||
videoEl.src = url;
|
||||
videoEl.addEventListener("loadedmetadata", () => {
|
||||
videoEl.play();
|
||||
});
|
||||
videoEl.addEventListener(
|
||||
"loadedmetadata",
|
||||
() => {
|
||||
videoEl.play();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
}
|
||||
|
||||
private _cleanUp() {
|
||||
this._cleanUpCount++;
|
||||
if (this._hlsPolyfillInstance) {
|
||||
this._hlsPolyfillInstance.destroy();
|
||||
this._hlsPolyfillInstance = undefined;
|
||||
|
||||
@@ -171,6 +171,16 @@ export class HaRipple extends LitElement {
|
||||
return;
|
||||
}
|
||||
|
||||
// A touch long press opens the context menu while the press continues,
|
||||
// e.g. for a hold action. touchend or pointercancel ends it instead.
|
||||
if (
|
||||
ev.type === "contextmenu" &&
|
||||
this._startEvent &&
|
||||
isTouch(this._startEvent)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (ev.type === "contextmenu" || ev.type === "touchend") {
|
||||
this._endPress();
|
||||
|
||||
@@ -193,13 +203,25 @@ export class HaRipple extends LitElement {
|
||||
break;
|
||||
case "pointerenter":
|
||||
this._hovered = true;
|
||||
|
||||
if (this._state === "waiting-for-click") {
|
||||
if (ev.buttons === 1) {
|
||||
// Back on the control with the press still held
|
||||
this._pressed = true;
|
||||
} else {
|
||||
// The press was released off the control, so no click follows
|
||||
this._endPress();
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case "pointerleave":
|
||||
this._hovered = false;
|
||||
|
||||
// Release a held mouse or pen press that moves off the control
|
||||
if (this._state !== "inactive") {
|
||||
this._endPress();
|
||||
// A mouse or pen press that moves off the control still clicks if it
|
||||
// is released back on it, so only hide the press until it returns
|
||||
if (this._state === "waiting-for-click") {
|
||||
this._pressed = false;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { html, LitElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { fireEvent, type HASSDomEvent } from "../../common/dom/fire_event";
|
||||
import type { ColorTempSelector } from "../../data/selector";
|
||||
import "../ha-labeled-slider";
|
||||
import { generateColorTemperatureGradient } from "../../dialogs/more-info/components/lights/light-color-temp-picker";
|
||||
import { kelvinRangeFromEntityStates } from "../../common/color/color-temp-selector-range";
|
||||
import {
|
||||
DEFAULT_MAX_KELVIN,
|
||||
DEFAULT_MIN_KELVIN,
|
||||
mired2kelvin,
|
||||
} from "../../common/color/convert-light-color";
|
||||
import { consumeEntityStates } from "../../common/decorators/consume-context-entry";
|
||||
import { fireEvent, type HASSDomEvent } from "../../common/dom/fire_event";
|
||||
import type { ColorTempSelector } from "../../data/selector";
|
||||
import { generateColorTemperatureGradient } from "../../dialogs/more-info/components/lights/light-color-temp-picker";
|
||||
import "../ha-labeled-slider";
|
||||
|
||||
@customElement("ha-selector-color_temp")
|
||||
export class HaColorTempSelector extends LitElement {
|
||||
@property({ attribute: false }) public selector!: ColorTempSelector;
|
||||
|
||||
@property() public value?: string;
|
||||
@property() public value?: string | number;
|
||||
|
||||
@property() public label?: string;
|
||||
|
||||
@@ -26,27 +29,16 @@ export class HaColorTempSelector extends LitElement {
|
||||
|
||||
@property({ type: Boolean }) public required = true;
|
||||
|
||||
protected render() {
|
||||
let min: number;
|
||||
let max: number;
|
||||
@property({ attribute: false }) public context?: {
|
||||
filter_entity?: string | string[];
|
||||
};
|
||||
|
||||
switch (this.selector.color_temp?.unit) {
|
||||
case "kelvin":
|
||||
min = this.selector.color_temp?.min ?? DEFAULT_MIN_KELVIN;
|
||||
max = this.selector.color_temp?.max ?? DEFAULT_MAX_KELVIN;
|
||||
break;
|
||||
case "mired":
|
||||
default:
|
||||
min =
|
||||
this.selector.color_temp?.min ??
|
||||
this.selector.color_temp?.min_mireds ??
|
||||
153;
|
||||
max =
|
||||
this.selector.color_temp?.max ??
|
||||
this.selector.color_temp?.max_mireds ??
|
||||
500;
|
||||
break;
|
||||
}
|
||||
@state()
|
||||
@consumeEntityStates({ entityIdPath: ["context", "filter_entity"] })
|
||||
private _filterEntityStates?: Record<string, HassEntity>;
|
||||
|
||||
protected render() {
|
||||
const { min, max } = this._bounds();
|
||||
const gradient = this._generateTemperatureGradient(
|
||||
this.selector.color_temp?.unit ?? "mired",
|
||||
min,
|
||||
@@ -72,6 +64,30 @@ export class HaColorTempSelector extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private _bounds(): { min: number; max: number } {
|
||||
switch (this.selector.color_temp?.unit) {
|
||||
case "kelvin":
|
||||
return (
|
||||
kelvinRangeFromEntityStates(this._filterEntityStates) ?? {
|
||||
min: this.selector.color_temp?.min ?? DEFAULT_MIN_KELVIN,
|
||||
max: this.selector.color_temp?.max ?? DEFAULT_MAX_KELVIN,
|
||||
}
|
||||
);
|
||||
case "mired":
|
||||
default:
|
||||
return {
|
||||
min:
|
||||
this.selector.color_temp?.min ??
|
||||
this.selector.color_temp?.min_mireds ??
|
||||
153,
|
||||
max:
|
||||
this.selector.color_temp?.max ??
|
||||
this.selector.color_temp?.max_mireds ??
|
||||
500,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private _generateTemperatureGradient = memoizeOne(
|
||||
(unit: "kelvin" | "mired", min: number, max: number) => {
|
||||
let gradient;
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type WebRtcOfferEvent,
|
||||
} from "../data/camera";
|
||||
import { apiContext, connectionContext } from "../data/context";
|
||||
import { isExternal } from "../data/external";
|
||||
import "./ha-alert";
|
||||
import "./ha-spinner";
|
||||
import { showToast } from "../util/toast";
|
||||
@@ -236,6 +237,12 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
return;
|
||||
}
|
||||
if (document.hidden) {
|
||||
if (isExternal) {
|
||||
// The companion apps pause JavaScript timers while in the background,
|
||||
// so a delayed clean up would not run until the app is opened again
|
||||
this._cleanUp();
|
||||
return;
|
||||
}
|
||||
this._hiddenCleanupTimeout = window.setTimeout(() => {
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
this._cleanUp();
|
||||
|
||||
@@ -22,11 +22,65 @@ const SMALL_THUMBNAIL_THRESHOLD = 16;
|
||||
const isSvgUrl = (url: string): boolean =>
|
||||
/\.svg(\?|#|$)/i.test(url) || url.startsWith("data:image/svg+xml");
|
||||
|
||||
// Local thumbnails can be slow to generate, for example when the integration
|
||||
// extracts them from a recording on a camera. Without a limit they take all of
|
||||
// the browser's connections to Home Assistant (6 for HTTP/1.1), and requests
|
||||
// such as starting media playback wait until all queued thumbnails are loaded.
|
||||
const MAX_PARALLEL_LOCAL_THUMBNAILS = 4;
|
||||
let activeLocalThumbnails = 0;
|
||||
const localThumbnailQueue: (() => void)[] = [];
|
||||
|
||||
const acquireLocalThumbnailSlot = (signal: AbortSignal): Promise<void> => {
|
||||
if (signal.aborted) {
|
||||
return Promise.reject(signal.reason);
|
||||
}
|
||||
if (activeLocalThumbnails < MAX_PARALLEL_LOCAL_THUMBNAILS) {
|
||||
activeLocalThumbnails++;
|
||||
return Promise.resolve();
|
||||
}
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const start = () => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
activeLocalThumbnails++;
|
||||
resolve();
|
||||
};
|
||||
const onAbort = () => {
|
||||
const index = localThumbnailQueue.indexOf(start);
|
||||
if (index !== -1) {
|
||||
localThumbnailQueue.splice(index, 1);
|
||||
}
|
||||
reject(signal.reason);
|
||||
};
|
||||
localThumbnailQueue.push(start);
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
};
|
||||
|
||||
const releaseLocalThumbnailSlot = (): void => {
|
||||
activeLocalThumbnails--;
|
||||
localThumbnailQueue.shift()?.();
|
||||
};
|
||||
|
||||
const fetchLocalThumbnail = async (
|
||||
fetchWithAuth: HomeAssistantApi["fetchWithAuth"],
|
||||
thumbnailUrl: string,
|
||||
signal: AbortSignal
|
||||
): Promise<Blob> => {
|
||||
await acquireLocalThumbnailSlot(signal);
|
||||
try {
|
||||
const response = await fetchWithAuth(thumbnailUrl, { signal });
|
||||
return await response.blob();
|
||||
} finally {
|
||||
releaseLocalThumbnailSlot();
|
||||
}
|
||||
};
|
||||
|
||||
const resolveThumbnailURL = (
|
||||
thumbnailUrl: string,
|
||||
darkMode: boolean | undefined,
|
||||
hassUrl: string | undefined,
|
||||
fetchWithAuth: HomeAssistantApi["fetchWithAuth"]
|
||||
fetchWithAuth: HomeAssistantApi["fetchWithAuth"],
|
||||
signal: AbortSignal
|
||||
): Promise<string> => {
|
||||
if (isBrandUrl(thumbnailUrl)) {
|
||||
return Promise.resolve(
|
||||
@@ -42,18 +96,16 @@ const resolveThumbnailURL = (
|
||||
}
|
||||
if (thumbnailUrl.startsWith("/")) {
|
||||
// Local thumbnails require authentication; fetch and inline as base64.
|
||||
return fetchWithAuth(thumbnailUrl)
|
||||
.then((response) => response.blob())
|
||||
.then(
|
||||
(blob) =>
|
||||
new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () =>
|
||||
resolve(typeof reader.result === "string" ? reader.result : "");
|
||||
reader.onerror = (e) => reject(e);
|
||||
reader.readAsDataURL(blob);
|
||||
})
|
||||
);
|
||||
return fetchLocalThumbnail(fetchWithAuth, thumbnailUrl, signal).then(
|
||||
(blob) =>
|
||||
new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () =>
|
||||
resolve(typeof reader.result === "string" ? reader.result : "");
|
||||
reader.onerror = (e) => reject(e);
|
||||
reader.readAsDataURL(blob);
|
||||
})
|
||||
);
|
||||
}
|
||||
return Promise.resolve(thumbnailUrl);
|
||||
};
|
||||
@@ -85,6 +137,28 @@ export class HaMediaBrowserThumbnail extends LitElement {
|
||||
|
||||
@state() private _brand = false;
|
||||
|
||||
private _abortController?: AbortController;
|
||||
|
||||
public connectedCallback(): void {
|
||||
super.connectedCallback();
|
||||
// Resume a thumbnail which was aborted when this element was disconnected
|
||||
if (this.hasUpdated && this.url && !this._resolvedUrl) {
|
||||
this._resolve();
|
||||
}
|
||||
}
|
||||
|
||||
public disconnectedCallback(): void {
|
||||
super.disconnectedCallback();
|
||||
// Do not keep loading thumbnails which are no longer shown
|
||||
if (this._abortController) {
|
||||
this._abortController.abort();
|
||||
this._abortController = undefined;
|
||||
// A shown image can belong to a previous url, clear it so
|
||||
// connectedCallback restarts loading the current url.
|
||||
this._resolvedUrl = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues): void {
|
||||
super.willUpdate(changedProps);
|
||||
if (
|
||||
@@ -97,6 +171,8 @@ export class HaMediaBrowserThumbnail extends LitElement {
|
||||
}
|
||||
|
||||
private async _resolve(): Promise<void> {
|
||||
this._abortController?.abort();
|
||||
this._abortController = undefined;
|
||||
this._small = false;
|
||||
this._brand = !!this.url && isBrandUrl(this.url);
|
||||
if (!this.url) {
|
||||
@@ -104,18 +180,28 @@ export class HaMediaBrowserThumbnail extends LitElement {
|
||||
return;
|
||||
}
|
||||
const requested = this.url;
|
||||
const abortController = new AbortController();
|
||||
this._abortController = abortController;
|
||||
try {
|
||||
const resolved = await resolveThumbnailURL(
|
||||
requested,
|
||||
this._darkMode,
|
||||
this._hassUrl,
|
||||
this._api.fetchWithAuth
|
||||
this._api.fetchWithAuth,
|
||||
abortController.signal
|
||||
);
|
||||
if (requested !== this.url) return;
|
||||
this._resolvedUrl = resolved;
|
||||
this._probeSize(resolved);
|
||||
} catch (_err) {
|
||||
// Aborted when the url changed or this element was disconnected,
|
||||
// which already restarted or reset the resolution.
|
||||
if (abortController.signal.aborted) return;
|
||||
if (requested === this.url) this._resolvedUrl = undefined;
|
||||
} finally {
|
||||
if (this._abortController === abortController) {
|
||||
this._abortController = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+123
-25
@@ -2,16 +2,37 @@ import type {
|
||||
HassEntityAttributeBase,
|
||||
HassEntityBase,
|
||||
} from "home-assistant-js-websocket";
|
||||
import { stateActive } from "../common/entity/state_active";
|
||||
import { supportsFeature } from "../common/entity/supports-feature";
|
||||
import type { HomeAssistantFormatters } from "../types";
|
||||
import { UNAVAILABLE } from "./entity/entity";
|
||||
import { UNAVAILABLE, UNKNOWN } from "./entity/entity";
|
||||
import { CoverEntityFeature } from "./feature/cover_entity_feature";
|
||||
|
||||
export { CoverEntityFeature };
|
||||
|
||||
export const DEFAULT_COVER_FAVORITE_POSITIONS = [0, 25, 75, 100];
|
||||
|
||||
export type CoverControlMode = "position" | "tilt";
|
||||
|
||||
export type CoverAction = "open" | "close" | "stop";
|
||||
|
||||
export type CoverCommand =
|
||||
| { mode: CoverControlMode; action: CoverAction }
|
||||
| { mode: CoverControlMode; action: "set"; value: number };
|
||||
|
||||
export interface CoverRequest {
|
||||
mode: CoverControlMode;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export interface CoverSwipe {
|
||||
action: "open" | "close";
|
||||
passedHalfway: boolean;
|
||||
}
|
||||
|
||||
export interface CoverDrag {
|
||||
value: number;
|
||||
swipe?: CoverSwipe;
|
||||
}
|
||||
|
||||
export const coverSupportsPosition = (stateObj: CoverEntity) =>
|
||||
supportsFeature(stateObj, CoverEntityFeature.SET_POSITION);
|
||||
|
||||
@@ -21,11 +42,79 @@ export const coverSupportsTiltPosition = (stateObj: CoverEntity) =>
|
||||
export const coverSupportsAnyPosition = (stateObj: CoverEntity) =>
|
||||
coverSupportsPosition(stateObj) || coverSupportsTiltPosition(stateObj);
|
||||
|
||||
export function isFullyOpen(stateObj: CoverEntity) {
|
||||
if (stateObj.attributes.current_position !== undefined) {
|
||||
return stateObj.attributes.current_position === 100;
|
||||
export const coverSupportsSetValue = (
|
||||
stateObj: CoverEntity,
|
||||
mode: CoverControlMode
|
||||
) =>
|
||||
mode === "tilt"
|
||||
? coverSupportsTiltPosition(stateObj)
|
||||
: coverSupportsPosition(stateObj);
|
||||
|
||||
const POSITION_FEATURES = [
|
||||
CoverEntityFeature.OPEN,
|
||||
CoverEntityFeature.CLOSE,
|
||||
CoverEntityFeature.STOP,
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
];
|
||||
|
||||
const TILT_FEATURES = [
|
||||
CoverEntityFeature.OPEN_TILT,
|
||||
CoverEntityFeature.CLOSE_TILT,
|
||||
CoverEntityFeature.STOP_TILT,
|
||||
CoverEntityFeature.SET_TILT_POSITION,
|
||||
];
|
||||
|
||||
export const coverHasPositionControls = (stateObj: CoverEntity) =>
|
||||
POSITION_FEATURES.some((feature) => supportsFeature(stateObj, feature));
|
||||
|
||||
export const coverHasTiltControls = (stateObj: CoverEntity) =>
|
||||
TILT_FEATURES.some((feature) => supportsFeature(stateObj, feature));
|
||||
|
||||
export const defaultCoverMode = (stateObj: CoverEntity): CoverControlMode =>
|
||||
coverHasTiltControls(stateObj) && !coverHasPositionControls(stateObj)
|
||||
? "tilt"
|
||||
: "position";
|
||||
|
||||
export const coverModeAttribute = (mode: CoverControlMode) =>
|
||||
mode === "tilt" ? "current_tilt_position" : "current_position";
|
||||
|
||||
const COVER_SERVICES: Record<
|
||||
CoverControlMode,
|
||||
Record<CoverCommand["action"], string>
|
||||
> = {
|
||||
position: {
|
||||
open: "open_cover",
|
||||
close: "close_cover",
|
||||
stop: "stop_cover",
|
||||
set: "set_cover_position",
|
||||
},
|
||||
tilt: {
|
||||
open: "open_cover_tilt",
|
||||
close: "close_cover_tilt",
|
||||
stop: "stop_cover_tilt",
|
||||
set: "set_cover_tilt_position",
|
||||
},
|
||||
};
|
||||
|
||||
export const coverCommandService = ({ mode, action }: CoverCommand) =>
|
||||
COVER_SERVICES[mode][action];
|
||||
|
||||
export const coverCommandData = (
|
||||
stateObj: CoverEntity,
|
||||
command: CoverCommand
|
||||
): Record<string, unknown> => {
|
||||
const data = { entity_id: stateObj.entity_id };
|
||||
if (command.action !== "set") {
|
||||
return data;
|
||||
}
|
||||
return stateObj.state === "open";
|
||||
if (command.mode === "tilt") {
|
||||
return { ...data, tilt_position: command.value };
|
||||
}
|
||||
return { ...data, position: command.value };
|
||||
};
|
||||
|
||||
export function isFullyOpen(stateObj: CoverEntity) {
|
||||
return stateObj.attributes.current_position === 100;
|
||||
}
|
||||
|
||||
export function isFullyClosed(stateObj: CoverEntity) {
|
||||
@@ -51,6 +140,10 @@ export function isClosing(stateObj: CoverEntity) {
|
||||
return stateObj.state === "closing";
|
||||
}
|
||||
|
||||
export function isMoving(stateObj: CoverEntity) {
|
||||
return isOpening(stateObj) || isClosing(stateObj);
|
||||
}
|
||||
|
||||
export function isTiltOnly(stateObj: CoverEntity) {
|
||||
const supportsCover =
|
||||
supportsFeature(stateObj, CoverEntityFeature.OPEN) ||
|
||||
@@ -113,24 +206,29 @@ export interface CoverEntity extends HassEntityBase {
|
||||
attributes: CoverEntityAttributes;
|
||||
}
|
||||
|
||||
export function computeCoverPositionStateDisplay(
|
||||
export const coverCurrentValue = (
|
||||
stateObj: CoverEntity,
|
||||
formatEntityAttributeValue: HomeAssistantFormatters["formatEntityAttributeValue"],
|
||||
position?: number
|
||||
) {
|
||||
const statePosition = stateActive(stateObj)
|
||||
? (stateObj.attributes.current_position ??
|
||||
stateObj.attributes.current_tilt_position)
|
||||
: undefined;
|
||||
mode: CoverControlMode
|
||||
): number | undefined => {
|
||||
if (mode === "tilt") {
|
||||
return stateObj.attributes.current_tilt_position ?? undefined;
|
||||
}
|
||||
const position = stateObj.attributes.current_position;
|
||||
if (
|
||||
position != null ||
|
||||
supportsFeature(stateObj, CoverEntityFeature.SET_POSITION)
|
||||
) {
|
||||
return position ?? undefined;
|
||||
}
|
||||
if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
|
||||
return undefined;
|
||||
}
|
||||
return stateObj.state === "closed" || stateObj.state === "opening" ? 0 : 100;
|
||||
};
|
||||
|
||||
const currentPosition = position ?? statePosition;
|
||||
|
||||
return currentPosition && currentPosition !== 100
|
||||
? formatEntityAttributeValue(
|
||||
stateObj,
|
||||
// Always use position as it's the same formatting as tilt position
|
||||
"current_position",
|
||||
Math.round(currentPosition)
|
||||
)
|
||||
: "";
|
||||
declare global {
|
||||
interface HASSDomEvents {
|
||||
"cover-command": CoverCommand;
|
||||
"cover-drag-changed": { drag?: CoverDrag };
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,6 @@ export const emptyGridSourceEnergyPreference =
|
||||
number_energy_price: null,
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
cost_adjustment_day: 0,
|
||||
});
|
||||
|
||||
export const emptySolarEnergyPreference =
|
||||
@@ -162,7 +161,6 @@ export interface GridSourceTypeEnergyPreference {
|
||||
stat_rate?: string; // always available if power_config is set
|
||||
power_config?: PowerConfig;
|
||||
|
||||
cost_adjustment_day: number;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import type {
|
||||
HassEntities,
|
||||
HassEntity,
|
||||
HassEntityAttributeBase,
|
||||
HassEntityBase,
|
||||
} from "home-assistant-js-websocket";
|
||||
import { computeDomain } from "../common/entity/compute_domain";
|
||||
import type { ExtEntityRegistryEntry } from "./entity/entity_registry";
|
||||
|
||||
interface GroupEntityAttributes extends HassEntityAttributeBase {
|
||||
entity_id: string[];
|
||||
@@ -24,3 +27,55 @@ export const computeGroupDomain = (
|
||||
];
|
||||
return uniqueDomains.length === 1 ? uniqueDomains[0] : undefined;
|
||||
};
|
||||
|
||||
/** Member entity IDs of a group, or undefined if it is not a group. */
|
||||
export const computeGroupMemberIds = (
|
||||
stateObj: HassEntity,
|
||||
entry?: Pick<ExtEntityRegistryEntry, "capabilities"> | null
|
||||
): string[] | undefined => {
|
||||
const ids =
|
||||
entry?.capabilities?.group_entities ??
|
||||
stateObj.attributes.group_entities ??
|
||||
stateObj.attributes.entity_id;
|
||||
return Array.isArray(ids) ? ids : undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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
|
||||
* hiding its bulbs doesn't read "All off".
|
||||
*/
|
||||
export const filterGroupsWithListedMembers = (
|
||||
entityIds: string[],
|
||||
states: HassEntities
|
||||
): string[] => {
|
||||
const listed = new Set(entityIds);
|
||||
const hasListedDescendant = (groupId: string): boolean => {
|
||||
const seen = new Set([groupId]);
|
||||
const queue = [groupId];
|
||||
while (queue.length) {
|
||||
const stateObj = states[queue.shift()!];
|
||||
for (const memberId of (stateObj && computeGroupMemberIds(stateObj)) ??
|
||||
[]) {
|
||||
if (seen.has(memberId)) {
|
||||
continue;
|
||||
}
|
||||
if (listed.has(memberId)) {
|
||||
return true;
|
||||
}
|
||||
seen.add(memberId);
|
||||
queue.push(memberId);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
return entityIds.filter((entityId) => {
|
||||
if (!hasListedDescendant(entityId)) {
|
||||
return true;
|
||||
}
|
||||
// A dropped group no longer counts as listed, so of two groups that
|
||||
// contain each other one still stays.
|
||||
listed.delete(entityId);
|
||||
return false;
|
||||
});
|
||||
};
|
||||
+47
-1
@@ -1,7 +1,7 @@
|
||||
import type { Connection } from "home-assistant-js-websocket";
|
||||
import { DEFAULT_ENTITY_NAME } from "../common/entity/entity_name_config";
|
||||
import type { HaDurationData } from "../components/ha-duration-input";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import type { HomeAssistant, HomeAssistantApi } from "../types";
|
||||
import { firstWeekday } from "../common/datetime/first_weekday";
|
||||
|
||||
export interface RecorderInfo {
|
||||
@@ -163,6 +163,52 @@ export const getRecorderInfo = (conn: Connection) =>
|
||||
type: "recorder/info",
|
||||
});
|
||||
|
||||
export interface RecorderTableUsage {
|
||||
table: string;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
// Byte figures are null when the database cannot report table sizes.
|
||||
export interface RecorderEntityUsage {
|
||||
// null collects rows without a known entity
|
||||
entity_id: string | null;
|
||||
states: number;
|
||||
states_bytes: number | null;
|
||||
attributes_bytes: number | null;
|
||||
}
|
||||
|
||||
export interface RecorderStatisticUsage {
|
||||
// null collects rows without a known statistic
|
||||
statistic_id: string | null;
|
||||
source: string | null;
|
||||
statistics: number;
|
||||
statistics_short_term: number;
|
||||
statistics_bytes: number | null;
|
||||
statistics_short_term_bytes: number | null;
|
||||
}
|
||||
|
||||
export interface RecorderDatabaseUsage {
|
||||
generated_at: string;
|
||||
duration: number;
|
||||
total_bytes: number;
|
||||
free_bytes: number | null;
|
||||
// SQLite write-ahead log, not part of total_bytes
|
||||
wal_bytes: number | null;
|
||||
tables: RecorderTableUsage[] | null;
|
||||
entities: RecorderEntityUsage[];
|
||||
statistics: RecorderStatisticUsage[];
|
||||
}
|
||||
|
||||
// Without refresh this returns the last report of the past hour, or null.
|
||||
export const fetchRecorderDatabaseUsage = (
|
||||
api: Pick<HomeAssistantApi, "callWS">,
|
||||
refresh = false
|
||||
) =>
|
||||
api.callWS<RecorderDatabaseUsage | null>({
|
||||
type: "recorder/database_usage",
|
||||
refresh,
|
||||
});
|
||||
|
||||
export type EntityRecordingDisabler = "user";
|
||||
|
||||
export interface RecorderEntityOptions {
|
||||
|
||||
@@ -185,6 +185,11 @@ export interface ColorRGBSelector {
|
||||
export interface ColorTempSelector {
|
||||
color_temp: {
|
||||
unit?: "kelvin" | "mired";
|
||||
/**
|
||||
* Slider bounds. For `unit: "kelvin"` these apply only when no entity in
|
||||
* the selector context `filter_entity` reports `min_color_temp_kelvin`
|
||||
* and `max_color_temp_kelvin`.
|
||||
*/
|
||||
min?: number;
|
||||
max?: number;
|
||||
min_mireds?: number;
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { mdiArrowBottomLeft, mdiArrowTopRight, mdiStop } from "@mdi/js";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import {
|
||||
computeCloseIcon,
|
||||
computeOpenIcon,
|
||||
} from "../../../../common/entity/cover_icon";
|
||||
import { supportsFeature } from "../../../../common/entity/supports-feature";
|
||||
import type {
|
||||
LocalizeFunc,
|
||||
LocalizeKeys,
|
||||
} from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-control-button";
|
||||
import "../../../../components/ha-svg-icon";
|
||||
import type {
|
||||
CoverAction,
|
||||
CoverControlMode,
|
||||
CoverEntity,
|
||||
} from "../../../../data/cover";
|
||||
import {
|
||||
CoverEntityFeature,
|
||||
canClose,
|
||||
canCloseTilt,
|
||||
canOpen,
|
||||
canOpenTilt,
|
||||
canStop,
|
||||
canStopTilt,
|
||||
} from "../../../../data/cover";
|
||||
|
||||
interface CoverButton {
|
||||
action: CoverAction;
|
||||
feature: CoverEntityFeature;
|
||||
icon: (stateObj: CoverEntity) => string;
|
||||
label: LocalizeKeys;
|
||||
enabled: (stateObj: CoverEntity) => boolean;
|
||||
}
|
||||
|
||||
const BUTTONS: Record<CoverControlMode, CoverButton[]> = {
|
||||
position: [
|
||||
{
|
||||
action: "open",
|
||||
feature: CoverEntityFeature.OPEN,
|
||||
icon: computeOpenIcon,
|
||||
label: "ui.card.cover.open_cover",
|
||||
enabled: canOpen,
|
||||
},
|
||||
{
|
||||
action: "stop",
|
||||
feature: CoverEntityFeature.STOP,
|
||||
icon: () => mdiStop,
|
||||
label: "ui.card.cover.stop_cover",
|
||||
enabled: canStop,
|
||||
},
|
||||
{
|
||||
action: "close",
|
||||
feature: CoverEntityFeature.CLOSE,
|
||||
icon: computeCloseIcon,
|
||||
label: "ui.card.cover.close_cover",
|
||||
enabled: canClose,
|
||||
},
|
||||
],
|
||||
tilt: [
|
||||
{
|
||||
action: "open",
|
||||
feature: CoverEntityFeature.OPEN_TILT,
|
||||
icon: () => mdiArrowTopRight,
|
||||
label: "ui.card.cover.open_tilt_cover",
|
||||
enabled: canOpenTilt,
|
||||
},
|
||||
{
|
||||
action: "stop",
|
||||
feature: CoverEntityFeature.STOP_TILT,
|
||||
icon: () => mdiStop,
|
||||
label: "ui.card.cover.stop_cover",
|
||||
enabled: canStopTilt,
|
||||
},
|
||||
{
|
||||
action: "close",
|
||||
feature: CoverEntityFeature.CLOSE_TILT,
|
||||
icon: () => mdiArrowBottomLeft,
|
||||
label: "ui.card.cover.close_tilt_cover",
|
||||
enabled: canCloseTilt,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@customElement("ha-more-info-cover-buttons")
|
||||
export class HaMoreInfoCoverButtons extends LitElement {
|
||||
@property({ attribute: false }) public stateObj!: CoverEntity;
|
||||
|
||||
@property({ attribute: false }) public mode: CoverControlMode = "position";
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
private _handleClick(ev: Event) {
|
||||
const action = (ev.currentTarget as HTMLElement).dataset
|
||||
.action as CoverAction;
|
||||
fireEvent(this, "cover-command", { mode: this.mode, action });
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.stateObj) {
|
||||
return nothing;
|
||||
}
|
||||
const stateObj = this.stateObj;
|
||||
const buttons = BUTTONS[this.mode].filter((button) =>
|
||||
supportsFeature(stateObj, button.feature)
|
||||
);
|
||||
if (!buttons.length) {
|
||||
return nothing;
|
||||
}
|
||||
return html`
|
||||
${buttons.map(
|
||||
(button) => html`
|
||||
<ha-control-button
|
||||
.label=${this._localize(button.label)}
|
||||
.disabled=${!button.enabled(stateObj)}
|
||||
data-action=${button.action}
|
||||
@click=${this._handleClick}
|
||||
>
|
||||
<div class="content">
|
||||
<ha-svg-icon .path=${button.icon(stateObj)}></ha-svg-icon>
|
||||
<span>
|
||||
${this._localize(
|
||||
`ui.dialogs.more_info_control.cover.${button.action}`
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</ha-control-button>
|
||||
`
|
||||
)}
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: var(--ha-space-3);
|
||||
width: 100%;
|
||||
}
|
||||
ha-control-button {
|
||||
flex: 1;
|
||||
max-width: 104px;
|
||||
height: 64px;
|
||||
--control-button-border-radius: var(--ha-border-radius-xl);
|
||||
--mdc-icon-size: 22px;
|
||||
}
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-1);
|
||||
font-size: var(--ha-font-size-s);
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-more-info-cover-buttons": HaMoreInfoCoverButtons;
|
||||
}
|
||||
}
|
||||
@@ -8,14 +8,14 @@ import { consumeLocalize } from "../../../../common/decorators/consume-context-e
|
||||
import { transform } from "../../../../common/decorators/transform";
|
||||
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import { clamp } from "../../../../common/number/clamp";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-control-button";
|
||||
import { apiContext, configContext } from "../../../../data/context";
|
||||
import type { CoverEntity } from "../../../../data/cover";
|
||||
import type { CoverControlMode, CoverEntity } from "../../../../data/cover";
|
||||
import {
|
||||
DEFAULT_COVER_FAVORITE_POSITIONS,
|
||||
coverSupportsPosition,
|
||||
coverSupportsTiltPosition,
|
||||
coverCurrentValue,
|
||||
} from "../../../../data/cover";
|
||||
import { normalizeFavoritePositions } from "../../../../data/favorite_positions";
|
||||
import { UNAVAILABLE } from "../../../../data/entity/entity";
|
||||
@@ -37,8 +37,6 @@ import {
|
||||
import "../ha-more-info-favorites";
|
||||
import type { HaMoreInfoFavorites } from "../ha-more-info-favorites";
|
||||
|
||||
type FavoriteKind = "position" | "tilt";
|
||||
|
||||
type FavoriteLocalizeKey =
|
||||
| "set"
|
||||
| "edit"
|
||||
@@ -50,8 +48,10 @@ type FavoriteLocalizeKey =
|
||||
| "edit_title"
|
||||
| "add_title";
|
||||
|
||||
const favoriteKindFromEvent = (ev: Event): FavoriteKind =>
|
||||
(ev.currentTarget as HTMLElement).dataset.kind as FavoriteKind;
|
||||
const OPTION_KEYS = {
|
||||
position: "favorite_positions",
|
||||
tilt: "favorite_tilt_positions",
|
||||
} as const satisfies Record<CoverControlMode, keyof CoverEntityOptions>;
|
||||
|
||||
@customElement("ha-more-info-cover-favorite-positions")
|
||||
export class HaMoreInfoCoverFavoritePositions extends LitElement {
|
||||
@@ -76,145 +76,70 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public editMode?: boolean;
|
||||
|
||||
@state() private _favoritePositions: number[] = [];
|
||||
@property({ attribute: false }) public mode: CoverControlMode = "position";
|
||||
|
||||
@state() private _favoriteTiltPositions: number[] = [];
|
||||
@state() private _favorites: number[] = [];
|
||||
|
||||
protected updated(changedProps: PropertyValues<this>): void {
|
||||
if (
|
||||
(changedProps.has("entry") || changedProps.has("stateObj")) &&
|
||||
this.entry &&
|
||||
this.stateObj
|
||||
) {
|
||||
const options = this.entry.options?.cover;
|
||||
|
||||
this._favoritePositions = coverSupportsPosition(this.stateObj)
|
||||
? normalizeFavoritePositions(
|
||||
options?.favorite_positions ?? DEFAULT_COVER_FAVORITE_POSITIONS
|
||||
)
|
||||
: [];
|
||||
|
||||
this._favoriteTiltPositions = coverSupportsTiltPosition(this.stateObj)
|
||||
? normalizeFavoritePositions(
|
||||
options?.favorite_tilt_positions ?? DEFAULT_COVER_FAVORITE_POSITIONS
|
||||
)
|
||||
: [];
|
||||
protected willUpdate(changedProps: PropertyValues<this>): void {
|
||||
if (changedProps.has("entry") || changedProps.has("mode")) {
|
||||
this._favorites = normalizeFavoritePositions(
|
||||
this.entry?.options?.cover?.[OPTION_KEYS[this.mode]] ??
|
||||
DEFAULT_COVER_FAVORITE_POSITIONS
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private _localizeFavorite(
|
||||
kind: FavoriteKind,
|
||||
key: FavoriteLocalizeKey,
|
||||
values?: Record<string, string | number>
|
||||
): string {
|
||||
return this._localize(
|
||||
`ui.dialogs.more_info_control.cover.${kind === "position" ? "favorite_position" : "favorite_tilt_position"}.${key}`,
|
||||
`ui.dialogs.more_info_control.cover.${this.mode === "position" ? "favorite_position" : "favorite_tilt_position"}.${key}`,
|
||||
values
|
||||
);
|
||||
}
|
||||
|
||||
private _getFavorites(kind: FavoriteKind): number[] {
|
||||
return kind === "position"
|
||||
? this._favoritePositions
|
||||
: this._favoriteTiltPositions;
|
||||
}
|
||||
|
||||
private _getCurrentValue(kind: FavoriteKind): number | undefined {
|
||||
const current =
|
||||
kind === "position"
|
||||
? this.stateObj.attributes.current_position
|
||||
: this.stateObj.attributes.current_tilt_position;
|
||||
|
||||
return current == null ? undefined : current;
|
||||
}
|
||||
|
||||
private async _save(options: CoverEntityOptions): Promise<void> {
|
||||
private async _setFavorites(favorites: number[]): Promise<void> {
|
||||
if (!this.entry) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentOptions: CoverEntityOptions = {
|
||||
...(this.entry.options?.cover ?? {}),
|
||||
};
|
||||
|
||||
if (coverSupportsPosition(this.stateObj)) {
|
||||
currentOptions.favorite_positions = this._favoritePositions;
|
||||
}
|
||||
|
||||
if (coverSupportsTiltPosition(this.stateObj)) {
|
||||
currentOptions.favorite_tilt_positions = this._favoriteTiltPositions;
|
||||
}
|
||||
|
||||
const normalized = normalizeFavoritePositions(favorites);
|
||||
this._favorites = normalized;
|
||||
const result = await updateEntityRegistryEntry(
|
||||
this._api.callWS,
|
||||
this.entry.entity_id,
|
||||
{
|
||||
options_domain: "cover",
|
||||
options: {
|
||||
...currentOptions,
|
||||
...options,
|
||||
...this.entry.options?.cover,
|
||||
[OPTION_KEYS[this.mode]]: normalized,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
fireEvent(this, "entity-entry-updated", result.entity_entry);
|
||||
}
|
||||
|
||||
private async _setFavorites(
|
||||
kind: FavoriteKind,
|
||||
favorites: number[]
|
||||
): Promise<void> {
|
||||
const normalized = normalizeFavoritePositions(favorites);
|
||||
|
||||
if (kind === "position") {
|
||||
this._favoritePositions = normalized;
|
||||
await this._save({ favorite_positions: normalized });
|
||||
return;
|
||||
}
|
||||
|
||||
this._favoriteTiltPositions = normalized;
|
||||
await this._save({ favorite_tilt_positions: normalized });
|
||||
}
|
||||
|
||||
private _move(kind: FavoriteKind, index: number, newIndex: number): void {
|
||||
const favorites = this._getFavorites(kind).concat();
|
||||
const moved = favorites.splice(index, 1)[0];
|
||||
favorites.splice(newIndex, 0, moved);
|
||||
this._setFavorites(kind, favorites);
|
||||
}
|
||||
|
||||
private _applyFavorite(kind: FavoriteKind, index: number): void {
|
||||
const favorite = this._getFavorites(kind)[index];
|
||||
|
||||
private _applyFavorite(index: number): void {
|
||||
const favorite = this._favorites[index];
|
||||
if (favorite === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind === "position") {
|
||||
this._api.callService("cover", "set_cover_position", {
|
||||
entity_id: this.stateObj.entity_id,
|
||||
position: favorite,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this._api.callService("cover", "set_cover_tilt_position", {
|
||||
entity_id: this.stateObj.entity_id,
|
||||
tilt_position: favorite,
|
||||
fireEvent(this, "cover-command", {
|
||||
mode: this.mode,
|
||||
action: "set",
|
||||
value: favorite,
|
||||
});
|
||||
}
|
||||
|
||||
private async _promptFavoriteValue(
|
||||
kind: FavoriteKind,
|
||||
value?: number
|
||||
): Promise<number | undefined> {
|
||||
const response = await showPromptDialog(this, {
|
||||
title: this._localizeFavorite(
|
||||
kind,
|
||||
value === undefined ? "add_title" : "edit_title"
|
||||
),
|
||||
inputLabel: this._localize(
|
||||
kind === "position"
|
||||
this.mode === "position"
|
||||
? "ui.card.cover.position"
|
||||
: "ui.card.cover.tilt_position"
|
||||
),
|
||||
@@ -235,76 +160,56 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return Math.max(0, Math.min(100, number));
|
||||
return clamp(number, 0, 100);
|
||||
}
|
||||
|
||||
private async _addFavorite(kind: FavoriteKind): Promise<void> {
|
||||
const value = await this._promptFavoriteValue(kind);
|
||||
|
||||
private async _addFavorite(): Promise<void> {
|
||||
const value = await this._promptFavoriteValue();
|
||||
if (value === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this._setFavorites(kind, [...this._getFavorites(kind), value]);
|
||||
await this._setFavorites([...this._favorites, value]);
|
||||
}
|
||||
|
||||
private async _editFavorite(
|
||||
kind: FavoriteKind,
|
||||
index: number
|
||||
): Promise<void> {
|
||||
const favorites = this._getFavorites(kind);
|
||||
const current = favorites[index];
|
||||
|
||||
private async _editFavorite(index: number): Promise<void> {
|
||||
const current = this._favorites[index];
|
||||
if (current === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const value = await this._promptFavoriteValue(kind, current);
|
||||
|
||||
const value = await this._promptFavoriteValue(current);
|
||||
if (value === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const updated = [...favorites];
|
||||
const updated = [...this._favorites];
|
||||
updated[index] = value;
|
||||
await this._setFavorites(kind, updated);
|
||||
await this._setFavorites(updated);
|
||||
}
|
||||
|
||||
private async _deleteFavorite(
|
||||
kind: FavoriteKind,
|
||||
index: number
|
||||
): Promise<void> {
|
||||
private async _deleteFavorite(index: number): Promise<void> {
|
||||
const confirmed = await showConfirmationDialog(this, {
|
||||
destructive: true,
|
||||
title: this._localizeFavorite(kind, "delete_confirm_title"),
|
||||
text: this._localizeFavorite(kind, "delete_confirm_text"),
|
||||
confirmText: this._localizeFavorite(kind, "delete_confirm_action"),
|
||||
title: this._localizeFavorite("delete_confirm_title"),
|
||||
text: this._localizeFavorite("delete_confirm_text"),
|
||||
confirmText: this._localizeFavorite("delete_confirm_action"),
|
||||
});
|
||||
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this._setFavorites(
|
||||
kind,
|
||||
this._getFavorites(kind).filter((_, itemIndex) => itemIndex !== index)
|
||||
this._favorites.filter((_, itemIndex) => itemIndex !== index)
|
||||
);
|
||||
}
|
||||
|
||||
private _renderFavoriteButton =
|
||||
(kind: FavoriteKind): HaMoreInfoFavorites["renderItem"] =>
|
||||
(favorite, _index, editMode) => {
|
||||
const currentValue = this._getCurrentValue(kind);
|
||||
const active = currentValue === favorite;
|
||||
const label = this._localizeFavorite(kind, editMode ? "edit" : "set", {
|
||||
private _favoriteButtonRenderer(): HaMoreInfoFavorites["renderItem"] {
|
||||
return (favorite, _index, editMode) => {
|
||||
const active = coverCurrentValue(this.stateObj, this.mode) === favorite;
|
||||
const label = this._localizeFavorite(editMode ? "edit" : "set", {
|
||||
value: `${favorite as number}%`,
|
||||
});
|
||||
|
||||
return html`
|
||||
<ha-control-button
|
||||
class=${classMap({
|
||||
active,
|
||||
})}
|
||||
class=${classMap({ active })}
|
||||
style=${styleMap({
|
||||
"--control-button-border-radius": "var(--ha-border-radius-pill)",
|
||||
width: "72px",
|
||||
@@ -317,20 +222,15 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
|
||||
</ha-control-button>
|
||||
`;
|
||||
};
|
||||
}
|
||||
|
||||
private _deleteLabel =
|
||||
(kind: FavoriteKind): HaMoreInfoFavorites["deleteLabel"] =>
|
||||
(index) =>
|
||||
this._localizeFavorite(kind, "delete", {
|
||||
number: index + 1,
|
||||
});
|
||||
private _deleteLabel: HaMoreInfoFavorites["deleteLabel"] = (index) =>
|
||||
this._localizeFavorite("delete", { number: index + 1 });
|
||||
|
||||
private _handleFavoriteAction = (
|
||||
private _handleFavoriteAction(
|
||||
ev: HASSDomEvent<HASSDomEvents["favorite-item-action"]>
|
||||
): void => {
|
||||
): void {
|
||||
ev.stopPropagation();
|
||||
const kind = favoriteKindFromEvent(ev);
|
||||
|
||||
const { action, index } = ev.detail;
|
||||
|
||||
if (action === "hold" && this._user?.is_admin) {
|
||||
@@ -339,158 +239,87 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
|
||||
}
|
||||
|
||||
if (this.editMode) {
|
||||
this._editFavorite(kind, index);
|
||||
this._editFavorite(index);
|
||||
return;
|
||||
}
|
||||
|
||||
this._applyFavorite(kind, index);
|
||||
};
|
||||
this._applyFavorite(index);
|
||||
}
|
||||
|
||||
private _handleFavoriteMoved = (
|
||||
private _handleFavoriteMoved(
|
||||
ev: HASSDomEvent<HASSDomEvents["favorite-item-moved"]>
|
||||
): void => {
|
||||
): void {
|
||||
ev.stopPropagation();
|
||||
const kind = favoriteKindFromEvent(ev);
|
||||
this._move(kind, ev.detail.oldIndex, ev.detail.newIndex);
|
||||
};
|
||||
const favorites = [...this._favorites];
|
||||
const [moved] = favorites.splice(ev.detail.oldIndex, 1);
|
||||
favorites.splice(ev.detail.newIndex, 0, moved);
|
||||
this._setFavorites(favorites);
|
||||
}
|
||||
|
||||
private _handleFavoriteDelete = (
|
||||
private _handleFavoriteDelete(
|
||||
ev: HASSDomEvent<HASSDomEvents["favorite-item-delete"]>
|
||||
): void => {
|
||||
): void {
|
||||
ev.stopPropagation();
|
||||
const kind = favoriteKindFromEvent(ev);
|
||||
this._deleteFavorite(kind, ev.detail.index);
|
||||
};
|
||||
this._deleteFavorite(ev.detail.index);
|
||||
}
|
||||
|
||||
private _handleFavoriteAdd = (
|
||||
private _handleFavoriteAdd(
|
||||
ev: HASSDomEvent<HASSDomEvents["favorite-item-add"]>
|
||||
): void => {
|
||||
): void {
|
||||
ev.stopPropagation();
|
||||
const kind = favoriteKindFromEvent(ev);
|
||||
this._addFavorite(kind);
|
||||
};
|
||||
this._addFavorite();
|
||||
}
|
||||
|
||||
private _handleFavoriteDone = (
|
||||
private _handleFavoriteDone(
|
||||
ev: HASSDomEvent<HASSDomEvents["favorite-item-done"]>
|
||||
): void => {
|
||||
): void {
|
||||
ev.stopPropagation();
|
||||
fireEvent(this, "toggle-edit-mode", false);
|
||||
};
|
||||
|
||||
private _renderKindSection(
|
||||
kind: FavoriteKind,
|
||||
label: string,
|
||||
favorites: number[],
|
||||
showDone: boolean,
|
||||
showLabel: boolean
|
||||
): TemplateResult | typeof nothing {
|
||||
if (!this.editMode && favorites.length === 0) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<section class="group">
|
||||
${showLabel ? html`<h4>${label}</h4>` : nothing}
|
||||
<ha-more-info-favorites
|
||||
data-kind=${kind}
|
||||
.items=${favorites}
|
||||
.renderItem=${this._renderFavoriteButton(kind)}
|
||||
.deleteLabel=${this._deleteLabel(kind)}
|
||||
.editMode=${this.editMode ?? false}
|
||||
.disabled=${this.stateObj.state === UNAVAILABLE}
|
||||
.isAdmin=${Boolean(this._user?.is_admin)}
|
||||
.showDone=${showDone}
|
||||
.addLabel=${this._localizeFavorite(kind, "add")}
|
||||
.doneLabel=${this._localize(
|
||||
"ui.dialogs.more_info_control.exit_edit_mode"
|
||||
)}
|
||||
@favorite-item-action=${this._handleFavoriteAction}
|
||||
@favorite-item-moved=${this._handleFavoriteMoved}
|
||||
@favorite-item-delete=${this._handleFavoriteDelete}
|
||||
@favorite-item-add=${this._handleFavoriteAdd}
|
||||
@favorite-item-done=${this._handleFavoriteDone}
|
||||
></ha-more-info-favorites>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
protected render(): TemplateResult | typeof nothing {
|
||||
if (!this.stateObj || !this.entry) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const supportsPosition = coverSupportsPosition(this.stateObj);
|
||||
const supportsTiltPosition = coverSupportsTiltPosition(this.stateObj);
|
||||
const showPositionSection = supportsPosition
|
||||
? this.editMode || this._favoritePositions.length > 0
|
||||
: false;
|
||||
const showTiltSection = supportsTiltPosition
|
||||
? this.editMode || this._favoriteTiltPositions.length > 0
|
||||
: false;
|
||||
const showLabels =
|
||||
[showPositionSection, showTiltSection].filter(Boolean).length > 1;
|
||||
|
||||
const showDoneOnPosition = supportsPosition && !supportsTiltPosition;
|
||||
if (!this.editMode && this._favorites.length === 0) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="groups">
|
||||
${
|
||||
supportsPosition
|
||||
? this._renderKindSection(
|
||||
"position",
|
||||
this._localize("ui.card.cover.position"),
|
||||
this._favoritePositions,
|
||||
showDoneOnPosition,
|
||||
showLabels
|
||||
)
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
supportsTiltPosition
|
||||
? this._renderKindSection(
|
||||
"tilt",
|
||||
this._localize("ui.card.cover.tilt_position"),
|
||||
this._favoriteTiltPositions,
|
||||
true,
|
||||
showLabels
|
||||
)
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
<ha-more-info-favorites
|
||||
.items=${this._favorites}
|
||||
.renderItem=${this._favoriteButtonRenderer()}
|
||||
.deleteLabel=${this._deleteLabel}
|
||||
.editMode=${this.editMode ?? false}
|
||||
.disabled=${this.stateObj.state === UNAVAILABLE}
|
||||
.isAdmin=${Boolean(this._user?.is_admin)}
|
||||
.showDone=${true}
|
||||
.addLabel=${this._localizeFavorite("add")}
|
||||
.doneLabel=${this._localize(
|
||||
"ui.dialogs.more_info_control.exit_edit_mode"
|
||||
)}
|
||||
@favorite-item-action=${this._handleFavoriteAction}
|
||||
@favorite-item-moved=${this._handleFavoriteMoved}
|
||||
@favorite-item-delete=${this._handleFavoriteDelete}
|
||||
@favorite-item-add=${this._handleFavoriteAdd}
|
||||
@favorite-item-done=${this._handleFavoriteDone}
|
||||
></ha-more-info-favorites>
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.groups {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-3);
|
||||
}
|
||||
|
||||
.group {
|
||||
ha-more-info-favorites {
|
||||
width: 100%;
|
||||
max-width: 384px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.group ha-more-info-favorites {
|
||||
--favorite-items-max-width: 384px;
|
||||
--favorite-item-active-background-color: var(--state-cover-active-color);
|
||||
}
|
||||
|
||||
h4 {
|
||||
margin: 0 0 var(--ha-space-2);
|
||||
color: var(--secondary-text-color);
|
||||
font-size: var(--ha-font-size-s);
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
text-align: center;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { TemplateResult } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import "../../../components/ha-absolute-time";
|
||||
import "../../../components/ha-relative-time";
|
||||
@@ -19,6 +20,10 @@ export class HaMoreInfoStateHeader extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public changedOverride?: number;
|
||||
|
||||
@property({ attribute: false }) public changedTextOverride?: string;
|
||||
|
||||
@property({ attribute: false }) public stateAccent = false;
|
||||
|
||||
@state() private _absoluteTime = false;
|
||||
|
||||
@state()
|
||||
@@ -51,30 +56,41 @@ export class HaMoreInfoStateHeader extends LitElement {
|
||||
const stateDisplay = this.stateOverride ?? this._localizeState();
|
||||
|
||||
return html`
|
||||
<p class="state">${stateDisplay}</p>
|
||||
<p class=${classMap({ state: true, accent: this.stateAccent })}>
|
||||
${stateDisplay}
|
||||
</p>
|
||||
<div class="time-row">
|
||||
<p class="last-changed" @click=${this._toggleAbsolute}>
|
||||
${
|
||||
this._absoluteTime
|
||||
? html`
|
||||
<ha-absolute-time
|
||||
.datetime=${
|
||||
this.changedOverride ?? this.stateObj.last_changed
|
||||
}
|
||||
></ha-absolute-time>
|
||||
`
|
||||
: html`
|
||||
<ha-relative-time
|
||||
.datetime=${
|
||||
this.changedOverride ?? this.stateObj.last_changed
|
||||
}
|
||||
capitalize
|
||||
></ha-relative-time>
|
||||
`
|
||||
}
|
||||
</p>
|
||||
${
|
||||
this.changedTextOverride
|
||||
? html`<p class="last-changed secondary" aria-hidden="true">
|
||||
${this.changedTextOverride}
|
||||
</p>`
|
||||
: html`<p class="last-changed" @click=${this._toggleAbsolute}>
|
||||
${
|
||||
this._absoluteTime
|
||||
? html`
|
||||
<ha-absolute-time
|
||||
.datetime=${
|
||||
this.changedOverride ?? this.stateObj.last_changed
|
||||
}
|
||||
></ha-absolute-time>
|
||||
`
|
||||
: html`
|
||||
<ha-relative-time
|
||||
.datetime=${
|
||||
this.changedOverride ?? this.stateObj.last_changed
|
||||
}
|
||||
capitalize
|
||||
></ha-relative-time>
|
||||
`
|
||||
}
|
||||
</p>`
|
||||
}
|
||||
<slot name="after-time"></slot>
|
||||
</div>
|
||||
<span class="visually-hidden" aria-live="polite"
|
||||
>${this.changedTextOverride ?? ""}</span
|
||||
>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -113,6 +129,22 @@ export class HaMoreInfoStateHeader extends LitElement {
|
||||
user-select: none;
|
||||
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
|
||||
}
|
||||
.visually-hidden {
|
||||
position: absolute;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
height: 1px;
|
||||
width: 1px;
|
||||
margin: -1px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
.state.accent {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
.last-changed.secondary {
|
||||
cursor: default;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,36 +1,46 @@
|
||||
import { mdiMenu, mdiSwapVertical } from "@mdi/js";
|
||||
import { mdiAngleAcute, mdiArrowUpDown } from "@mdi/js";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
|
||||
import { supportsFeature } from "../../../common/entity/supports-feature";
|
||||
import type { HASSDomEvent } from "../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-icon-button-group";
|
||||
import "../../../components/ha-icon-button-toggle";
|
||||
import { formattersContext } from "../../../data/context";
|
||||
import {
|
||||
shouldShowFavoriteOptions,
|
||||
type ExtEntityRegistryEntry,
|
||||
} from "../../../data/entity/entity_registry";
|
||||
import type { CoverEntity } from "../../../data/cover";
|
||||
import {
|
||||
CoverEntityFeature,
|
||||
coverSupportsAnyPosition,
|
||||
coverSupportsPosition,
|
||||
coverSupportsTiltPosition,
|
||||
computeCoverPositionStateDisplay,
|
||||
import { apiContext, formattersContext } from "../../../data/context";
|
||||
import type {
|
||||
CoverCommand,
|
||||
CoverControlMode,
|
||||
CoverDrag,
|
||||
CoverEntity,
|
||||
} from "../../../data/cover";
|
||||
import "../../../state-control/cover/ha-state-control-cover-buttons";
|
||||
import "../../../state-control/cover/ha-state-control-cover-position";
|
||||
import "../../../state-control/cover/ha-state-control-cover-tilt-position";
|
||||
import "../../../state-control/cover/ha-state-control-cover-toggle";
|
||||
import type { HomeAssistantFormatters } from "../../../types";
|
||||
import {
|
||||
coverCommandData,
|
||||
coverCommandService,
|
||||
coverCurrentValue,
|
||||
coverHasPositionControls,
|
||||
coverHasTiltControls,
|
||||
coverModeAttribute,
|
||||
coverSupportsPosition,
|
||||
coverSupportsSetValue,
|
||||
defaultCoverMode,
|
||||
} from "../../../data/cover";
|
||||
import type { ExtEntityRegistryEntry } from "../../../data/entity/entity_registry";
|
||||
import { CoverRequestController } from "../../../state-control/cover/cover-request-controller";
|
||||
import "../../../state-control/cover/ha-state-control-cover";
|
||||
import type { HomeAssistantApi, HomeAssistantFormatters } from "../../../types";
|
||||
import "../components/covers/ha-more-info-cover-buttons";
|
||||
import "../components/covers/ha-more-info-cover-favorite-positions";
|
||||
import "../components/ha-more-info-state-header";
|
||||
import { moreInfoControlStyle } from "../components/more-info-control-style";
|
||||
|
||||
type Mode = "position" | "button";
|
||||
type CoverHintKey =
|
||||
| "requested"
|
||||
| "requested_open"
|
||||
| "requested_closed"
|
||||
| "currently"
|
||||
| "currently_unknown";
|
||||
|
||||
@customElement("more-info-cover")
|
||||
class MoreInfoCover extends LitElement {
|
||||
@@ -42,159 +52,176 @@ class MoreInfoCover extends LitElement {
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: HomeAssistantApi;
|
||||
|
||||
@property({ attribute: false }) public stateObj?: CoverEntity;
|
||||
|
||||
@property({ attribute: false }) public entry?: ExtEntityRegistryEntry | null;
|
||||
|
||||
@property({ attribute: false }) public editMode?: boolean;
|
||||
|
||||
@state() private _mode?: Mode;
|
||||
@state() private _mode: CoverControlMode = "position";
|
||||
|
||||
private _setMode(ev) {
|
||||
this._mode = ev.currentTarget.mode;
|
||||
}
|
||||
@state() private _drag?: CoverDrag;
|
||||
|
||||
private _requests = new CoverRequestController(this);
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>): void {
|
||||
super.willUpdate(changedProps);
|
||||
if (changedProps.has("stateObj") && this.stateObj) {
|
||||
const entityId = this.stateObj.entity_id;
|
||||
const oldEntityId = changedProps.get("stateObj")?.entity_id;
|
||||
if (!this._mode || entityId !== oldEntityId) {
|
||||
this._mode = coverSupportsAnyPosition(this.stateObj)
|
||||
? "position"
|
||||
: "button";
|
||||
}
|
||||
if (!changedProps.has("stateObj") || !this.stateObj) {
|
||||
return;
|
||||
}
|
||||
if (changedProps.get("stateObj")?.entity_id !== this.stateObj.entity_id) {
|
||||
this._mode = defaultCoverMode(this.stateObj);
|
||||
this._requests.clear();
|
||||
this._drag = undefined;
|
||||
return;
|
||||
}
|
||||
this._requests.stateChanged(this.stateObj);
|
||||
}
|
||||
|
||||
private get _stateOverride() {
|
||||
const stateDisplay = this._formatters.formatEntityState(this.stateObj!);
|
||||
private _setMode(ev: Event) {
|
||||
this._mode = (ev.currentTarget as HTMLElement).dataset
|
||||
.mode as CoverControlMode;
|
||||
}
|
||||
|
||||
const positionStateDisplay = computeCoverPositionStateDisplay(
|
||||
private _handleCommand(ev: HASSDomEvent<CoverCommand>) {
|
||||
ev.stopPropagation();
|
||||
const stateObj = this.stateObj!;
|
||||
const command = ev.detail;
|
||||
this._api
|
||||
.callService(
|
||||
"cover",
|
||||
coverCommandService(command),
|
||||
coverCommandData(stateObj, command)
|
||||
)
|
||||
.catch(() => this._requests.clear());
|
||||
this._requests.commandSent(command, stateObj);
|
||||
}
|
||||
|
||||
private _handleDrag(ev: HASSDomEvent<HASSDomEvents["cover-drag-changed"]>) {
|
||||
ev.stopPropagation();
|
||||
this._drag = ev.detail.drag;
|
||||
}
|
||||
|
||||
private _formatValue(mode: CoverControlMode, value: number) {
|
||||
return this._formatters.formatEntityAttributeValue(
|
||||
this.stateObj!,
|
||||
this._formatters.formatEntityAttributeValue
|
||||
coverModeAttribute(mode),
|
||||
Math.round(value)
|
||||
);
|
||||
}
|
||||
|
||||
if (positionStateDisplay) {
|
||||
return `${stateDisplay} · ${positionStateDisplay}`;
|
||||
private _hint(key: CoverHintKey, values?: Record<string, string>) {
|
||||
return this._localize(`ui.dialogs.more_info_control.cover.${key}`, values);
|
||||
}
|
||||
|
||||
private _dragText(): string | undefined {
|
||||
const drag = this._drag;
|
||||
if (!drag) {
|
||||
return undefined;
|
||||
}
|
||||
return stateDisplay;
|
||||
if (!drag.swipe) {
|
||||
return this._formatValue(this._mode, drag.value);
|
||||
}
|
||||
if (!drag.swipe.passedHalfway) {
|
||||
return undefined;
|
||||
}
|
||||
return this._localize(
|
||||
drag.swipe.action === "close"
|
||||
? "ui.dialogs.more_info_control.cover.closes_on_release"
|
||||
: "ui.dialogs.more_info_control.cover.opens_on_release"
|
||||
);
|
||||
}
|
||||
|
||||
private _stateText(): string {
|
||||
const stateObj = this.stateObj!;
|
||||
const stateDisplay = this._formatters.formatEntityState(stateObj);
|
||||
const value = Math.round(
|
||||
stateObj.attributes[coverModeAttribute(this._mode)] ?? 0
|
||||
);
|
||||
if (value === 0) {
|
||||
return stateDisplay;
|
||||
}
|
||||
return `${stateDisplay} · ${this._formatValue(this._mode, value)}`;
|
||||
}
|
||||
|
||||
private _dragHint(): string | undefined {
|
||||
if (!this._drag || this._drag.swipe) {
|
||||
return undefined;
|
||||
}
|
||||
const current = coverCurrentValue(this.stateObj!, this._mode);
|
||||
return current === undefined
|
||||
? this._hint("currently_unknown")
|
||||
: this._hint("currently", {
|
||||
value: this._formatValue(this._mode, current),
|
||||
});
|
||||
}
|
||||
|
||||
private _requestHint(): string | undefined {
|
||||
const request = this._requests.request;
|
||||
if (!request || this._drag) {
|
||||
return undefined;
|
||||
}
|
||||
if (request.mode === "position" && !coverSupportsPosition(this.stateObj!)) {
|
||||
return this._hint(request.value ? "requested_open" : "requested_closed");
|
||||
}
|
||||
return this._hint("requested", {
|
||||
value: this._formatValue(request.mode, request.value),
|
||||
});
|
||||
}
|
||||
|
||||
private _showFavorites(stateObj: CoverEntity): boolean {
|
||||
if (!this.entry) {
|
||||
return false;
|
||||
}
|
||||
return coverSupportsSetValue(stateObj, this._mode);
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.stateObj) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const supportsPosition = coverSupportsPosition(this.stateObj);
|
||||
|
||||
const supportsTiltPosition = coverSupportsTiltPosition(this.stateObj);
|
||||
|
||||
const showFavoriteControls = Boolean(
|
||||
this.entry &&
|
||||
(this.editMode ||
|
||||
(coverSupportsPosition(this.stateObj) &&
|
||||
shouldShowFavoriteOptions(
|
||||
this.entry.options?.cover?.favorite_positions
|
||||
)) ||
|
||||
(coverSupportsTiltPosition(this.stateObj) &&
|
||||
shouldShowFavoriteOptions(
|
||||
this.entry.options?.cover?.favorite_tilt_positions
|
||||
)))
|
||||
);
|
||||
|
||||
const supportsOpenClose =
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.OPEN) ||
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE) ||
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.STOP);
|
||||
|
||||
const supportsTilt =
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.OPEN_TILT) ||
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE_TILT) ||
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.STOP_TILT);
|
||||
|
||||
const supportsOpenCloseOnly =
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.OPEN) &&
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE) &&
|
||||
!supportsFeature(this.stateObj, CoverEntityFeature.STOP) &&
|
||||
!supportsTilt &&
|
||||
!supportsPosition &&
|
||||
!supportsTiltPosition;
|
||||
const stateObj = this.stateObj;
|
||||
const bothModes =
|
||||
coverHasPositionControls(stateObj) && coverHasTiltControls(stateObj);
|
||||
const dragText = this._dragText();
|
||||
|
||||
return html`
|
||||
<ha-more-info-state-header
|
||||
.stateObj=${this.stateObj}
|
||||
.stateOverride=${this._stateOverride}
|
||||
.stateObj=${stateObj}
|
||||
.stateOverride=${dragText ?? this._stateText()}
|
||||
.changedTextOverride=${this._dragHint() ?? this._requestHint()}
|
||||
.stateAccent=${dragText !== undefined}
|
||||
></ha-more-info-state-header>
|
||||
<div class="controls">
|
||||
<div
|
||||
class="controls"
|
||||
@cover-command=${this._handleCommand}
|
||||
@cover-drag-changed=${this._handleDrag}
|
||||
>
|
||||
<div class="main-control">
|
||||
<ha-state-control-cover
|
||||
.stateObj=${stateObj}
|
||||
.mode=${this._mode}
|
||||
.request=${this._requests.request}
|
||||
></ha-state-control-cover>
|
||||
${
|
||||
this._mode === "position"
|
||||
? html`
|
||||
${
|
||||
supportsPosition
|
||||
? html`
|
||||
<ha-state-control-cover-position
|
||||
.stateObj=${this.stateObj}
|
||||
></ha-state-control-cover-position>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
supportsTiltPosition
|
||||
? html`
|
||||
<ha-state-control-cover-tilt-position
|
||||
.stateObj=${this.stateObj}
|
||||
></ha-state-control-cover-tilt-position>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
this._mode === "button"
|
||||
? html`
|
||||
${
|
||||
supportsOpenCloseOnly
|
||||
? html`
|
||||
<ha-state-control-cover-toggle
|
||||
.stateObj=${this.stateObj}
|
||||
></ha-state-control-cover-toggle>
|
||||
`
|
||||
: supportsOpenClose || supportsTilt
|
||||
? html`
|
||||
<ha-state-control-cover-buttons
|
||||
.stateObj=${this.stateObj}
|
||||
></ha-state-control-cover-buttons>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
${
|
||||
(supportsPosition || supportsTiltPosition) &&
|
||||
(supportsOpenClose || supportsTilt)
|
||||
bothModes
|
||||
? html`
|
||||
<ha-icon-button-group>
|
||||
<ha-icon-button-toggle
|
||||
.label=${this._localize(
|
||||
`ui.dialogs.more_info_control.cover.switch_mode.position`
|
||||
)}
|
||||
.label=${this._localize("ui.card.cover.position")}
|
||||
.selected=${this._mode === "position"}
|
||||
.path=${mdiMenu}
|
||||
.mode=${"position"}
|
||||
.path=${mdiArrowUpDown}
|
||||
data-mode="position"
|
||||
@click=${this._setMode}
|
||||
></ha-icon-button-toggle>
|
||||
<ha-icon-button-toggle
|
||||
.label=${this._localize(
|
||||
`ui.dialogs.more_info_control.cover.switch_mode.button`
|
||||
)}
|
||||
.selected=${this._mode === "button"}
|
||||
.path=${mdiSwapVertical}
|
||||
.mode=${"button"}
|
||||
.label=${this._localize("ui.card.cover.tilt_position")}
|
||||
.selected=${this._mode === "tilt"}
|
||||
.path=${mdiAngleAcute}
|
||||
data-mode="tilt"
|
||||
@click=${this._setMode}
|
||||
></ha-icon-button-toggle>
|
||||
</ha-icon-button-group>
|
||||
@@ -202,13 +229,18 @@ class MoreInfoCover extends LitElement {
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
<ha-more-info-cover-buttons
|
||||
.stateObj=${stateObj}
|
||||
.mode=${this._mode}
|
||||
></ha-more-info-cover-buttons>
|
||||
${
|
||||
showFavoriteControls
|
||||
this._showFavorites(stateObj)
|
||||
? html`
|
||||
<ha-more-info-cover-favorite-positions
|
||||
.stateObj=${this.stateObj}
|
||||
.stateObj=${stateObj}
|
||||
.entry=${this.entry}
|
||||
.editMode=${this.editMode}
|
||||
.mode=${this._mode}
|
||||
></ha-more-info-cover-favorite-positions>
|
||||
`
|
||||
: nothing
|
||||
@@ -223,11 +255,12 @@ class MoreInfoCover extends LitElement {
|
||||
css`
|
||||
.main-control {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-4);
|
||||
}
|
||||
.main-control > * {
|
||||
margin: 0 var(--ha-space-2);
|
||||
ha-more-info-cover-buttons {
|
||||
max-width: 360px;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -227,7 +227,7 @@ class MoreInfoWeather extends LitElement {
|
||||
.datetime=${this.stateObj.last_changed}
|
||||
capitalize
|
||||
></ha-relative-time>
|
||||
<ha-tooltip for="relative-time">
|
||||
<ha-tooltip trigger="hover focus click" for="relative-time">
|
||||
<div class="row">
|
||||
<span class="column-name">
|
||||
${this._i18n.localize(
|
||||
|
||||
@@ -12,6 +12,7 @@ import { computeStateDomain } from "../../common/entity/compute_state_domain";
|
||||
import { getEntityContext } from "../../common/entity/context/get_entity_context";
|
||||
import "../../components/ha-badge";
|
||||
import type { ExtEntityRegistryEntry } from "../../data/entity/entity_registry";
|
||||
import { computeGroupMemberIds } from "../../data/group";
|
||||
import { supportsCoverPositionCardFeature } from "../../panels/lovelace/card-features/hui-cover-position-card-feature";
|
||||
import { supportsLightBrightnessCardFeature } from "../../panels/lovelace/card-features/hui-light-brightness-card-feature";
|
||||
import { supportsLightColorCardFeature } from "../../panels/lovelace/card-features/hui-light-color-card-feature";
|
||||
@@ -115,13 +116,9 @@ class MoreInfoContent extends LitElement {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const memberIds =
|
||||
(entry?.capabilities?.group_entities as string[] | undefined) ??
|
||||
(Array.isArray(stateObj.attributes.entity_id)
|
||||
? (stateObj.attributes.entity_id as string[])
|
||||
: undefined);
|
||||
|
||||
return memberIds?.filter((entityId) => !entities[entityId]?.hidden);
|
||||
return computeGroupMemberIds(stateObj, entry)?.filter(
|
||||
(entityId) => !entities[entityId]?.hidden
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -33,7 +33,11 @@ export class HuiPersistentNotificationItem extends LitElement {
|
||||
.datetime=${this.notification.created_at}
|
||||
capitalize
|
||||
></ha-relative-time>
|
||||
<ha-tooltip for="relative-time" placement="bottom">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="relative-time"
|
||||
placement="bottom"
|
||||
>
|
||||
${this._computeTooltip(this.hass, this.notification)}
|
||||
</ha-tooltip>
|
||||
</span>
|
||||
|
||||
@@ -597,7 +597,7 @@ export const configSections: Record<string, PageNavigation[]> = {
|
||||
translationKey: "storage",
|
||||
iconPath: mdiDatabase,
|
||||
iconColor: "#518C43",
|
||||
component: "hassio",
|
||||
component: ["hassio", "recorder"],
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -768,7 +768,6 @@ export class HaEnergyGridSourceEditor extends EnergyEditorMixin(
|
||||
number_energy_price: draft.number_energy_price,
|
||||
entity_energy_price_export: draft.entity_energy_price_export,
|
||||
number_energy_price_export: draft.number_energy_price_export,
|
||||
cost_adjustment_day: draft.cost_adjustment_day,
|
||||
};
|
||||
if (draft.name) {
|
||||
source.name = draft.name;
|
||||
|
||||
@@ -52,6 +52,7 @@ import { bytesToString } from "../../../util/bytes-to-string";
|
||||
import { showMoveDatadiskDialog } from "./show-dialog-move-datadisk";
|
||||
import { showMountViewDialog } from "./show-dialog-view-mount";
|
||||
import "./storage-breakdown-chart";
|
||||
import "./storage-database-card";
|
||||
|
||||
@customElement("ha-config-section-storage")
|
||||
class HaConfigSectionStorage extends LitElement {
|
||||
@@ -152,104 +153,123 @@ class HaConfigSectionStorage extends LitElement {
|
||||
`
|
||||
: ""
|
||||
}
|
||||
|
||||
<ha-card
|
||||
outlined
|
||||
.header=${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.title"
|
||||
)}
|
||||
>
|
||||
${
|
||||
this._mountsInfo === null
|
||||
? html`<ha-alert
|
||||
class="mounts-not-supported"
|
||||
alert-type="warning"
|
||||
.title=${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.not_supported.title"
|
||||
)}
|
||||
>
|
||||
${
|
||||
isHAOS
|
||||
? html`${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.not_supported.os",
|
||||
{ version: "10.2" }
|
||||
)}
|
||||
<ha-button
|
||||
appearance="plain"
|
||||
slot="action"
|
||||
@click=${this._navigateToUpdates}
|
||||
>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.not_supported.navigate_to_updates"
|
||||
)}
|
||||
</ha-button>`
|
||||
: this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.not_supported.supervised"
|
||||
)
|
||||
}
|
||||
</ha-alert>`
|
||||
: validMounts?.length
|
||||
? html`<ha-list-base
|
||||
aria-label=${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.title"
|
||||
)}
|
||||
>
|
||||
${validMounts.map((mount) =>
|
||||
mount.state === SupervisorMountState.ACTIVE
|
||||
? html`<ha-list-item-button
|
||||
.mount=${mount}
|
||||
@click=${this._changeMount}
|
||||
>
|
||||
${this._renderMountContent(mount)}
|
||||
<ha-icon-next slot="end"></ha-icon-next>
|
||||
</ha-list-item-button>`
|
||||
: html`<ha-list-item-base>
|
||||
${this._renderMountContent(mount)}
|
||||
<div slot="end" class="mount-actions">
|
||||
<ha-icon-button
|
||||
.mount=${mount}
|
||||
.label=${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.reload"
|
||||
)}
|
||||
@click=${this._reloadMount}
|
||||
.path=${mdiReload}
|
||||
></ha-icon-button>
|
||||
<ha-icon-button
|
||||
.mount=${mount}
|
||||
.label=${this.hass.localize("ui.common.edit")}
|
||||
@click=${this._changeMount}
|
||||
.path=${mdiPencil}
|
||||
></ha-icon-button>
|
||||
</div>
|
||||
</ha-list-item-base>`
|
||||
)}
|
||||
</ha-list-base>`
|
||||
: html`<div class="no-mounts">
|
||||
<ha-svg-icon .path=${mdiNas}></ha-svg-icon>
|
||||
<p>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.no_mounts"
|
||||
)}
|
||||
</p>
|
||||
</div>`
|
||||
}
|
||||
${
|
||||
this._mountsInfo !== null
|
||||
? html`<div class="card-actions">
|
||||
<ha-button appearance="plain" @click=${this._addMount}>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.add_title"
|
||||
)}
|
||||
</ha-button>
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
</ha-card>
|
||||
${
|
||||
isComponentLoaded(this.hass.config, "recorder")
|
||||
? html`<storage-database-card
|
||||
.narrow=${this.narrow}
|
||||
></storage-database-card>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
isComponentLoaded(this.hass.config, "hassio")
|
||||
? this._renderMounts(validMounts, isHAOS)
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
</hass-subpage>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderMounts(
|
||||
validMounts: SupervisorMount[] | undefined,
|
||||
isHAOS: boolean | undefined
|
||||
) {
|
||||
return html`
|
||||
<ha-card
|
||||
outlined
|
||||
.header=${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.title"
|
||||
)}
|
||||
>
|
||||
${
|
||||
this._mountsInfo === null
|
||||
? html`<ha-alert
|
||||
class="mounts-not-supported"
|
||||
alert-type="warning"
|
||||
.title=${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.not_supported.title"
|
||||
)}
|
||||
>
|
||||
${
|
||||
isHAOS
|
||||
? html`${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.not_supported.os",
|
||||
{ version: "10.2" }
|
||||
)}
|
||||
<ha-button
|
||||
appearance="plain"
|
||||
slot="action"
|
||||
@click=${this._navigateToUpdates}
|
||||
>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.not_supported.navigate_to_updates"
|
||||
)}
|
||||
</ha-button>`
|
||||
: this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.not_supported.supervised"
|
||||
)
|
||||
}
|
||||
</ha-alert>`
|
||||
: validMounts?.length
|
||||
? html`<ha-list-base
|
||||
aria-label=${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.title"
|
||||
)}
|
||||
>
|
||||
${validMounts.map((mount) =>
|
||||
mount.state === SupervisorMountState.ACTIVE
|
||||
? html`<ha-list-item-button
|
||||
.mount=${mount}
|
||||
@click=${this._changeMount}
|
||||
>
|
||||
${this._renderMountContent(mount)}
|
||||
<ha-icon-next slot="end"></ha-icon-next>
|
||||
</ha-list-item-button>`
|
||||
: html`<ha-list-item-base>
|
||||
${this._renderMountContent(mount)}
|
||||
<div slot="end" class="mount-actions">
|
||||
<ha-icon-button
|
||||
.mount=${mount}
|
||||
.label=${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.reload"
|
||||
)}
|
||||
@click=${this._reloadMount}
|
||||
.path=${mdiReload}
|
||||
></ha-icon-button>
|
||||
<ha-icon-button
|
||||
.mount=${mount}
|
||||
.label=${this.hass.localize("ui.common.edit")}
|
||||
@click=${this._changeMount}
|
||||
.path=${mdiPencil}
|
||||
></ha-icon-button>
|
||||
</div>
|
||||
</ha-list-item-base>`
|
||||
)}
|
||||
</ha-list-base>`
|
||||
: html`<div class="no-mounts">
|
||||
<ha-svg-icon .path=${mdiNas}></ha-svg-icon>
|
||||
<p>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.no_mounts"
|
||||
)}
|
||||
</p>
|
||||
</div>`
|
||||
}
|
||||
${
|
||||
this._mountsInfo !== null
|
||||
? html`<div class="card-actions">
|
||||
<ha-button appearance="plain" @click=${this._addMount}>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.storage.network_mounts.add_title"
|
||||
)}
|
||||
</ha-button>
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
</ha-card>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderDiskLifeTime(diskLifeTime: number | null) {
|
||||
if (diskLifeTime === null) {
|
||||
return nothing;
|
||||
|
||||
@@ -0,0 +1,559 @@
|
||||
import type { PropertyValues, TemplateResult } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import type { HassConfig } from "home-assistant-js-websocket";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { getGraphColorByIndex } from "../../../common/color/colors";
|
||||
import { formatDateTime } from "../../../common/datetime/format_date_time";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../common/decorators/transform";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../../common/dom/fire_event";
|
||||
import { computeStateName } from "../../../common/entity/compute_state_name";
|
||||
import { formatNumber } from "../../../common/number/format_number";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/data-table/ha-data-table";
|
||||
import type {
|
||||
DataTableColumnContainer,
|
||||
DataTableRowData,
|
||||
} from "../../../components/data-table/ha-data-table";
|
||||
import "../../../components/ha-alert";
|
||||
import "../../../components/ha-button";
|
||||
import "../../../components/ha-card";
|
||||
import "../../../components/ha-segmented-bar";
|
||||
import type { Segment } from "../../../components/ha-segmented-bar";
|
||||
import "../../../components/ha-spinner";
|
||||
import {
|
||||
apiContext,
|
||||
configContext,
|
||||
fullEntitiesContext,
|
||||
internationalizationContext,
|
||||
statesContext,
|
||||
uiContext,
|
||||
} from "../../../data/context";
|
||||
import type {
|
||||
RecorderDatabaseUsage,
|
||||
RecorderTableUsage,
|
||||
} from "../../../data/recorder";
|
||||
import type { EntityRegistryEntry } from "../../../data/entity/entity_registry";
|
||||
import { fetchRecorderDatabaseUsage } from "../../../data/recorder";
|
||||
import { showMoreInfoDialog } from "../../../dialogs/more-info/show-ha-more-info-dialog";
|
||||
import type { FrontendLocaleData } from "../../../data/translation";
|
||||
import type { Themes } from "../../../data/ws-themes";
|
||||
import type {
|
||||
HomeAssistant,
|
||||
HomeAssistantApi,
|
||||
HomeAssistantConfig,
|
||||
HomeAssistantInternationalization,
|
||||
HomeAssistantUI,
|
||||
} from "../../../types";
|
||||
import { bytesToString } from "../../../util/bytes-to-string";
|
||||
|
||||
// Tables below minShare of the total are summed into otherBytes.
|
||||
export const groupSmallTables = (
|
||||
tables: RecorderTableUsage[],
|
||||
minShare = 0.01
|
||||
): { tables: RecorderTableUsage[]; otherBytes: number; totalBytes: number } => {
|
||||
const totalBytes = tables.reduce((sum, table) => sum + table.bytes, 0);
|
||||
const large = tables.filter(
|
||||
(table) => table.bytes > 0 && table.bytes >= totalBytes * minShare
|
||||
);
|
||||
return {
|
||||
tables: large,
|
||||
otherBytes: totalBytes - large.reduce((sum, table) => sum + table.bytes, 0),
|
||||
totalBytes,
|
||||
};
|
||||
};
|
||||
|
||||
// Row id for the rows the database cannot attribute to an entity or statistic.
|
||||
export const UNKNOWN_ROW_ID = "unknown";
|
||||
|
||||
export interface DatabaseUsageRow {
|
||||
id: string;
|
||||
states: number;
|
||||
statistics: number;
|
||||
statistics_short_term: number;
|
||||
bytes: number | null;
|
||||
}
|
||||
|
||||
// Statistics of an entity share its ID and are merged into its row.
|
||||
export const databaseUsageRows = (
|
||||
usage: RecorderDatabaseUsage
|
||||
): DatabaseUsageRow[] => {
|
||||
const rows = new Map<string, DatabaseUsageRow>();
|
||||
const row = (id: string | null) => {
|
||||
const key = id ?? UNKNOWN_ROW_ID;
|
||||
let result = rows.get(key);
|
||||
if (!result) {
|
||||
result = {
|
||||
id: key,
|
||||
states: 0,
|
||||
statistics: 0,
|
||||
statistics_short_term: 0,
|
||||
bytes: usage.tables ? 0 : null,
|
||||
};
|
||||
rows.set(key, result);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
for (const entity of usage.entities) {
|
||||
const result = row(entity.entity_id);
|
||||
result.states += entity.states;
|
||||
if (result.bytes !== null) {
|
||||
result.bytes +=
|
||||
(entity.states_bytes ?? 0) + (entity.attributes_bytes ?? 0);
|
||||
}
|
||||
}
|
||||
for (const statistic of usage.statistics) {
|
||||
const result = row(statistic.statistic_id);
|
||||
result.statistics += statistic.statistics;
|
||||
result.statistics_short_term += statistic.statistics_short_term;
|
||||
if (result.bytes !== null) {
|
||||
result.bytes +=
|
||||
(statistic.statistics_bytes ?? 0) +
|
||||
(statistic.statistics_short_term_bytes ?? 0);
|
||||
}
|
||||
}
|
||||
return [...rows.values()];
|
||||
};
|
||||
|
||||
interface EntityUsageRow extends DatabaseUsageRow, DataTableRowData {
|
||||
name: string;
|
||||
hasSettings: boolean;
|
||||
}
|
||||
|
||||
@customElement("storage-database-card")
|
||||
export class StorageDatabaseCard extends LitElement {
|
||||
@property({ type: Boolean }) public narrow = false;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
@transform<HomeAssistantInternationalization, FrontendLocaleData>({
|
||||
transformer: ({ locale }) => locale,
|
||||
})
|
||||
private _locale!: FrontendLocaleData;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, HassConfig>({
|
||||
transformer: ({ config }) => config,
|
||||
})
|
||||
private _hassConfig!: HassConfig;
|
||||
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: HomeAssistantApi;
|
||||
|
||||
@state()
|
||||
@consume({ context: uiContext, subscribe: true })
|
||||
@transform<HomeAssistantUI, Themes>({
|
||||
transformer: ({ themes }) => themes,
|
||||
})
|
||||
private _themes!: Themes;
|
||||
|
||||
// Not reactive: read when building the rows, which follow the entity registry.
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
private _states!: HomeAssistant["states"];
|
||||
|
||||
// Includes disabled entities, which have no state but can have recorded data.
|
||||
@state()
|
||||
@consume({ context: fullEntitiesContext, subscribe: true })
|
||||
private _entityRegistry: EntityRegistryEntry[] = [];
|
||||
|
||||
// Undefined until loaded, null when no recent report exists.
|
||||
@state() private _usage?: RecorderDatabaseUsage | null;
|
||||
|
||||
@state() private _loading = false;
|
||||
|
||||
@state() private _analyzing = false;
|
||||
|
||||
@state() private _error?: string;
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>): void {
|
||||
super.firstUpdated(changedProps);
|
||||
this._load();
|
||||
}
|
||||
|
||||
protected render(): TemplateResult {
|
||||
const usage = this._usage;
|
||||
return html`
|
||||
<ha-card
|
||||
outlined
|
||||
.header=${this._localize("ui.panel.config.storage.database.title")}
|
||||
>
|
||||
<div class="card-content">
|
||||
${
|
||||
this._error
|
||||
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
usage
|
||||
? this._renderUsage(usage)
|
||||
: this._analyzing
|
||||
? html`<div class="loading">
|
||||
<ha-spinner></ha-spinner>
|
||||
<span>
|
||||
${this._localize(
|
||||
"ui.panel.config.storage.database.analyzing"
|
||||
)}
|
||||
</span>
|
||||
</div>`
|
||||
: usage === null
|
||||
? html`<p class="description">
|
||||
${this._localize(
|
||||
"ui.panel.config.storage.database.description"
|
||||
)}
|
||||
</p>`
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
<div class="card-actions">
|
||||
<ha-button
|
||||
appearance="plain"
|
||||
.loading=${this._analyzing}
|
||||
.disabled=${this._loading || this._analyzing}
|
||||
@click=${this._analyze}
|
||||
>
|
||||
${this._localize(
|
||||
usage
|
||||
? "ui.panel.config.storage.database.analyze_again"
|
||||
: "ui.panel.config.storage.database.analyze"
|
||||
)}
|
||||
</ha-button>
|
||||
</div>
|
||||
</ha-card>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderUsage(usage: RecorderDatabaseUsage) {
|
||||
return html`
|
||||
<div class="summary">
|
||||
<span class="total">${bytesToString(usage.total_bytes)}</span>
|
||||
<span class="generated">
|
||||
${this._localize("ui.panel.config.storage.database.as_of", {
|
||||
time: formatDateTime(
|
||||
new Date(usage.generated_at),
|
||||
this._locale,
|
||||
this._hassConfig
|
||||
),
|
||||
})}
|
||||
</span>
|
||||
${
|
||||
!usage.tables?.length && usage.free_bytes
|
||||
? html`<span class="generated">
|
||||
${this._localize(
|
||||
"ui.panel.config.storage.database.unused_space_of",
|
||||
{ size: bytesToString(usage.free_bytes) }
|
||||
)}
|
||||
</span>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
usage.wal_bytes
|
||||
? html`<span class="generated">
|
||||
${this._localize("ui.panel.config.storage.database.wal", {
|
||||
size: bytesToString(usage.wal_bytes),
|
||||
})}
|
||||
</span>`
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
${
|
||||
usage.tables?.length
|
||||
? html`<ha-segmented-bar
|
||||
.heading=${this._localize(
|
||||
"ui.panel.config.storage.database.tables"
|
||||
)}
|
||||
.segments=${this._tableSegments(
|
||||
usage.tables,
|
||||
usage.total_bytes,
|
||||
usage.free_bytes,
|
||||
this._localize,
|
||||
this._themes
|
||||
)}
|
||||
></ha-segmented-bar>`
|
||||
: nothing
|
||||
}
|
||||
<div class="table">
|
||||
<ha-data-table
|
||||
.narrow=${this.narrow}
|
||||
.columns=${this._columns(
|
||||
this._localize,
|
||||
this._locale,
|
||||
this.narrow,
|
||||
usage.tables !== null
|
||||
)}
|
||||
.data=${this._rows(usage, this._entityRegistry, this._localize)}
|
||||
.searchLabel=${this._localize(
|
||||
"ui.panel.config.storage.database.search"
|
||||
)}
|
||||
.noDataText=${this._localize(
|
||||
"ui.panel.config.storage.database.no_entities"
|
||||
)}
|
||||
></ha-data-table>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private _tableSegments = memoizeOne(
|
||||
(
|
||||
tables: RecorderTableUsage[],
|
||||
totalBytes: number,
|
||||
freeBytes: number | null,
|
||||
localize: LocalizeFunc,
|
||||
_themes: Themes
|
||||
): Segment[] => {
|
||||
const computedStyles = getComputedStyle(this);
|
||||
const grouped = groupSmallTables(tables);
|
||||
const segments = grouped.tables.map((table) => ({
|
||||
name: table.table,
|
||||
bytes: table.bytes,
|
||||
}));
|
||||
// PostgreSQL catalogs are in the total but not in the tables.
|
||||
const otherBytes =
|
||||
grouped.otherBytes +
|
||||
Math.max(0, totalBytes - grouped.totalBytes - (freeBytes ?? 0));
|
||||
if (otherBytes > 0) {
|
||||
segments.push({
|
||||
name: localize("ui.panel.config.storage.database.other_tables"),
|
||||
bytes: otherBytes,
|
||||
});
|
||||
}
|
||||
const result: Segment[] = segments.map((segment, index) => ({
|
||||
value: segment.bytes,
|
||||
color: getGraphColorByIndex(index, computedStyles),
|
||||
label: html`${segment.name}
|
||||
<span style="color: var(--secondary-text-color)"
|
||||
>${bytesToString(segment.bytes)}</span
|
||||
>`,
|
||||
}));
|
||||
if (freeBytes) {
|
||||
result.push({
|
||||
value: freeBytes,
|
||||
color:
|
||||
"var(--ha-bar-background-color, var(--secondary-background-color))",
|
||||
label: html`${localize("ui.panel.config.storage.database.unused_space")}
|
||||
<span style="color: var(--secondary-text-color)"
|
||||
>${bytesToString(freeBytes)}</span
|
||||
>`,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
);
|
||||
|
||||
// Keyed on the entity registry, not the states, so renames update the
|
||||
// names without rebuilding the rows on every state change.
|
||||
private _rows = memoizeOne(
|
||||
(
|
||||
usage: RecorderDatabaseUsage,
|
||||
entityRegistry: EntityRegistryEntry[],
|
||||
localize: LocalizeFunc
|
||||
): EntityUsageRow[] => {
|
||||
const registered = new Set(
|
||||
entityRegistry.map((entry) => entry.entity_id)
|
||||
);
|
||||
return databaseUsageRows(usage).map((row) => {
|
||||
const stateObj = this._states[row.id];
|
||||
return {
|
||||
...row,
|
||||
// Statistics of external sources (e.g. "sensor:energy") have no entity.
|
||||
hasSettings: stateObj !== undefined || registered.has(row.id),
|
||||
name:
|
||||
row.id === UNKNOWN_ROW_ID
|
||||
? localize("ui.panel.config.storage.database.unknown")
|
||||
: stateObj
|
||||
? computeStateName(stateObj)
|
||||
: row.id,
|
||||
};
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
private _columns = memoizeOne(
|
||||
(
|
||||
localize: LocalizeFunc,
|
||||
locale: FrontendLocaleData,
|
||||
narrow: boolean,
|
||||
hasSizes: boolean
|
||||
): DataTableColumnContainer<EntityUsageRow> => ({
|
||||
name: {
|
||||
title: localize("ui.panel.config.storage.database.columns.entity"),
|
||||
main: true,
|
||||
sortable: true,
|
||||
filterable: true,
|
||||
flex: 3,
|
||||
template: (row) => {
|
||||
const content = html`${row.name}
|
||||
${
|
||||
row.id !== UNKNOWN_ROW_ID && row.name !== row.id
|
||||
? html`<div class="secondary">${row.id}</div>`
|
||||
: nothing
|
||||
}`;
|
||||
// Rendered inside the data table, which styles .row-button.
|
||||
return row.hasSettings
|
||||
? html`<button
|
||||
type="button"
|
||||
class="row-button"
|
||||
data-entity-id=${row.id}
|
||||
@click=${this._openSettings}
|
||||
>
|
||||
${content}
|
||||
</button>`
|
||||
: content;
|
||||
},
|
||||
},
|
||||
id: {
|
||||
title: localize("ui.panel.config.storage.database.columns.entity_id"),
|
||||
filterable: true,
|
||||
hidden: true,
|
||||
},
|
||||
states: {
|
||||
title: localize("ui.panel.config.storage.database.columns.states"),
|
||||
type: "numeric",
|
||||
minWidth: "100px",
|
||||
maxWidth: "100px",
|
||||
sortable: true,
|
||||
// Without sizes the rows are sorted by states instead.
|
||||
direction: hasSizes ? undefined : "desc",
|
||||
hidden: narrow && hasSizes,
|
||||
showNarrow: !hasSizes,
|
||||
template: (row) => formatNumber(row.states, locale),
|
||||
},
|
||||
statistics: {
|
||||
title: localize("ui.panel.config.storage.database.columns.statistics"),
|
||||
type: "numeric",
|
||||
minWidth: "100px",
|
||||
maxWidth: "100px",
|
||||
sortable: true,
|
||||
hidden: narrow,
|
||||
template: (row) => formatNumber(row.statistics, locale),
|
||||
},
|
||||
statistics_short_term: {
|
||||
title: localize(
|
||||
"ui.panel.config.storage.database.columns.statistics_short_term"
|
||||
),
|
||||
type: "numeric",
|
||||
minWidth: "130px",
|
||||
maxWidth: "130px",
|
||||
sortable: true,
|
||||
hidden: narrow,
|
||||
template: (row) => formatNumber(row.statistics_short_term, locale),
|
||||
},
|
||||
bytes: {
|
||||
title: localize("ui.panel.config.storage.database.columns.size"),
|
||||
type: "numeric",
|
||||
minWidth: "100px",
|
||||
maxWidth: "100px",
|
||||
sortable: true,
|
||||
direction: hasSizes ? "desc" : undefined,
|
||||
hidden: !hasSizes,
|
||||
showNarrow: hasSizes,
|
||||
template: (row) => bytesToString(row.bytes ?? 0),
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
// Arrow function: the data table renders the template, not this card.
|
||||
private _openSettings = (
|
||||
ev: HASSDomCurrentTargetEvent<HTMLButtonElement>
|
||||
) => {
|
||||
showMoreInfoDialog(this, {
|
||||
entityId: ev.currentTarget.dataset.entityId!,
|
||||
view: "settings",
|
||||
});
|
||||
};
|
||||
|
||||
private async _load() {
|
||||
this._loading = true;
|
||||
this._error = undefined;
|
||||
try {
|
||||
this._usage = await fetchRecorderDatabaseUsage(this._api);
|
||||
} catch (err: any) {
|
||||
this._error = this._errorMessage(err);
|
||||
} finally {
|
||||
this._loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async _analyze() {
|
||||
this._analyzing = true;
|
||||
this._error = undefined;
|
||||
try {
|
||||
this._usage = await fetchRecorderDatabaseUsage(this._api, true);
|
||||
} catch (err: any) {
|
||||
this._error = this._errorMessage(err);
|
||||
} finally {
|
||||
this._analyzing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private _errorMessage(err: any): string {
|
||||
switch (err.code) {
|
||||
case "recorder_not_ready":
|
||||
return this._localize(
|
||||
"ui.panel.config.storage.database.errors.recorder_not_ready"
|
||||
);
|
||||
case "migration_in_progress":
|
||||
return this._localize(
|
||||
"ui.panel.config.storage.database.errors.migration_in_progress"
|
||||
);
|
||||
default:
|
||||
return err.message || err.code || String(err);
|
||||
}
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
ha-card {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.card-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--ha-space-4);
|
||||
}
|
||||
.card-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-3);
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
.summary {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: var(--ha-space-2);
|
||||
}
|
||||
.total {
|
||||
font-size: var(--ha-font-size-2xl);
|
||||
}
|
||||
.generated,
|
||||
.description {
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
.description {
|
||||
margin: 0;
|
||||
}
|
||||
.table {
|
||||
height: 480px;
|
||||
}
|
||||
ha-data-table {
|
||||
--data-table-border-width: 0;
|
||||
height: 100%;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"storage-database-card": StorageDatabaseCard;
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import { DirtyStateProviderMixin } from "../../../mixins/dirty-state-provider-mi
|
||||
import { haStyleDialog } from "../../../resources/styles";
|
||||
import type { HomeAssistant, ValueChangedEvent } from "../../../types";
|
||||
import "../../../components/entity/ha-favorites-editor";
|
||||
import { computeFavoriteCardsSize } from "../../lovelace/strategies/helpers/favorite-cards";
|
||||
import "../components/home-shortcuts-editor";
|
||||
import type { EditHomeDialogParams } from "./show-dialog-edit-home";
|
||||
|
||||
@@ -27,9 +28,9 @@ interface EditorState {
|
||||
shortcuts: ShortcutItem[];
|
||||
}
|
||||
|
||||
// The common-controls strategy caps the section at 8 (or the favorites count,
|
||||
// whichever is larger); once favorites reach the cap, predictions never render
|
||||
// so the suggested-entities toggle has no effect.
|
||||
// The common-controls strategy caps the section at 8 slots (or the slots the
|
||||
// favorites use, whichever is larger); once favorites reach the cap,
|
||||
// predictions never render so the suggested-entities toggle has no effect.
|
||||
const SUGGESTED_ENTITIES_CAP = 8;
|
||||
|
||||
const WELCOME_SCHEMA: HaFormSchema[] = [
|
||||
@@ -140,7 +141,8 @@ export class DialogEditHome
|
||||
show_suggested_entities: this._state.show_suggested_entities,
|
||||
}}
|
||||
.schema=${this._suggestedSchema(
|
||||
this._state.favorite_entities.length >= SUGGESTED_ENTITIES_CAP
|
||||
computeFavoriteCardsSize(this._state.favorite_entities) >=
|
||||
SUGGESTED_ENTITIES_CAP
|
||||
)}
|
||||
.computeLabel=${this._computeSuggestedLabel}
|
||||
.computeHelper=${this._computeSuggestedHelper}
|
||||
@@ -213,7 +215,8 @@ export class DialogEditHome
|
||||
|
||||
private _computeSuggestedHelper = (): string => {
|
||||
const favoritesFull =
|
||||
(this._state?.favorite_entities.length ?? 0) >= SUGGESTED_ENTITIES_CAP;
|
||||
computeFavoriteCardsSize(this._state?.favorite_entities ?? []) >=
|
||||
SUGGESTED_ENTITIES_CAP;
|
||||
return this.hass.localize(
|
||||
favoritesFull
|
||||
? "ui.panel.home.editor.suggested_entities_disabled_description"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { css, html, LitElement, nothing, unsafeCSS } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
@@ -14,6 +14,7 @@ import { computeAttributeNameDisplay } from "../../../common/entity/compute_attr
|
||||
import { computeDomain } from "../../../common/entity/compute_domain";
|
||||
import { stateColorCss } from "../../../common/entity/state_color";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-control-slider";
|
||||
import type { CoverEntity } from "../../../data/cover";
|
||||
import { coverSupportsTiltPosition } from "../../../data/cover";
|
||||
import {
|
||||
@@ -24,7 +25,6 @@ import {
|
||||
import { UNAVAILABLE } from "../../../data/entity/entity";
|
||||
import { DOMAIN_ATTRIBUTES_UNITS } from "../../../data/entity/entity_attributes";
|
||||
import type { FrontendLocaleData } from "../../../data/translation";
|
||||
import { generateTiltSliderTrackBackgroundGradient } from "../../../state-control/cover/ha-state-control-cover-tilt-position";
|
||||
import type {
|
||||
HomeAssistant,
|
||||
HomeAssistantApi,
|
||||
@@ -37,6 +37,33 @@ import type {
|
||||
LovelaceCardFeatureContext,
|
||||
} from "./types";
|
||||
|
||||
function generateTiltSliderTrackBackgroundGradient() {
|
||||
const count = 24;
|
||||
const minStrokeWidth = 0.2;
|
||||
const gradient: [number, string][] = [];
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const stopOffset1 = i / count;
|
||||
const stopOffset2 =
|
||||
stopOffset1 +
|
||||
(i / count ** 2) * (1 - minStrokeWidth) +
|
||||
minStrokeWidth / count;
|
||||
|
||||
if (i !== 0) {
|
||||
gradient.push([stopOffset1, "transparent"]);
|
||||
}
|
||||
gradient.push([stopOffset1, "var(--control-slider-color)"]);
|
||||
gradient.push([stopOffset2, "var(--control-slider-color)"]);
|
||||
gradient.push([stopOffset2, "transparent"]);
|
||||
}
|
||||
|
||||
return unsafeCSS(
|
||||
gradient
|
||||
.map(([stop, color]) => `${color} ${(stop as number) * 100}%`)
|
||||
.join(", ")
|
||||
);
|
||||
}
|
||||
|
||||
const GRADIENT = generateTiltSliderTrackBackgroundGradient();
|
||||
|
||||
const supportsCoverTiltPositionCardFeatureFromState = (
|
||||
|
||||
@@ -159,7 +159,11 @@ class HuiEnergyCarbonGaugeCard extends LitElement implements LovelaceCard {
|
||||
id="info"
|
||||
.path=${mdiInformationOutline}
|
||||
></ha-svg-icon>
|
||||
<ha-tooltip for="info" placement="left">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="info"
|
||||
placement="left"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.carbon_consumed_gauge.card_indicates_energy_used"
|
||||
)}
|
||||
|
||||
@@ -129,7 +129,11 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
|
||||
<span class="imported" id="eq-imported">
|
||||
${fmtEnergy(imported)}
|
||||
</span>
|
||||
<ha-tooltip for="eq-imported" placement="top">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="eq-imported"
|
||||
placement="top"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.grid_balance.imported",
|
||||
{ value: fmt(imported) }
|
||||
@@ -139,7 +143,11 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
|
||||
<span class="exported" id="eq-exported">
|
||||
${fmtEnergy(exported)}
|
||||
</span>
|
||||
<ha-tooltip for="eq-exported" placement="top">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="eq-exported"
|
||||
placement="top"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.grid_balance.exported",
|
||||
{ value: fmt(exported) }
|
||||
@@ -152,7 +160,11 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
|
||||
>
|
||||
${fmtEnergy(net)}
|
||||
</span>
|
||||
<ha-tooltip for="eq-net" placement="top">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="eq-net"
|
||||
placement="top"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
`ui.panel.lovelace.cards.energy.grid_balance.net_${isConsumption ? "import" : "export"}`,
|
||||
{ value: fmt(Math.abs(net)) }
|
||||
@@ -168,7 +180,11 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
|
||||
class="bar-fill return"
|
||||
style="width: ${leftPercent}%"
|
||||
></div>
|
||||
<ha-tooltip for="bar-exported" placement="top">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="bar-exported"
|
||||
placement="top"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.grid_balance.exported",
|
||||
{ value: fmt(exported) }
|
||||
@@ -181,7 +197,11 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
|
||||
class="bar-net return"
|
||||
style="width: ${netBarWidth}%"
|
||||
></div>
|
||||
<ha-tooltip for="bar-net-left" placement="top">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="bar-net-left"
|
||||
placement="top"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.grid_balance.net_export",
|
||||
{
|
||||
@@ -199,7 +219,11 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
|
||||
class="bar-fill consumption"
|
||||
style="width: ${rightPercent}%"
|
||||
></div>
|
||||
<ha-tooltip for="bar-imported" placement="top">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="bar-imported"
|
||||
placement="top"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.grid_balance.imported",
|
||||
{ value: fmt(imported) }
|
||||
@@ -212,7 +236,11 @@ class HuiEnergyGridBalanceCard extends LitElement implements LovelaceCard {
|
||||
class="bar-net consumption"
|
||||
style="width: ${netBarWidth}%"
|
||||
></div>
|
||||
<ha-tooltip for="bar-net-right" placement="top">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="bar-net-right"
|
||||
placement="top"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.grid_balance.net_import",
|
||||
{
|
||||
|
||||
@@ -126,7 +126,11 @@ class HuiEnergyGridGaugeCard extends LitElement implements LovelaceCard {
|
||||
id="info"
|
||||
.path=${mdiInformationOutline}
|
||||
></ha-svg-icon>
|
||||
<ha-tooltip for="info" placement="left">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="info"
|
||||
placement="left"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.grid_neutrality_gauge.energy_dependency"
|
||||
)}
|
||||
|
||||
@@ -125,7 +125,11 @@ class HuiEnergySelfSufficiencyGaugeCard
|
||||
id="info"
|
||||
.path=${mdiInformationOutline}
|
||||
></ha-svg-icon>
|
||||
<ha-tooltip for="info" placement="left">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="info"
|
||||
placement="left"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.self_sufficiency_gauge.card_indicates_self_sufficiency_quota"
|
||||
)}
|
||||
|
||||
@@ -114,7 +114,11 @@ class HuiEnergySolarGaugeCard extends LitElement implements LovelaceCard {
|
||||
id="info"
|
||||
.path=${mdiInformationOutline}
|
||||
></ha-svg-icon>
|
||||
<ha-tooltip for="info" placement="left">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="info"
|
||||
placement="left"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.solar_consumed_gauge.card_indicates_solar_energy_used"
|
||||
)}
|
||||
|
||||
@@ -255,46 +255,16 @@ export class HuiEnergySourcesTableCard
|
||||
<th class="mdc-data-table__cell cell-source" scope="row" .title=${label}>
|
||||
${label}
|
||||
</th>
|
||||
${
|
||||
compare
|
||||
? html`<td class="mdc-data-table__cell mdc-data-table__cell--numeric">
|
||||
${formattedCompareEnergy}
|
||||
</td>
|
||||
${
|
||||
showCosts
|
||||
? html`<td
|
||||
class="mdc-data-table__cell mdc-data-table__cell--numeric"
|
||||
>
|
||||
${
|
||||
compareCost !== null
|
||||
? formatNumber(compareCost, this._i18n.locale, {
|
||||
style: "currency",
|
||||
currency: this._hassConfig.currency!,
|
||||
})
|
||||
: ""
|
||||
}
|
||||
</td>`
|
||||
: ""
|
||||
}`
|
||||
: ""
|
||||
}
|
||||
<td class="mdc-data-table__cell mdc-data-table__cell--numeric">
|
||||
${formattedEnergy}
|
||||
</td>
|
||||
${this._renderValueCell(
|
||||
formattedEnergy,
|
||||
compare ? formattedCompareEnergy : undefined
|
||||
)}
|
||||
${
|
||||
showCosts
|
||||
? html` <td
|
||||
class="mdc-data-table__cell mdc-data-table__cell--numeric"
|
||||
>
|
||||
${
|
||||
cost !== null
|
||||
? formatNumber(cost, this._i18n.locale, {
|
||||
style: "currency",
|
||||
currency: this._hassConfig.currency!,
|
||||
})
|
||||
: ""
|
||||
}
|
||||
</td>`
|
||||
? this._renderValueCell(
|
||||
this._formatCost(cost),
|
||||
compare ? this._formatCost(compareCost) : undefined
|
||||
)
|
||||
: ""
|
||||
}
|
||||
</tr>`;
|
||||
@@ -351,49 +321,37 @@ export class HuiEnergySourcesTableCard
|
||||
<th class="mdc-data-table__cell cell-source" scope="row" .title=${label}>
|
||||
${label}
|
||||
</th>
|
||||
${
|
||||
compare
|
||||
? html`<td class="mdc-data-table__cell mdc-data-table__cell--numeric">
|
||||
${formattedCompareEnergy}
|
||||
</td>
|
||||
${
|
||||
showCosts
|
||||
? html`<td
|
||||
class="mdc-data-table__cell mdc-data-table__cell--numeric"
|
||||
>
|
||||
${
|
||||
compareCost !== null
|
||||
? formatNumber(compareCost, this._i18n.locale, {
|
||||
style: "currency",
|
||||
currency: this._hassConfig.currency!,
|
||||
})
|
||||
: ""
|
||||
}
|
||||
</td>`
|
||||
: ""
|
||||
}`
|
||||
: ""
|
||||
}
|
||||
<td class="mdc-data-table__cell mdc-data-table__cell--numeric">
|
||||
${formattedEnergy}
|
||||
</td>
|
||||
${this._renderValueCell(
|
||||
formattedEnergy,
|
||||
compare ? formattedCompareEnergy : undefined
|
||||
)}
|
||||
${
|
||||
showCosts
|
||||
? html`<td class="mdc-data-table__cell mdc-data-table__cell--numeric">
|
||||
${
|
||||
cost !== null
|
||||
? formatNumber(cost, this._i18n.locale, {
|
||||
style: "currency",
|
||||
currency: this._hassConfig.currency!,
|
||||
})
|
||||
: ""
|
||||
}
|
||||
</td>`
|
||||
? this._renderValueCell(
|
||||
this._formatCost(cost),
|
||||
compare ? this._formatCost(compareCost) : undefined
|
||||
)
|
||||
: ""
|
||||
}
|
||||
</tr>`;
|
||||
}
|
||||
|
||||
private _formatCost(cost: number | null): string {
|
||||
return cost !== null
|
||||
? formatNumber(cost, this._i18n.locale, {
|
||||
style: "currency",
|
||||
currency: this._hassConfig.currency!,
|
||||
})
|
||||
: "";
|
||||
}
|
||||
|
||||
private _renderValueCell(value: string, compareValue: string | undefined) {
|
||||
return html`<td class="mdc-data-table__cell mdc-data-table__cell--numeric">
|
||||
<div>${value}</div>
|
||||
${compareValue ? html`<div class="compare">${compareValue}</div>` : nothing}
|
||||
</td>`;
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this._config) {
|
||||
return nothing;
|
||||
@@ -731,32 +689,6 @@ export class HuiEnergySourcesTableCard
|
||||
"ui.panel.lovelace.cards.energy.energy_sources_table.source"
|
||||
)}
|
||||
</th>
|
||||
${
|
||||
compare
|
||||
? html`<th
|
||||
class="mdc-data-table__header-cell mdc-data-table__header-cell--numeric"
|
||||
role="columnheader"
|
||||
scope="col"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.energy_sources_table.previous_energy"
|
||||
)}
|
||||
</th>
|
||||
${
|
||||
showCosts
|
||||
? html`<th
|
||||
class="mdc-data-table__header-cell mdc-data-table__header-cell--numeric"
|
||||
role="columnheader"
|
||||
scope="col"
|
||||
>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.energy_sources_table.previous_cost"
|
||||
)}
|
||||
</th>`
|
||||
: ""
|
||||
}`
|
||||
: ""
|
||||
}
|
||||
<th
|
||||
class="mdc-data-table__header-cell mdc-data-table__header-cell--numeric"
|
||||
role="columnheader"
|
||||
@@ -765,6 +697,15 @@ export class HuiEnergySourcesTableCard
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.energy_sources_table.energy"
|
||||
)}
|
||||
${
|
||||
compare
|
||||
? html`<div class="compare">
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.energy_sources_table.previous_energy"
|
||||
)}
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
</th>
|
||||
${
|
||||
showCosts
|
||||
@@ -776,6 +717,15 @@ export class HuiEnergySourcesTableCard
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.energy_sources_table.cost"
|
||||
)}
|
||||
${
|
||||
compare
|
||||
? html`<div class="compare">
|
||||
${this._i18n.localize(
|
||||
"ui.panel.lovelace.cards.energy.energy_sources_table.previous_cost"
|
||||
)}
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
</th>`
|
||||
: ""
|
||||
}
|
||||
@@ -1248,6 +1198,14 @@ export class HuiEnergySourcesTableCard
|
||||
white-space: nowrap;
|
||||
width: 1%;
|
||||
}
|
||||
.compare {
|
||||
color: var(--secondary-text-color);
|
||||
font-size: var(--ha-font-size-s);
|
||||
}
|
||||
.mdc-data-table__header-cell .compare {
|
||||
font-weight: var(--ha-font-weight-normal);
|
||||
white-space: normal;
|
||||
}
|
||||
.mdc-data-table__header-cell--numeric {
|
||||
text-align: var(--float-end);
|
||||
white-space: nowrap;
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
getSummedData,
|
||||
} from "../../../data/energy";
|
||||
import { EnergyCollectionController } from "../../../data/energy-collection-controller";
|
||||
import { filterGroupsWithListedMembers } from "../../../data/group";
|
||||
import type { ActionHandlerEvent } from "../../../data/lovelace/action_handler";
|
||||
import type {
|
||||
HomeAssistantConfig,
|
||||
@@ -176,7 +177,10 @@ export class HuiHomeSummaryCard extends LitElement implements LovelaceCard {
|
||||
generateEntityFilter(states, entities, devices, areas, floors, filter)
|
||||
);
|
||||
|
||||
const lightEntities = findEntities(allEntities, lightsFilters);
|
||||
const lightEntities = filterGroupsWithListedMembers(
|
||||
findEntities(allEntities, lightsFilters),
|
||||
states
|
||||
);
|
||||
|
||||
const onLights = lightEntities.filter((entityId) => {
|
||||
const s = states[entityId]?.state;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, eventOptions, property, query } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { DOMAINS_INPUT_ROW } from "../../../common/const";
|
||||
@@ -36,6 +36,10 @@ export class HuiGenericEntityRow extends LitElement {
|
||||
@property({ attribute: "catch-interaction", type: Boolean })
|
||||
public catchInteraction?;
|
||||
|
||||
@query(".row > slot") private _controlSlot?: HTMLSlotElement;
|
||||
|
||||
private _pressedControl = false;
|
||||
|
||||
protected render() {
|
||||
if (!this.hass || !this.config) {
|
||||
return nothing;
|
||||
@@ -64,6 +68,8 @@ export class HuiGenericEntityRow extends LitElement {
|
||||
return html`
|
||||
<div
|
||||
class="row ${classMap({ pointer })}"
|
||||
@pointerdown=${this._handlePointerDown}
|
||||
@click=${this._handleClick}
|
||||
@action=${this._handleAction}
|
||||
.actionHandler=${actionHandler({
|
||||
hasHold: hasAction(this.config!.hold_action),
|
||||
@@ -138,6 +144,22 @@ export class HuiGenericEntityRow extends LitElement {
|
||||
);
|
||||
}
|
||||
|
||||
private _handlePointerDown(ev: PointerEvent) {
|
||||
this._pressedControl = this._isControlEvent(ev);
|
||||
}
|
||||
|
||||
@eventOptions({ capture: true })
|
||||
private _handleClick(ev: MouseEvent) {
|
||||
if (this._pressedControl && ev.detail > 0 && !this._isControlEvent(ev)) {
|
||||
ev.stopImmediatePropagation();
|
||||
}
|
||||
this._pressedControl = false;
|
||||
}
|
||||
|
||||
private _isControlEvent(ev: Event) {
|
||||
return !!this._controlSlot && ev.composedPath().includes(this._controlSlot);
|
||||
}
|
||||
|
||||
private _handleAction(ev: ActionHandlerEvent) {
|
||||
handleAction(this, this.hass!, this.config!, ev.detail.action!);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
export {
|
||||
computeCssColor,
|
||||
computeCssVariableName,
|
||||
} from "../../common/color/compute-color";
|
||||
export { showEnterCodeDialog } from "../../dialogs/enter-code/show-enter-code-dialog";
|
||||
export {
|
||||
showAlertDialog,
|
||||
|
||||
@@ -5,6 +5,16 @@ import type {
|
||||
TileCardConfig,
|
||||
} from "../../cards/types";
|
||||
|
||||
// The camera card takes the grid area of two tiles.
|
||||
export const computeFavoriteCardSize = (entityId: string): number =>
|
||||
computeDomain(entityId) === "camera" ? 2 : 1;
|
||||
|
||||
export const computeFavoriteCardsSize = (entityIds: string[]): number =>
|
||||
entityIds.reduce(
|
||||
(size, entityId) => size + computeFavoriteCardSize(entityId),
|
||||
0
|
||||
);
|
||||
|
||||
export const computeFavoriteCardConfig = (
|
||||
entityId: string
|
||||
): LovelaceCardConfig => {
|
||||
|
||||
@@ -36,7 +36,10 @@ import type {
|
||||
TileCardConfig,
|
||||
UpdatesCardConfig,
|
||||
} from "../../cards/types";
|
||||
import { computeFavoriteCardConfig } from "../helpers/favorite-cards";
|
||||
import {
|
||||
computeFavoriteCardConfig,
|
||||
computeFavoriteCardsSize,
|
||||
} from "../helpers/favorite-cards";
|
||||
import { findMaintenanceEntities } from "../../../maintenance/strategies/maintenance-view-strategy";
|
||||
import {
|
||||
computeDefaultSecurityAlertVisibility,
|
||||
@@ -290,7 +293,10 @@ export class HomeOverviewViewStrategy extends ReactiveElement {
|
||||
const favoriteEntities = (config.favorite_entities || []).filter(
|
||||
(entityId) => hass.states[entityId] !== undefined
|
||||
);
|
||||
const maxCommonControls = Math.max(8, favoriteEntities.length);
|
||||
const maxCommonControls = Math.max(
|
||||
8,
|
||||
computeFavoriteCardsSize(favoriteEntities)
|
||||
);
|
||||
|
||||
const favoritesHeadingCard: HeadingCardConfig = {
|
||||
type: "heading",
|
||||
|
||||
+32
-11
@@ -6,7 +6,11 @@ import { getCommonControlsUsagePrediction } from "../../../../data/usage_predict
|
||||
import type { HomeAssistant } from "../../../../types";
|
||||
import type { HeadingCardConfig } from "../../cards/types";
|
||||
import type { Condition } from "../../common/validate-condition";
|
||||
import { computeFavoriteCardConfig } from "../helpers/favorite-cards";
|
||||
import {
|
||||
computeFavoriteCardConfig,
|
||||
computeFavoriteCardSize,
|
||||
computeFavoriteCardsSize,
|
||||
} from "../helpers/favorite-cards";
|
||||
import type {
|
||||
LovelaceStrategyDependency,
|
||||
LovelaceStrategyEditor,
|
||||
@@ -14,6 +18,19 @@ import type {
|
||||
|
||||
const DEFAULT_LIMIT = 8;
|
||||
|
||||
// The limit counts tile-sized slots, so a camera uses two of them.
|
||||
const fitToLimit = (entities: string[], limit: number): string[] => {
|
||||
const result: string[] = [];
|
||||
let size = 0;
|
||||
for (const entity of entities) {
|
||||
const entitySize = computeFavoriteCardSize(entity);
|
||||
if (size + entitySize > limit) continue;
|
||||
result.push(entity);
|
||||
size += entitySize;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
export interface CommonControlsSectionStrategyConfig {
|
||||
type: "common-controls";
|
||||
limit?: number;
|
||||
@@ -69,15 +86,19 @@ export class CommonControlsSectionStrategy extends ReactiveElement {
|
||||
(entity) => entity in hass.states
|
||||
);
|
||||
|
||||
// Pinned entities already fill the section, skip the prediction call.
|
||||
if (includedEntities.length >= limit) {
|
||||
section.cards!.push(
|
||||
...includedEntities.slice(0, limit).map(computeFavoriteCardConfig)
|
||||
);
|
||||
// Pinned entities always show. Predictions only fill the free slots.
|
||||
const freeSlots = limit - computeFavoriteCardsSize(includedEntities);
|
||||
const predictionsLoaded = isComponentLoaded(
|
||||
hass.config,
|
||||
"usage_prediction"
|
||||
);
|
||||
|
||||
if (includedEntities.length > 0 && (freeSlots <= 0 || !predictionsLoaded)) {
|
||||
section.cards!.push(...includedEntities.map(computeFavoriteCardConfig));
|
||||
return section;
|
||||
}
|
||||
|
||||
if (!isComponentLoaded(hass.config, "usage_prediction")) {
|
||||
if (!predictionsLoaded) {
|
||||
section.cards!.push({
|
||||
type: "markdown",
|
||||
content: hass.localize(
|
||||
@@ -104,10 +125,10 @@ export class CommonControlsSectionStrategy extends ReactiveElement {
|
||||
}
|
||||
);
|
||||
|
||||
const entities = [...includedEntities, ...predictedEntities].slice(
|
||||
0,
|
||||
limit
|
||||
);
|
||||
const entities = [
|
||||
...includedEntities,
|
||||
...fitToLimit(predictedEntities, freeSlots),
|
||||
];
|
||||
|
||||
if (entities.length === 0) {
|
||||
section.cards!.push({
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { css } from "lit";
|
||||
|
||||
export const coverDrawingStyles = css`
|
||||
:host {
|
||||
--cover-drawing-sky-top: #9ed3f6;
|
||||
--cover-drawing-sky-bottom: #3f97e6;
|
||||
--cover-drawing-sky-warm: #ffffff;
|
||||
--cover-drawing-sky-cool: #2b86d9;
|
||||
--cover-drawing-frame: color-mix(
|
||||
in srgb,
|
||||
var(--disabled-color) 20%,
|
||||
var(--ha-dialog-surface-background, var(--card-background-color))
|
||||
);
|
||||
--cover-drawing-frame-edge: #e6e0d8;
|
||||
--cover-drawing-fabric: #e1e1e1;
|
||||
--cover-drawing-fabric-edge: #bdbdbd;
|
||||
--cover-drawing-seam: #bdbdbd;
|
||||
--cover-drawing-lift: #f5f5f5;
|
||||
--cover-drawing-stripe: #ffffff;
|
||||
--cover-drawing-slot: #cfe8fb;
|
||||
--cover-drawing-ghost: #e1e1e1;
|
||||
--cover-drawing-metal: #6f7a84;
|
||||
--cover-drawing-grass-top: #a8d49a;
|
||||
--cover-drawing-grass-bottom: #7fb071;
|
||||
--cover-drawing-handle: #ffffff;
|
||||
--cover-drawing-gauge: rgba(0, 0, 0, 0.12);
|
||||
--cover-drawing-handle-shadow: rgba(0, 0, 0, 0.28);
|
||||
}
|
||||
.control.dark {
|
||||
--cover-drawing-sky-top: #1a2140;
|
||||
--cover-drawing-sky-bottom: #2c5490;
|
||||
--cover-drawing-sky-warm: #3e59a6;
|
||||
--cover-drawing-sky-cool: #0a1733;
|
||||
--cover-drawing-frame-edge: #3a4149;
|
||||
--cover-drawing-fabric: #5a6069;
|
||||
--cover-drawing-fabric-edge: #858e99;
|
||||
--cover-drawing-seam: #464b53;
|
||||
--cover-drawing-lift: #6e757e;
|
||||
--cover-drawing-stripe: #676e78;
|
||||
--cover-drawing-slot: #3b5f96;
|
||||
--cover-drawing-ghost: #9aa3ad;
|
||||
--cover-drawing-metal: #9aa5b0;
|
||||
--cover-drawing-grass-top: #3f6b45;
|
||||
--cover-drawing-grass-bottom: #2b4a31;
|
||||
--cover-drawing-handle: #f2f4f6;
|
||||
--cover-drawing-gauge: rgba(0, 0, 0, 0.28);
|
||||
--cover-drawing-handle-shadow: rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
.sky-top {
|
||||
stop-color: var(--cover-drawing-sky-top);
|
||||
}
|
||||
.sky-bottom {
|
||||
stop-color: var(--cover-drawing-sky-bottom);
|
||||
}
|
||||
.sky-warm {
|
||||
stop-color: var(--cover-drawing-sky-warm);
|
||||
}
|
||||
.sky-cool {
|
||||
stop-color: var(--cover-drawing-sky-cool);
|
||||
}
|
||||
.grass-top {
|
||||
stop-color: var(--cover-drawing-grass-top);
|
||||
}
|
||||
.grass-bottom {
|
||||
stop-color: var(--cover-drawing-grass-bottom);
|
||||
}
|
||||
.frame {
|
||||
fill: var(--cover-drawing-frame);
|
||||
}
|
||||
.opening-edge {
|
||||
fill: none;
|
||||
stroke: var(--cover-drawing-frame);
|
||||
stroke-width: 3;
|
||||
}
|
||||
.fabric {
|
||||
fill: var(--cover-drawing-fabric);
|
||||
}
|
||||
.stripe {
|
||||
fill: var(--cover-drawing-stripe);
|
||||
}
|
||||
.bottom-bar {
|
||||
fill: var(--cover-drawing-fabric-edge);
|
||||
}
|
||||
.seam,
|
||||
.cord {
|
||||
fill: var(--cover-drawing-seam);
|
||||
}
|
||||
.seam.faint {
|
||||
opacity: 0.5;
|
||||
}
|
||||
.cord {
|
||||
opacity: 0.85;
|
||||
}
|
||||
.lift {
|
||||
fill: var(--cover-drawing-lift);
|
||||
opacity: 0.75;
|
||||
}
|
||||
.slat-line {
|
||||
stroke: var(--cover-drawing-fabric-edge);
|
||||
}
|
||||
.slot {
|
||||
fill: var(--cover-drawing-slot);
|
||||
}
|
||||
.panel-shadow {
|
||||
fill: #000;
|
||||
}
|
||||
.ghost {
|
||||
fill: var(--cover-drawing-ghost);
|
||||
}
|
||||
.target-line {
|
||||
fill: none;
|
||||
stroke: var(--cover-drawing-handle);
|
||||
stroke-width: 2;
|
||||
stroke-linecap: round;
|
||||
filter: drop-shadow(0 1px 1.5px var(--cover-drawing-handle-shadow));
|
||||
}
|
||||
.metal {
|
||||
fill: var(--cover-drawing-metal);
|
||||
}
|
||||
.gauge-rail {
|
||||
fill: var(--cover-drawing-gauge);
|
||||
}
|
||||
.gauge-ball {
|
||||
fill: var(--cover-drawing-handle);
|
||||
filter: drop-shadow(0 0.5px 1.5px var(--cover-drawing-handle-shadow));
|
||||
}
|
||||
.pill-handle {
|
||||
fill: var(--cover-drawing-handle);
|
||||
filter: drop-shadow(0 1px 2px var(--cover-drawing-handle-shadow));
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { ReactiveControllerHost } from "lit";
|
||||
import type {
|
||||
CoverCommand,
|
||||
CoverControlMode,
|
||||
CoverEntity,
|
||||
CoverRequest,
|
||||
} from "../../data/cover";
|
||||
import { coverCurrentValue, isMoving } from "../../data/cover";
|
||||
|
||||
const roundedCurrentValue = (stateObj: CoverEntity, mode: CoverControlMode) => {
|
||||
const value = coverCurrentValue(stateObj, mode);
|
||||
return value === undefined ? undefined : Math.round(value);
|
||||
};
|
||||
|
||||
const END_VALUES = { open: 100, close: 0 };
|
||||
|
||||
export class CoverRequestController {
|
||||
private _request?: CoverRequest;
|
||||
|
||||
private _startValue?: number;
|
||||
|
||||
private _moving = false;
|
||||
|
||||
constructor(private readonly _host: ReactiveControllerHost) {}
|
||||
|
||||
public get request(): CoverRequest | undefined {
|
||||
return this._request;
|
||||
}
|
||||
|
||||
public clear(): void {
|
||||
this._setRequest(undefined);
|
||||
}
|
||||
|
||||
public commandSent(command: CoverCommand, stateObj: CoverEntity): void {
|
||||
const { mode } = command;
|
||||
if (command.action === "stop") {
|
||||
if (this._request?.mode === mode) {
|
||||
this._setRequest(undefined);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const value =
|
||||
command.action === "set" ? command.value : END_VALUES[command.action];
|
||||
const startValue = roundedCurrentValue(stateObj, mode);
|
||||
this._setRequest(startValue === value ? undefined : { mode, value });
|
||||
this._startValue = startValue;
|
||||
}
|
||||
|
||||
public stateChanged(stateObj: CoverEntity): void {
|
||||
const request = this._request;
|
||||
if (!request) {
|
||||
return;
|
||||
}
|
||||
const value = roundedCurrentValue(stateObj, request.mode);
|
||||
if (value === request.value) {
|
||||
this._setRequest(undefined);
|
||||
return;
|
||||
}
|
||||
if (isMoving(stateObj)) {
|
||||
this._moving = true;
|
||||
return;
|
||||
}
|
||||
if (this._moving || (value !== undefined && value !== this._startValue)) {
|
||||
this._setRequest(undefined);
|
||||
}
|
||||
}
|
||||
|
||||
private _setRequest(request: CoverRequest | undefined) {
|
||||
this._request = request;
|
||||
this._moving = false;
|
||||
this._host.requestUpdate();
|
||||
}
|
||||
}
|
||||
@@ -1,302 +0,0 @@
|
||||
import { mdiArrowBottomLeft, mdiArrowTopRight, mdiStop } from "@mdi/js";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { repeat } from "lit/directives/repeat";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import {
|
||||
computeCloseIcon,
|
||||
computeOpenIcon,
|
||||
} from "../../common/entity/cover_icon";
|
||||
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
import { supportsFeature } from "../../common/entity/supports-feature";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import "../../components/ha-control-button";
|
||||
import "../../components/ha-control-button-group";
|
||||
import "../../components/ha-control-slider";
|
||||
import "../../components/ha-svg-icon";
|
||||
import { apiContext } from "../../data/context";
|
||||
import type { CoverEntity } from "../../data/cover";
|
||||
import {
|
||||
CoverEntityFeature,
|
||||
canClose,
|
||||
canCloseTilt,
|
||||
canOpen,
|
||||
canOpenTilt,
|
||||
canStop,
|
||||
canStopTilt,
|
||||
} from "../../data/cover";
|
||||
import type { HomeAssistantApi } from "../../types";
|
||||
|
||||
type CoverButton =
|
||||
"open" | "close" | "stop" | "open-tilt" | "close-tilt" | "none";
|
||||
|
||||
interface CoverLayout {
|
||||
type: "line" | "cross";
|
||||
buttons: CoverButton[];
|
||||
}
|
||||
|
||||
export const getCoverLayout = memoizeOne(
|
||||
(stateObj: CoverEntity): CoverLayout => {
|
||||
const supportsOpen = supportsFeature(stateObj, CoverEntityFeature.OPEN);
|
||||
const supportsClose = supportsFeature(stateObj, CoverEntityFeature.CLOSE);
|
||||
const supportsStop = supportsFeature(stateObj, CoverEntityFeature.STOP);
|
||||
const supportsOpenTilt = supportsFeature(
|
||||
stateObj,
|
||||
CoverEntityFeature.OPEN_TILT
|
||||
);
|
||||
const supportsCloseTilt = supportsFeature(
|
||||
stateObj,
|
||||
CoverEntityFeature.CLOSE_TILT
|
||||
);
|
||||
const supportsStopTilt = supportsFeature(
|
||||
stateObj,
|
||||
CoverEntityFeature.STOP_TILT
|
||||
);
|
||||
|
||||
if (
|
||||
(supportsOpen || supportsClose) &&
|
||||
(supportsOpenTilt || supportsCloseTilt)
|
||||
) {
|
||||
return {
|
||||
type: "cross",
|
||||
buttons: [
|
||||
supportsOpen ? "open" : "none",
|
||||
supportsCloseTilt ? "close-tilt" : "none",
|
||||
supportsStop || supportsStopTilt ? "stop" : "none",
|
||||
supportsOpenTilt ? "open-tilt" : "none",
|
||||
supportsClose ? "close" : "none",
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (supportsOpen || supportsClose) {
|
||||
const buttons: CoverButton[] = [];
|
||||
if (supportsOpen) buttons.push("open");
|
||||
if (supportsStop) buttons.push("stop");
|
||||
if (supportsClose) buttons.push("close");
|
||||
return {
|
||||
type: "line",
|
||||
buttons,
|
||||
};
|
||||
}
|
||||
|
||||
if (supportsOpenTilt || supportsCloseTilt) {
|
||||
const buttons: CoverButton[] = [];
|
||||
if (supportsOpenTilt) buttons.push("open-tilt");
|
||||
if (supportsStopTilt) buttons.push("stop");
|
||||
if (supportsCloseTilt) buttons.push("close-tilt");
|
||||
return {
|
||||
type: "line",
|
||||
buttons,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: "line",
|
||||
buttons: [],
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
@customElement("ha-state-control-cover-buttons")
|
||||
export class HaStateControlCoverButtons extends LitElement {
|
||||
@state()
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: HomeAssistantApi;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@property({ attribute: false }) public stateObj!: CoverEntity;
|
||||
|
||||
private _onOpenTap(ev): void {
|
||||
ev.stopPropagation();
|
||||
this._api.callService("cover", "open_cover", {
|
||||
entity_id: this.stateObj!.entity_id,
|
||||
});
|
||||
}
|
||||
|
||||
private _onCloseTap(ev): void {
|
||||
ev.stopPropagation();
|
||||
this._api.callService("cover", "close_cover", {
|
||||
entity_id: this.stateObj!.entity_id,
|
||||
});
|
||||
}
|
||||
|
||||
private _onOpenTiltTap(ev): void {
|
||||
ev.stopPropagation();
|
||||
this._api.callService("cover", "open_cover_tilt", {
|
||||
entity_id: this.stateObj!.entity_id,
|
||||
});
|
||||
}
|
||||
|
||||
private _onCloseTiltTap(ev): void {
|
||||
ev.stopPropagation();
|
||||
this._api.callService("cover", "close_cover_tilt", {
|
||||
entity_id: this.stateObj!.entity_id,
|
||||
});
|
||||
}
|
||||
|
||||
private _onStopTap(ev): void {
|
||||
ev.stopPropagation();
|
||||
if (supportsFeature(this.stateObj, CoverEntityFeature.STOP)) {
|
||||
this._api.callService("cover", "stop_cover", {
|
||||
entity_id: this.stateObj!.entity_id,
|
||||
});
|
||||
}
|
||||
if (supportsFeature(this.stateObj, CoverEntityFeature.STOP_TILT)) {
|
||||
this._api.callService("cover", "stop_cover_tilt", {
|
||||
entity_id: this.stateObj!.entity_id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
protected renderButton(button: CoverButton | undefined) {
|
||||
if (button === "open") {
|
||||
return html`
|
||||
<ha-control-button
|
||||
.label=${this._localize("ui.card.cover.open_cover")}
|
||||
@click=${this._onOpenTap}
|
||||
.disabled=${!canOpen(this.stateObj)}
|
||||
data-button="open"
|
||||
>
|
||||
<ha-svg-icon .path=${computeOpenIcon(this.stateObj)}></ha-svg-icon>
|
||||
</ha-control-button>
|
||||
`;
|
||||
}
|
||||
if (button === "close") {
|
||||
return html`
|
||||
<ha-control-button
|
||||
.label=${this._localize("ui.card.cover.close_cover")}
|
||||
@click=${this._onCloseTap}
|
||||
.disabled=${!canClose(this.stateObj)}
|
||||
data-button="close"
|
||||
>
|
||||
<ha-svg-icon .path=${computeCloseIcon(this.stateObj)}></ha-svg-icon>
|
||||
</ha-control-button>
|
||||
`;
|
||||
}
|
||||
if (button === "stop") {
|
||||
return html`
|
||||
<ha-control-button
|
||||
.label=${this._localize("ui.card.cover.stop_cover")}
|
||||
@click=${this._onStopTap}
|
||||
.disabled=${!canStop(this.stateObj) && !canStopTilt(this.stateObj)}
|
||||
data-button="stop"
|
||||
>
|
||||
<ha-svg-icon .path=${mdiStop}></ha-svg-icon>
|
||||
</ha-control-button>
|
||||
`;
|
||||
}
|
||||
if (button === "open-tilt") {
|
||||
return html`
|
||||
<ha-control-button
|
||||
.label=${this._localize("ui.card.cover.open_tilt_cover")}
|
||||
@click=${this._onOpenTiltTap}
|
||||
.disabled=${!canOpenTilt(this.stateObj)}
|
||||
data-button="open-tilt"
|
||||
>
|
||||
<ha-svg-icon .path=${mdiArrowTopRight}></ha-svg-icon>
|
||||
</ha-control-button>
|
||||
`;
|
||||
}
|
||||
if (button === "close-tilt") {
|
||||
return html`
|
||||
<ha-control-button
|
||||
.label=${this._localize("ui.card.cover.close_tilt_cover")}
|
||||
@click=${this._onCloseTiltTap}
|
||||
.disabled=${!canCloseTilt(this.stateObj)}
|
||||
data-button="close-tilt"
|
||||
>
|
||||
<ha-svg-icon .path=${mdiArrowBottomLeft}></ha-svg-icon>
|
||||
</ha-control-button>
|
||||
`;
|
||||
}
|
||||
return nothing;
|
||||
}
|
||||
|
||||
protected render(): TemplateResult {
|
||||
const layout = getCoverLayout(this.stateObj);
|
||||
|
||||
return html`
|
||||
${
|
||||
layout.type === "line"
|
||||
? html`
|
||||
<ha-control-button-group vertical>
|
||||
${repeat(
|
||||
layout.buttons,
|
||||
(action) => action,
|
||||
(action) => this.renderButton(action)
|
||||
)}
|
||||
</ha-control-button-group>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
layout.type === "cross"
|
||||
? html`
|
||||
<div class="cross-container">
|
||||
${repeat(
|
||||
layout.buttons,
|
||||
(action) => action,
|
||||
(action) => this.renderButton(action)
|
||||
)}
|
||||
</div>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
ha-control-button-group {
|
||||
height: 45vh;
|
||||
max-height: 320px;
|
||||
min-height: 200px;
|
||||
--control-button-group-spacing: 10px;
|
||||
--control-button-group-thickness: 100px;
|
||||
}
|
||||
.cross-container {
|
||||
height: 45vh;
|
||||
max-height: 320px;
|
||||
min-height: 200px;
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
grid-template-columns: repeat(3, min(100px, 25vw, 15vh));
|
||||
grid-template-rows: repeat(3, min(100px, 25vw, 15vh));
|
||||
grid-template-areas: ". open ." "close-tilt stop open-tilt" ". close .";
|
||||
}
|
||||
.cross-container > * {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
.cross-container > [data-button="open"] {
|
||||
grid-area: open;
|
||||
}
|
||||
.cross-container > [data-button="close"] {
|
||||
grid-area: close;
|
||||
}
|
||||
.cross-container > [data-button="open-tilt"] {
|
||||
grid-area: open-tilt;
|
||||
}
|
||||
.cross-container > [data-button="close-tilt"] {
|
||||
grid-area: close-tilt;
|
||||
}
|
||||
.cross-container > [data-button="stop"] {
|
||||
grid-area: stop;
|
||||
}
|
||||
ha-control-button {
|
||||
--control-button-border-radius: var(--ha-border-radius-6xl);
|
||||
--mdc-icon-size: 24px;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-state-control-cover-buttons": HaStateControlCoverButtons;
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
import type { TemplateResult, PropertyValues } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import type { HASSDomEvent } from "../../common/dom/fire_event";
|
||||
import { transform } from "../../common/decorators/transform";
|
||||
import { stateColorCss } from "../../common/entity/state_color";
|
||||
import "../../components/ha-control-slider";
|
||||
import {
|
||||
apiContext,
|
||||
formattersContext,
|
||||
internationalizationContext,
|
||||
} from "../../data/context";
|
||||
import type { CoverEntity } from "../../data/cover";
|
||||
import { UNAVAILABLE } from "../../data/entity/entity";
|
||||
import { DOMAIN_ATTRIBUTES_UNITS } from "../../data/entity/entity_attributes";
|
||||
import type { FrontendLocaleData } from "../../data/translation";
|
||||
import type {
|
||||
HomeAssistantApi,
|
||||
HomeAssistantFormatters,
|
||||
HomeAssistantInternationalization,
|
||||
} from "../../types";
|
||||
|
||||
@customElement("ha-state-control-cover-position")
|
||||
export class HaStateControlCoverPosition extends LitElement {
|
||||
@state()
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: HomeAssistantApi;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
private _formatters!: HomeAssistantFormatters;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
@transform<HomeAssistantInternationalization, FrontendLocaleData>({
|
||||
transformer: ({ locale }) => locale,
|
||||
})
|
||||
private _locale!: FrontendLocaleData;
|
||||
|
||||
@property({ attribute: false }) public stateObj!: CoverEntity;
|
||||
|
||||
@state() value?: number;
|
||||
|
||||
protected updated(changedProp: PropertyValues<this>): void {
|
||||
if (changedProp.has("stateObj")) {
|
||||
const currentPosition = this.stateObj?.attributes.current_position;
|
||||
this.value =
|
||||
currentPosition != null ? Math.round(currentPosition) : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private _valueChanged(ev: HASSDomEvent<HASSDomEvents["value-changed"]>) {
|
||||
const { value } = ev.detail;
|
||||
if (typeof value !== "number" || isNaN(value)) return;
|
||||
|
||||
this._api.callService("cover", "set_cover_position", {
|
||||
entity_id: this.stateObj!.entity_id,
|
||||
position: value,
|
||||
});
|
||||
}
|
||||
|
||||
protected render(): TemplateResult {
|
||||
const openColor = stateColorCss(this.stateObj, "open");
|
||||
const color = stateColorCss(this.stateObj);
|
||||
|
||||
return html`
|
||||
<ha-control-slider
|
||||
touch-action="none"
|
||||
vertical
|
||||
.value=${this.value}
|
||||
min="0"
|
||||
max="100"
|
||||
show-handle
|
||||
mode="end"
|
||||
@value-changed=${this._valueChanged}
|
||||
.label=${this._formatters.formatEntityAttributeName(
|
||||
this.stateObj,
|
||||
"current_position"
|
||||
)}
|
||||
style=${styleMap({
|
||||
// Use open color for inactive state to avoid grey slider that looks disabled
|
||||
"--state-cover-inactive-color": openColor,
|
||||
"--control-slider-color": color,
|
||||
"--control-slider-background": color,
|
||||
})}
|
||||
.disabled=${this.stateObj.state === UNAVAILABLE}
|
||||
.unit=${DOMAIN_ATTRIBUTES_UNITS.cover.current_position}
|
||||
.locale=${this._locale}
|
||||
>
|
||||
</ha-control-slider>
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
ha-control-slider {
|
||||
height: 45vh;
|
||||
max-height: 320px;
|
||||
min-height: 200px;
|
||||
--control-slider-thickness: 130px;
|
||||
--control-slider-border-radius: var(--ha-border-radius-6xl);
|
||||
--control-slider-color: var(--primary-color);
|
||||
--control-slider-background: var(--disabled-color);
|
||||
--control-slider-background-opacity: 0.2;
|
||||
--control-slider-tooltip-font-size: var(--ha-font-size-xl);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-state-control-cover-position": HaStateControlCoverPosition;
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
import type { CSSResultGroup, TemplateResult, PropertyValues } from "lit";
|
||||
import { css, html, LitElement, unsafeCSS } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import type { HASSDomEvent } from "../../common/dom/fire_event";
|
||||
import { transform } from "../../common/decorators/transform";
|
||||
import { stateColorCss } from "../../common/entity/state_color";
|
||||
import "../../components/ha-control-slider";
|
||||
import {
|
||||
apiContext,
|
||||
formattersContext,
|
||||
internationalizationContext,
|
||||
} from "../../data/context";
|
||||
import type { CoverEntity } from "../../data/cover";
|
||||
import { UNAVAILABLE } from "../../data/entity/entity";
|
||||
import { DOMAIN_ATTRIBUTES_UNITS } from "../../data/entity/entity_attributes";
|
||||
import type { FrontendLocaleData } from "../../data/translation";
|
||||
import type {
|
||||
HomeAssistantApi,
|
||||
HomeAssistantFormatters,
|
||||
HomeAssistantInternationalization,
|
||||
} from "../../types";
|
||||
|
||||
export function generateTiltSliderTrackBackgroundGradient() {
|
||||
const count = 24;
|
||||
const minStrokeWidth = 0.2;
|
||||
const gradient: [number, string][] = [];
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const stopOffset1 = i / count;
|
||||
const stopOffset2 =
|
||||
stopOffset1 +
|
||||
(i / count ** 2) * (1 - minStrokeWidth) +
|
||||
minStrokeWidth / count;
|
||||
|
||||
if (i !== 0) {
|
||||
gradient.push([stopOffset1, "transparent"]);
|
||||
}
|
||||
gradient.push([stopOffset1, "var(--control-slider-color)"]);
|
||||
gradient.push([stopOffset2, "var(--control-slider-color)"]);
|
||||
gradient.push([stopOffset2, "transparent"]);
|
||||
}
|
||||
|
||||
return unsafeCSS(
|
||||
gradient
|
||||
.map(([stop, color]) => `${color} ${(stop as number) * 100}%`)
|
||||
.join(", ")
|
||||
);
|
||||
}
|
||||
|
||||
const GRADIENT = generateTiltSliderTrackBackgroundGradient();
|
||||
|
||||
@customElement("ha-state-control-cover-tilt-position")
|
||||
export class HaStateControlInfoCoverTiltPosition extends LitElement {
|
||||
@state()
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: HomeAssistantApi;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
private _formatters!: HomeAssistantFormatters;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
@transform<HomeAssistantInternationalization, FrontendLocaleData>({
|
||||
transformer: ({ locale }) => locale,
|
||||
})
|
||||
private _locale!: FrontendLocaleData;
|
||||
|
||||
@property({ attribute: false }) public stateObj!: CoverEntity;
|
||||
|
||||
@state() value?: number;
|
||||
|
||||
protected updated(changedProp: PropertyValues<this>): void {
|
||||
if (changedProp.has("stateObj")) {
|
||||
this.value =
|
||||
this.stateObj.attributes.current_tilt_position != null
|
||||
? Math.round(this.stateObj.attributes.current_tilt_position)
|
||||
: undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private _valueChanged(ev: HASSDomEvent<HASSDomEvents["value-changed"]>) {
|
||||
const { value } = ev.detail;
|
||||
if (typeof value !== "number" || isNaN(value)) return;
|
||||
|
||||
this._api.callService("cover", "set_cover_tilt_position", {
|
||||
entity_id: this.stateObj!.entity_id,
|
||||
tilt_position: value,
|
||||
});
|
||||
}
|
||||
|
||||
protected render(): TemplateResult {
|
||||
const openColor = stateColorCss(this.stateObj, "open");
|
||||
const color = stateColorCss(this.stateObj);
|
||||
|
||||
return html`
|
||||
<ha-control-slider
|
||||
touch-action="none"
|
||||
vertical
|
||||
.value=${this.value}
|
||||
min="0"
|
||||
max="100"
|
||||
mode="cursor"
|
||||
@value-changed=${this._valueChanged}
|
||||
.label=${this._formatters.formatEntityAttributeName(
|
||||
this.stateObj,
|
||||
"current_tilt_position"
|
||||
)}
|
||||
style=${styleMap({
|
||||
// Use open color for inactive state to avoid grey slider that looks disabled
|
||||
"--state-cover-inactive-color": openColor,
|
||||
"--control-slider-color": color,
|
||||
"--control-slider-background": color,
|
||||
})}
|
||||
.disabled=${this.stateObj.state === UNAVAILABLE}
|
||||
.unit=${DOMAIN_ATTRIBUTES_UNITS.cover.current_tilt_position}
|
||||
.locale=${this._locale}
|
||||
>
|
||||
<div slot="background" class="gradient"></div>
|
||||
</ha-control-slider>
|
||||
`;
|
||||
}
|
||||
|
||||
static get styles(): CSSResultGroup {
|
||||
return css`
|
||||
ha-control-slider {
|
||||
height: 45vh;
|
||||
max-height: 320px;
|
||||
min-height: 200px;
|
||||
--control-slider-thickness: 130px;
|
||||
--control-slider-border-radius: var(--ha-border-radius-6xl);
|
||||
--control-slider-color: var(--primary-color);
|
||||
--control-slider-background: var(--disabled-color);
|
||||
--control-slider-background-opacity: 0.2;
|
||||
--control-slider-tooltip-font-size: var(--ha-font-size-xl);
|
||||
}
|
||||
.gradient {
|
||||
background: linear-gradient(to bottom, ${GRADIENT});
|
||||
opacity: 0.6;
|
||||
}
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-state-control-cover-tilt-position": HaStateControlInfoCoverTiltPosition;
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { html, LitElement } 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 { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
import { stateColorCss } from "../../common/entity/state_color";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import "../../components/ha-control-button";
|
||||
import "../../components/ha-control-switch";
|
||||
import "../../components/ha-state-icon";
|
||||
import { apiContext } from "../../data/context";
|
||||
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
|
||||
import { forwardHaptic } from "../../data/haptics";
|
||||
import { stateControlToggleStyle } from "../../resources/state-control-styles";
|
||||
import type { HomeAssistantApi } from "../../types";
|
||||
|
||||
@customElement("ha-state-control-cover-toggle")
|
||||
export class HaStateControlCoverToggle extends LitElement {
|
||||
@state()
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: HomeAssistantApi;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@property({ attribute: false }) public stateObj!: HassEntity;
|
||||
|
||||
private _valueChanged(ev) {
|
||||
const checked = ev.target.checked as boolean;
|
||||
|
||||
if (checked) {
|
||||
this._turnOn();
|
||||
} else {
|
||||
this._turnOff();
|
||||
}
|
||||
}
|
||||
|
||||
private _turnOn() {
|
||||
this._callService(true);
|
||||
}
|
||||
|
||||
private _turnOff() {
|
||||
this._callService(false);
|
||||
}
|
||||
|
||||
private async _callService(turnOn): Promise<void> {
|
||||
if (!this.stateObj) {
|
||||
return;
|
||||
}
|
||||
forwardHaptic(this, "light");
|
||||
|
||||
await this._api.callService(
|
||||
"cover",
|
||||
turnOn ? "open_cover" : "close_cover",
|
||||
{
|
||||
entity_id: this.stateObj.entity_id,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
protected render(): TemplateResult {
|
||||
const onColor = stateColorCss(this.stateObj, "open");
|
||||
const offColor = stateColorCss(this.stateObj, "closed");
|
||||
|
||||
const isOn =
|
||||
this.stateObj.state === "open" ||
|
||||
this.stateObj.state === "closing" ||
|
||||
this.stateObj.state === "opening";
|
||||
const isOff = this.stateObj.state === "closed";
|
||||
|
||||
if (
|
||||
this.stateObj.attributes.assumed_state ||
|
||||
this.stateObj.state === UNKNOWN
|
||||
) {
|
||||
return html`
|
||||
<div class="buttons">
|
||||
<ha-control-button
|
||||
.label=${this._localize("ui.card.cover.open_cover")}
|
||||
@click=${this._turnOn}
|
||||
.disabled=${this.stateObj.state === UNAVAILABLE}
|
||||
class=${classMap({
|
||||
active: isOn,
|
||||
})}
|
||||
style=${styleMap({
|
||||
"--color": onColor,
|
||||
})}
|
||||
>
|
||||
<ha-state-icon
|
||||
.stateObj=${this.stateObj}
|
||||
.stateValue=${"open"}
|
||||
></ha-state-icon>
|
||||
</ha-control-button>
|
||||
<ha-control-button
|
||||
.label=${this._localize("ui.card.cover.close_cover")}
|
||||
@click=${this._turnOff}
|
||||
.disabled=${this.stateObj.state === UNAVAILABLE}
|
||||
class=${classMap({
|
||||
active: isOff,
|
||||
})}
|
||||
style=${styleMap({
|
||||
"--color": offColor,
|
||||
})}
|
||||
>
|
||||
<ha-state-icon
|
||||
.stateObj=${this.stateObj}
|
||||
.stateValue=${"closed"}
|
||||
></ha-state-icon>
|
||||
</ha-control-button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-control-switch
|
||||
touch-action="none"
|
||||
vertical
|
||||
reversed
|
||||
.checked=${isOn}
|
||||
@change=${this._valueChanged}
|
||||
.label=${
|
||||
isOn
|
||||
? this._localize("ui.card.cover.close_cover")
|
||||
: this._localize("ui.card.cover.open_cover")
|
||||
}
|
||||
style=${styleMap({
|
||||
"--control-switch-on-color": onColor,
|
||||
"--control-switch-off-color": offColor,
|
||||
})}
|
||||
.disabled=${this.stateObj.state === UNAVAILABLE}
|
||||
>
|
||||
<ha-state-icon
|
||||
slot="icon-on"
|
||||
.stateObj=${this.stateObj}
|
||||
.stateValue=${"open"}
|
||||
></ha-state-icon>
|
||||
<ha-state-icon
|
||||
slot="icon-off"
|
||||
.stateObj=${this.stateObj}
|
||||
.stateValue=${"closed"}
|
||||
></ha-state-icon>
|
||||
</ha-control-switch>
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = [stateControlToggleStyle];
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-state-control-cover-toggle": HaStateControlCoverToggle;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,834 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { LitElement, css, html, nothing, svg } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../common/decorators/transform";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { mainWindow } from "../../common/dom/get_main_window";
|
||||
import { supportsFeature } from "../../common/entity/supports-feature";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import {
|
||||
formattersContext,
|
||||
reducedMotionContext,
|
||||
uiContext,
|
||||
} from "../../data/context";
|
||||
import type {
|
||||
CoverControlMode,
|
||||
CoverDrag,
|
||||
CoverEntity,
|
||||
CoverRequest,
|
||||
CoverSwipe,
|
||||
} from "../../data/cover";
|
||||
import {
|
||||
CoverEntityFeature,
|
||||
coverCurrentValue,
|
||||
coverHasTiltControls,
|
||||
coverModeAttribute,
|
||||
coverSupportsPosition,
|
||||
coverSupportsSetValue,
|
||||
coverSupportsTiltPosition,
|
||||
isMoving,
|
||||
isOpening,
|
||||
} from "../../data/cover";
|
||||
import { UNAVAILABLE } from "../../data/entity/entity";
|
||||
import type { HomeAssistantFormatters, HomeAssistantUI } from "../../types";
|
||||
import { coverDrawingStyles } from "./cover-drawing-styles";
|
||||
import { coverShape } from "./shapes";
|
||||
import { PointerDragController } from "./pointer-drag-controller";
|
||||
import type { CoverShape, OpeningDirection } from "./shapes/shared";
|
||||
import {
|
||||
FRAME,
|
||||
VIEWBOX_SIZE,
|
||||
clampPercent,
|
||||
isHorizontal,
|
||||
} from "./shapes/shared";
|
||||
import type { SpringOptions } from "./spring";
|
||||
import { PercentSpring } from "./spring";
|
||||
import { WaveMotion } from "./wave";
|
||||
|
||||
type HandleMotion = "follow" | "drag" | "swipe" | "request" | "return";
|
||||
|
||||
type ModeSprings = Record<CoverControlMode, PercentSpring>;
|
||||
|
||||
type ModeMotions = Record<CoverControlMode, HandleMotion>;
|
||||
|
||||
const SWIPE_SPRING: SpringOptions = { stiffness: 22, damping: 0.8 };
|
||||
const KEY_COMMIT_DELAY = 500;
|
||||
const SWIPE_RESISTANCE = 20;
|
||||
const GAUGE_WIDTH = 16;
|
||||
const MODES = ["position", "tilt"] as const;
|
||||
|
||||
const MOVING_HINT_ANGLE: Record<OpeningDirection, number> = {
|
||||
up: 0,
|
||||
down: 180,
|
||||
left: -90,
|
||||
};
|
||||
|
||||
const SKY_LAYERS = ["sky", "sky-warm", "sky-cool"];
|
||||
|
||||
const pillHandle = (cx: number, cy: number, vertical: boolean) =>
|
||||
vertical
|
||||
? svg`<rect class="pill-handle" x=${cx - 4} y=${cy - 22} width="8" height="44" rx="4"></rect>`
|
||||
: svg`<rect class="pill-handle" x=${cx - 24} y=${cy - 4} width="48" height="8" rx="4"></rect>`;
|
||||
|
||||
const swipeResistance = (distance: number) =>
|
||||
SWIPE_RESISTANCE * (1 - Math.exp(-Math.max(0, distance) / 30));
|
||||
|
||||
const modeSprings = (): ModeSprings => ({
|
||||
position: new PercentSpring(),
|
||||
tilt: new PercentSpring(),
|
||||
});
|
||||
|
||||
const modeMotions = (): ModeMotions => ({
|
||||
position: "follow",
|
||||
tilt: "follow",
|
||||
});
|
||||
|
||||
@customElement("ha-state-control-cover")
|
||||
export class HaStateControlCover extends LitElement {
|
||||
@property({ attribute: false }) public stateObj!: CoverEntity;
|
||||
|
||||
@property({ attribute: false }) public mode: CoverControlMode = "position";
|
||||
|
||||
@property({ attribute: false }) public request?: CoverRequest;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
private _formatters!: HomeAssistantFormatters;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@consume({ context: reducedMotionContext, subscribe: true })
|
||||
private _reducedMotion = false;
|
||||
|
||||
@state()
|
||||
@consume({ context: uiContext, subscribe: true })
|
||||
@transform<HomeAssistantUI, boolean>({
|
||||
transformer: ({ themes }) => themes.darkMode,
|
||||
})
|
||||
private _darkMode?: boolean;
|
||||
|
||||
@state() private _drag?: CoverDrag;
|
||||
|
||||
@state() private _pointerFocus = false;
|
||||
|
||||
@query(".control") private _control?: HTMLElement;
|
||||
|
||||
private _coverSprings = modeSprings();
|
||||
|
||||
private _handleSprings = modeSprings();
|
||||
|
||||
private _handleMotions = modeMotions();
|
||||
|
||||
private _wave = new WaveMotion();
|
||||
|
||||
private _frame?: number;
|
||||
|
||||
private _lastFrame = 0;
|
||||
|
||||
private _keyCommitTimer?: number;
|
||||
|
||||
private _pointer = new PointerDragController(this);
|
||||
|
||||
public connectedCallback(): void {
|
||||
super.connectedCallback();
|
||||
if (this.stateObj) {
|
||||
this._startLoop();
|
||||
}
|
||||
}
|
||||
|
||||
public disconnectedCallback(): void {
|
||||
super.disconnectedCallback();
|
||||
if (this._frame) {
|
||||
cancelAnimationFrame(this._frame);
|
||||
this._frame = undefined;
|
||||
}
|
||||
clearTimeout(this._keyCommitTimer);
|
||||
this._keyCommitTimer = undefined;
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>): void {
|
||||
super.willUpdate(changedProps);
|
||||
if (!this.stateObj) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
changedProps.has("stateObj") &&
|
||||
changedProps.get("stateObj")?.entity_id !== this.stateObj.entity_id
|
||||
) {
|
||||
this._resetMotion();
|
||||
}
|
||||
this._startLoop();
|
||||
}
|
||||
|
||||
private _resetMotion() {
|
||||
for (const mode of MODES) {
|
||||
const value = this._drawingGoal(mode);
|
||||
this._coverSprings[mode].jumpTo(value);
|
||||
this._handleSprings[mode].jumpTo(value);
|
||||
}
|
||||
this._handleMotions = modeMotions();
|
||||
this._wave.reset(this._coverSprings.position.value);
|
||||
}
|
||||
|
||||
private get _shape(): CoverShape {
|
||||
return coverShape(this.stateObj.attributes.device_class, this.mode);
|
||||
}
|
||||
|
||||
private get _isRtl(): boolean {
|
||||
return mainWindow.document.dir === "rtl";
|
||||
}
|
||||
|
||||
private get _canSetValue(): boolean {
|
||||
return coverSupportsSetValue(this.stateObj, this.mode);
|
||||
}
|
||||
|
||||
private get _openCloseOnly(): boolean {
|
||||
return (
|
||||
this.mode === "position" &&
|
||||
!coverSupportsPosition(this.stateObj) &&
|
||||
(supportsFeature(this.stateObj, CoverEntityFeature.OPEN) ||
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE))
|
||||
);
|
||||
}
|
||||
|
||||
private get _valueUnknown(): boolean {
|
||||
if (this.mode === "tilt" && !this._canSetValue) {
|
||||
return false;
|
||||
}
|
||||
return coverCurrentValue(this.stateObj, this.mode) === undefined;
|
||||
}
|
||||
|
||||
private get _interactive(): boolean {
|
||||
return (
|
||||
this.stateObj.state !== UNAVAILABLE &&
|
||||
(this._canSetValue || (this._openCloseOnly && !this._valueUnknown))
|
||||
);
|
||||
}
|
||||
|
||||
private get _valueChanging(): boolean {
|
||||
return this._drag !== undefined || this.request?.mode === this.mode;
|
||||
}
|
||||
|
||||
private _drawingGoal(mode: CoverControlMode): number {
|
||||
const value = coverCurrentValue(this.stateObj, mode);
|
||||
if (value !== undefined) {
|
||||
return clampPercent(value);
|
||||
}
|
||||
if (mode === "tilt" && !coverSupportsTiltPosition(this.stateObj)) {
|
||||
return 50;
|
||||
}
|
||||
return this._coverSprings[mode].value;
|
||||
}
|
||||
|
||||
private _handleGoal(mode: CoverControlMode): number {
|
||||
if (this.request?.mode === mode) {
|
||||
return this.request.value;
|
||||
}
|
||||
return Math.round(this._drawingGoal(mode));
|
||||
}
|
||||
|
||||
private _startLoop() {
|
||||
if (this._frame || !this.isConnected) {
|
||||
return;
|
||||
}
|
||||
this._lastFrame = performance.now();
|
||||
this._frame = requestAnimationFrame(this._tick);
|
||||
}
|
||||
|
||||
private _tick = (time: number) => {
|
||||
this._frame = undefined;
|
||||
const dt = Math.min(100, time - this._lastFrame) / 1000;
|
||||
this._lastFrame = time;
|
||||
let changed = false;
|
||||
for (const mode of MODES) {
|
||||
const goal = this._drawingGoal(mode);
|
||||
changed = this._moveSpring(this._coverSprings[mode], goal, dt) || changed;
|
||||
changed = this._moveHandle(mode, goal, dt) || changed;
|
||||
}
|
||||
if (this._shape.usesWave) {
|
||||
changed = this._moveWave(dt) || changed;
|
||||
}
|
||||
if (changed) {
|
||||
this.requestUpdate();
|
||||
this._frame = requestAnimationFrame(this._tick);
|
||||
}
|
||||
};
|
||||
|
||||
private _moveSpring(
|
||||
spring: PercentSpring,
|
||||
goal: number,
|
||||
dt: number,
|
||||
options?: SpringOptions
|
||||
): boolean {
|
||||
return this._reducedMotion
|
||||
? spring.jumpTo(goal)
|
||||
: spring.moveTo(goal, dt, options);
|
||||
}
|
||||
|
||||
private _moveWave(dt: number): boolean {
|
||||
const position = this._coverSprings.position.value;
|
||||
if (this._reducedMotion) {
|
||||
this._wave.jumpTo(position);
|
||||
return false;
|
||||
}
|
||||
return this._wave.moveTo(position, dt);
|
||||
}
|
||||
|
||||
private _handleMotion(mode: CoverControlMode): HandleMotion {
|
||||
if (this._drag && this.mode === mode) {
|
||||
return this._drag.swipe ? "swipe" : "drag";
|
||||
}
|
||||
if (this.request?.mode === mode) {
|
||||
return "request";
|
||||
}
|
||||
const previous = this._handleMotions[mode];
|
||||
const afterRequest = previous === "request" || previous === "return";
|
||||
const distance = Math.abs(
|
||||
this._handleSprings[mode].value - this._coverSprings[mode].value
|
||||
);
|
||||
if (afterRequest && distance > 0.5) {
|
||||
return "return";
|
||||
}
|
||||
return "follow";
|
||||
}
|
||||
|
||||
private _moveHandle(
|
||||
mode: CoverControlMode,
|
||||
goal: number,
|
||||
dt: number
|
||||
): boolean {
|
||||
const handle = this._handleSprings[mode];
|
||||
const motion = this._handleMotion(mode);
|
||||
this._handleMotions[mode] = motion;
|
||||
switch (motion) {
|
||||
case "drag":
|
||||
return handle.jumpTo(this._drag!.value);
|
||||
case "swipe":
|
||||
return this._moveSpring(handle, this._drag!.value, dt, SWIPE_SPRING);
|
||||
case "request":
|
||||
return this._moveSpring(handle, this.request!.value, dt);
|
||||
case "return":
|
||||
return this._moveSpring(handle, goal, dt);
|
||||
default:
|
||||
return handle.jumpTo(this._coverSprings[mode].value);
|
||||
}
|
||||
}
|
||||
|
||||
private _setDrag(drag: CoverDrag | undefined) {
|
||||
const previous = this._drag;
|
||||
this._drag = drag;
|
||||
this._startLoop();
|
||||
if (!drag && !previous) {
|
||||
return;
|
||||
}
|
||||
const changed =
|
||||
!drag ||
|
||||
!previous ||
|
||||
(drag.swipe
|
||||
? drag.swipe.passedHalfway !== previous.swipe?.passedHalfway
|
||||
: drag.value !== previous.value);
|
||||
if (changed) {
|
||||
fireEvent(this, "cover-drag-changed", { drag });
|
||||
}
|
||||
}
|
||||
|
||||
private _sendValue(value: number) {
|
||||
fireEvent(this, "cover-command", { mode: this.mode, action: "set", value });
|
||||
}
|
||||
|
||||
private _pointerValue(ev: PointerEvent, shape: CoverShape) {
|
||||
const rect = this._control?.getBoundingClientRect();
|
||||
if (!rect?.width || !rect.height) {
|
||||
return undefined;
|
||||
}
|
||||
let x = ((ev.clientX - rect.left) / rect.width) * VIEWBOX_SIZE;
|
||||
const y = ((ev.clientY - rect.top) / rect.height) * VIEWBOX_SIZE;
|
||||
if (isHorizontal(shape) && this._isRtl) {
|
||||
x = VIEWBOX_SIZE - x;
|
||||
}
|
||||
return shape.valueAt(x, y);
|
||||
}
|
||||
|
||||
private _onPointerDown(ev: PointerEvent) {
|
||||
if (!this._interactive || ev.button !== 0) {
|
||||
return;
|
||||
}
|
||||
this._commitKeyValue();
|
||||
const shape = this._shape;
|
||||
this._pointerFocus = true;
|
||||
this._control?.focus({ preventScroll: true });
|
||||
ev.preventDefault();
|
||||
const startPointer = this._pointerValue(ev, shape);
|
||||
if (startPointer === undefined) {
|
||||
return;
|
||||
}
|
||||
if (this._openCloseOnly) {
|
||||
this._startSwipe(ev, shape, startPointer);
|
||||
return;
|
||||
}
|
||||
this._startDrag(ev, shape, startPointer);
|
||||
}
|
||||
|
||||
private _startDrag(
|
||||
ev: PointerEvent,
|
||||
shape: CoverShape,
|
||||
startPointer: number
|
||||
) {
|
||||
const startValue =
|
||||
this._valueUnknown && this.request?.mode !== this.mode
|
||||
? startPointer
|
||||
: this._handleGoal(this.mode);
|
||||
this._pointer.start(ev, {
|
||||
move: (e) => {
|
||||
const pointer = this._pointerValue(e, shape);
|
||||
if (pointer === undefined) {
|
||||
return;
|
||||
}
|
||||
const value = startValue + pointer - startPointer;
|
||||
this._setDrag({ value: clampPercent(Math.round(value)) });
|
||||
},
|
||||
drop: () => {
|
||||
const value = this._drag?.value;
|
||||
this._setDrag(undefined);
|
||||
if (value !== undefined) {
|
||||
this._sendValue(value);
|
||||
}
|
||||
},
|
||||
tap: (e) => {
|
||||
const pointer = this._pointerValue(e, shape);
|
||||
if (pointer !== undefined) {
|
||||
this._sendValue(clampPercent(Math.round(pointer)));
|
||||
}
|
||||
},
|
||||
cancel: () => this._setDrag(undefined),
|
||||
});
|
||||
}
|
||||
|
||||
private _swipeAction(): CoverSwipe["action"] {
|
||||
const end =
|
||||
this.request?.mode === "position"
|
||||
? this.request.value
|
||||
: this._drawingGoal("position");
|
||||
return end >= 50 ? "close" : "open";
|
||||
}
|
||||
|
||||
private _startSwipe(
|
||||
ev: PointerEvent,
|
||||
shape: CoverShape,
|
||||
startPointer: number
|
||||
) {
|
||||
const action = this._swipeAction();
|
||||
const closing = action === "close";
|
||||
if (
|
||||
!supportsFeature(
|
||||
this.stateObj,
|
||||
closing ? CoverEntityFeature.CLOSE : CoverEntityFeature.OPEN
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const direction = closing ? -1 : 1;
|
||||
this._pointer.start(ev, {
|
||||
move: (e) => {
|
||||
const pointer = this._pointerValue(e, shape);
|
||||
if (pointer === undefined) {
|
||||
return;
|
||||
}
|
||||
const progress = (pointer - startPointer) * direction;
|
||||
const passedHalfway = progress > 50;
|
||||
if (
|
||||
this._drag?.swipe &&
|
||||
this._drag.swipe.passedHalfway !== passedHalfway &&
|
||||
"vibrate" in navigator
|
||||
) {
|
||||
navigator.vibrate(10);
|
||||
}
|
||||
const travel = passedHalfway
|
||||
? 100 - swipeResistance(100 - progress)
|
||||
: swipeResistance(progress);
|
||||
this._setDrag({
|
||||
value: closing ? 100 - travel : travel,
|
||||
swipe: { action, passedHalfway },
|
||||
});
|
||||
},
|
||||
drop: () => {
|
||||
const passedHalfway = Boolean(this._drag?.swipe?.passedHalfway);
|
||||
this._setDrag(undefined);
|
||||
if (passedHalfway) {
|
||||
fireEvent(this, "cover-command", { mode: "position", action });
|
||||
}
|
||||
},
|
||||
tap: (e) => {
|
||||
const pointer = this._pointerValue(e, shape);
|
||||
if (pointer !== undefined && pointer >= 50 !== closing) {
|
||||
fireEvent(this, "cover-command", { mode: "position", action });
|
||||
}
|
||||
},
|
||||
cancel: () => this._setDrag(undefined),
|
||||
});
|
||||
}
|
||||
|
||||
private _onBlur() {
|
||||
this._pointerFocus = false;
|
||||
this._commitKeyValue();
|
||||
}
|
||||
|
||||
private _onKeyDown(ev: KeyboardEvent) {
|
||||
this._pointerFocus = false;
|
||||
if (!this._interactive || !this._canSetValue) {
|
||||
return;
|
||||
}
|
||||
const step = this._keyStep(ev);
|
||||
if (step === undefined) {
|
||||
return;
|
||||
}
|
||||
ev.preventDefault();
|
||||
const current = this._drag?.value ?? this._handleGoal(this.mode);
|
||||
this._setDrag({ value: clampPercent(current + step) });
|
||||
clearTimeout(this._keyCommitTimer);
|
||||
this._keyCommitTimer = window.setTimeout(
|
||||
this._commitKeyValue,
|
||||
KEY_COMMIT_DELAY
|
||||
);
|
||||
}
|
||||
|
||||
private _commitKeyValue = () => {
|
||||
if (this._keyCommitTimer === undefined) {
|
||||
return;
|
||||
}
|
||||
clearTimeout(this._keyCommitTimer);
|
||||
this._keyCommitTimer = undefined;
|
||||
const value = this._drag?.value;
|
||||
this._setDrag(undefined);
|
||||
if (value !== undefined) {
|
||||
this._sendValue(value);
|
||||
}
|
||||
};
|
||||
|
||||
private _keyStep(ev: KeyboardEvent): number | undefined {
|
||||
const step = ev.shiftKey ? 10 : 1;
|
||||
const horizontalSign = this._isRtl ? -1 : 1;
|
||||
switch (ev.key) {
|
||||
case "ArrowUp":
|
||||
return step;
|
||||
case "ArrowDown":
|
||||
return -step;
|
||||
case "ArrowRight":
|
||||
return step * horizontalSign;
|
||||
case "ArrowLeft":
|
||||
return -step * horizontalSign;
|
||||
case "PageUp":
|
||||
return 10;
|
||||
case "PageDown":
|
||||
return -10;
|
||||
case "Home":
|
||||
return -100;
|
||||
case "End":
|
||||
return 100;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private _formatValue(value: number): string {
|
||||
return this._formatters.formatEntityAttributeValue(
|
||||
this.stateObj,
|
||||
coverModeAttribute(this.mode),
|
||||
Math.round(value)
|
||||
);
|
||||
}
|
||||
|
||||
private _movingHintAngle(shape: CoverShape): number | undefined {
|
||||
if (
|
||||
this.mode !== "position" ||
|
||||
this._valueUnknown ||
|
||||
!isMoving(this.stateObj)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const openingAngle = MOVING_HINT_ANGLE[shape.opens];
|
||||
return isOpening(this.stateObj) ? openingAngle : openingAngle + 180;
|
||||
}
|
||||
|
||||
private _valueText(value: number): string {
|
||||
const current = Math.round(this._drawingGoal(this.mode));
|
||||
if (this._valueUnknown && !this._valueChanging) {
|
||||
return this._localize("state.default.unknown");
|
||||
}
|
||||
if (!this._drag && this.request?.mode === this.mode && value !== current) {
|
||||
return this._localize(
|
||||
"ui.dialogs.more_info_control.cover.requested_value_text",
|
||||
{
|
||||
value: this._formatValue(value),
|
||||
current: this._formatValue(current),
|
||||
}
|
||||
);
|
||||
}
|
||||
return this._formatValue(value);
|
||||
}
|
||||
|
||||
private _drawnTilt(): number {
|
||||
if (this.mode === "tilt" && this._drag) {
|
||||
return this._drag.value;
|
||||
}
|
||||
return coverHasTiltControls(this.stateObj)
|
||||
? this._coverSprings.tilt.value
|
||||
: 0;
|
||||
}
|
||||
|
||||
private _renderDefs() {
|
||||
const { left, top, width, height } = FRAME;
|
||||
return svg`
|
||||
<defs>
|
||||
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" class="sky-top"></stop>
|
||||
<stop offset="1" class="sky-bottom"></stop>
|
||||
</linearGradient>
|
||||
<radialGradient id="sky-warm" cx="22%" cy="14%" r="58%">
|
||||
<stop offset="0" class="sky-warm" stop-opacity="0.55"></stop>
|
||||
<stop offset="1" class="sky-warm" stop-opacity="0"></stop>
|
||||
</radialGradient>
|
||||
<radialGradient id="sky-cool" cx="82%" cy="92%" r="62%">
|
||||
<stop offset="0" class="sky-cool" stop-opacity="0.45"></stop>
|
||||
<stop offset="1" class="sky-cool" stop-opacity="0"></stop>
|
||||
</radialGradient>
|
||||
<clipPath id="opening-clip">
|
||||
<rect x=${left} y=${top} width=${width} height=${height} rx="12"></rect>
|
||||
</clipPath>
|
||||
</defs>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderSky() {
|
||||
const { left, top, width, height } = FRAME;
|
||||
return SKY_LAYERS.map(
|
||||
(layer) => svg`
|
||||
<rect
|
||||
x=${left}
|
||||
y=${top}
|
||||
width=${width}
|
||||
height=${height}
|
||||
fill="url(#${layer})"
|
||||
></rect>
|
||||
`
|
||||
);
|
||||
}
|
||||
|
||||
private _renderTarget(shape: CoverShape, value: number) {
|
||||
return svg`
|
||||
${shape.targetShape?.(value) ?? nothing}
|
||||
${shape.targetLine ? svg`<path class="target-line" d=${shape.targetLine(value)}></path>` : nothing}
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderHandle(shape: CoverShape, value: number) {
|
||||
const [cx, cy] = shape.handleAt(value);
|
||||
if (shape.handle !== "gauge") {
|
||||
return pillHandle(cx, cy, isHorizontal(shape));
|
||||
}
|
||||
const [, railTop] = shape.handleAt(100);
|
||||
const [, railBottom] = shape.handleAt(0);
|
||||
const x = this._isRtl ? VIEWBOX_SIZE - cx : cx;
|
||||
return svg`
|
||||
<rect
|
||||
class="gauge-rail"
|
||||
x=${x - GAUGE_WIDTH / 2}
|
||||
y=${railTop - GAUGE_WIDTH / 2}
|
||||
width=${GAUGE_WIDTH}
|
||||
height=${railBottom - railTop + GAUGE_WIDTH}
|
||||
rx=${GAUGE_WIDTH / 2}
|
||||
></rect>
|
||||
<circle class="gauge-ball" cx=${x} cy=${cy} r=${GAUGE_WIDTH / 2 - 2}></circle>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderMovingHint(angle: number) {
|
||||
return svg`
|
||||
<g transform="translate(${FRAME.centerX} ${FRAME.centerY}) rotate(${angle})">
|
||||
<g class="moving-hint">
|
||||
<path class="chevron back" d="M-6 6.5 L0 0.5 L6 6.5"></path>
|
||||
<path class="chevron" d="M-6 -0.5 L0 -6.5 L6 -0.5"></path>
|
||||
</g>
|
||||
</g>
|
||||
`;
|
||||
}
|
||||
|
||||
private _sliderAria(shape: CoverShape, value: number) {
|
||||
return {
|
||||
label: this._localize(
|
||||
this.mode === "tilt"
|
||||
? "ui.card.cover.tilt_position"
|
||||
: "ui.card.cover.position"
|
||||
),
|
||||
valueNow: String(value),
|
||||
valueText: this._valueText(value),
|
||||
orientation: isHorizontal(shape)
|
||||
? ("horizontal" as const)
|
||||
: ("vertical" as const),
|
||||
};
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.stateObj) {
|
||||
return nothing;
|
||||
}
|
||||
const shape = this._shape;
|
||||
const mode = this.mode;
|
||||
const unknown = this._valueUnknown;
|
||||
const interactive = this._interactive;
|
||||
const changing = this._valueChanging;
|
||||
const cover = this._coverSprings[mode].value;
|
||||
const handle = this._handleSprings[mode].value;
|
||||
const withHandle = interactive && (!unknown || changing);
|
||||
const withTarget = changing && (unknown || Math.abs(handle - cover) > 1);
|
||||
const parts = shape.render({
|
||||
position: this._coverSprings.position.value,
|
||||
tilt: this._drawnTilt(),
|
||||
wave: this._wave,
|
||||
});
|
||||
const flip = isHorizontal(shape) && this._isRtl;
|
||||
const movingHintAngle = this._movingHintAngle(shape);
|
||||
const value = Math.round(this._drag?.value ?? this._handleGoal(mode));
|
||||
const slider = interactive && this._canSetValue;
|
||||
const aria = slider ? this._sliderAria(shape, value) : undefined;
|
||||
const { left, top, width, height } = FRAME;
|
||||
|
||||
return html`
|
||||
<div
|
||||
class=${classMap({
|
||||
control: true,
|
||||
interactive,
|
||||
disabled: this.stateObj.state === UNAVAILABLE,
|
||||
dark: this._darkMode,
|
||||
"pointer-focus": this._pointerFocus,
|
||||
})}
|
||||
role=${ifDefined(aria ? "slider" : undefined)}
|
||||
tabindex=${ifDefined(aria ? "0" : undefined)}
|
||||
aria-label=${ifDefined(aria?.label)}
|
||||
aria-valuemin=${ifDefined(aria ? "0" : undefined)}
|
||||
aria-valuemax=${ifDefined(aria ? "100" : undefined)}
|
||||
aria-valuenow=${ifDefined(aria?.valueNow)}
|
||||
aria-valuetext=${ifDefined(aria?.valueText)}
|
||||
aria-orientation=${ifDefined(aria?.orientation)}
|
||||
@pointerdown=${this._onPointerDown}
|
||||
@keydown=${this._onKeyDown}
|
||||
@blur=${this._onBlur}
|
||||
>
|
||||
<svg viewBox="0 0 ${VIEWBOX_SIZE} ${VIEWBOX_SIZE}" aria-hidden="true">
|
||||
${this._renderDefs()}
|
||||
<rect
|
||||
class="frame"
|
||||
width=${VIEWBOX_SIZE}
|
||||
height=${VIEWBOX_SIZE}
|
||||
rx="22"
|
||||
></rect>
|
||||
<g
|
||||
transform=${ifDefined(flip ? `translate(${VIEWBOX_SIZE} 0) scale(-1 1)` : undefined)}
|
||||
>
|
||||
<g clip-path="url(#opening-clip)">
|
||||
${this._renderSky()} ${parts.back ?? nothing}
|
||||
${unknown ? nothing : parts.cover} ${parts.front ?? nothing}
|
||||
${withTarget ? this._renderTarget(shape, handle) : nothing}
|
||||
</g>
|
||||
<rect
|
||||
class="opening-edge"
|
||||
x=${left - 0.5}
|
||||
y=${top - 0.5}
|
||||
width=${width + 1}
|
||||
height=${height + 1}
|
||||
rx="12.5"
|
||||
></rect>
|
||||
${movingHintAngle !== undefined ? this._renderMovingHint(movingHintAngle) : nothing}
|
||||
${withHandle ? this._renderHandle(shape, handle) : nothing}
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = [
|
||||
coverDrawingStyles,
|
||||
css`
|
||||
:host {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
}
|
||||
.control {
|
||||
position: relative;
|
||||
flex: none;
|
||||
width: clamp(200px, 45vh, 300px);
|
||||
max-width: 100%;
|
||||
aspect-ratio: 1 / 1;
|
||||
border-radius: var(--ha-border-radius-4xl);
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
outline: none;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
.control.interactive {
|
||||
cursor: grab;
|
||||
}
|
||||
.control.interactive:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
.control:focus-visible:not(.pointer-focus) {
|
||||
box-shadow: 0 0 0 3px var(--primary-color);
|
||||
}
|
||||
.control.disabled {
|
||||
opacity: 0.4;
|
||||
}
|
||||
svg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
.moving-hint {
|
||||
animation: drift 1.4s linear infinite;
|
||||
}
|
||||
.chevron {
|
||||
fill: none;
|
||||
stroke: var(--cover-drawing-handle);
|
||||
stroke-width: 2.5;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
opacity: 0.8;
|
||||
filter: drop-shadow(0 1px 1.5px var(--cover-drawing-handle-shadow));
|
||||
}
|
||||
.chevron.back {
|
||||
opacity: 0.45;
|
||||
}
|
||||
@keyframes drift {
|
||||
from {
|
||||
transform: translateY(4px);
|
||||
opacity: 0;
|
||||
}
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
to {
|
||||
transform: translateY(-4px);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.moving-hint {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-state-control-cover": HaStateControlCover;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { ReactiveController, ReactiveControllerHost } from "lit";
|
||||
|
||||
const DRAG_THRESHOLD = 6;
|
||||
|
||||
export interface PointerDragHandlers {
|
||||
move(ev: PointerEvent): void;
|
||||
drop(ev: PointerEvent): void;
|
||||
tap(ev: PointerEvent): void;
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
export class PointerDragController implements ReactiveController {
|
||||
private _stop?: () => void;
|
||||
|
||||
constructor(host: ReactiveControllerHost) {
|
||||
host.addController(this);
|
||||
}
|
||||
|
||||
public hostDisconnected(): void {
|
||||
this._stop?.();
|
||||
}
|
||||
|
||||
public start(down: PointerEvent, handlers: PointerDragHandlers): void {
|
||||
this._stop?.();
|
||||
let dragging = false;
|
||||
const onMove = (ev: PointerEvent) => {
|
||||
if (
|
||||
!dragging &&
|
||||
Math.hypot(ev.clientX - down.clientX, ev.clientY - down.clientY) <
|
||||
DRAG_THRESHOLD
|
||||
) {
|
||||
return;
|
||||
}
|
||||
dragging = true;
|
||||
handlers.move(ev);
|
||||
};
|
||||
const onUp = (ev: PointerEvent) => {
|
||||
this._stop?.();
|
||||
if (dragging) {
|
||||
handlers.drop(ev);
|
||||
} else {
|
||||
handlers.tap(ev);
|
||||
}
|
||||
};
|
||||
const onCancel = () => {
|
||||
this._stop?.();
|
||||
handlers.cancel();
|
||||
};
|
||||
window.addEventListener("pointermove", onMove);
|
||||
window.addEventListener("pointerup", onUp);
|
||||
window.addEventListener("pointercancel", onCancel);
|
||||
this._stop = () => {
|
||||
window.removeEventListener("pointermove", onMove);
|
||||
window.removeEventListener("pointerup", onUp);
|
||||
window.removeEventListener("pointercancel", onCancel);
|
||||
this._stop = undefined;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { svg } from "lit";
|
||||
import type { CoverShape } from "./shared";
|
||||
import { FRAME, ghost, headrail, valueAxis } from "./shared";
|
||||
|
||||
const SCALLOPS = 8;
|
||||
const SCALLOP_WIDTH = FRAME.width / SCALLOPS;
|
||||
const MIN_EXTENT = 8;
|
||||
|
||||
const hem = valueAxis(FRAME.top, FRAME.top + FRAME.height * 0.9);
|
||||
|
||||
const hemY = (value: number) =>
|
||||
Math.max(FRAME.top + MIN_EXTENT, hem.coordAt(value));
|
||||
|
||||
const scallops = (bottom: number) => {
|
||||
let path = "";
|
||||
for (let index = SCALLOPS; index > 0; index--) {
|
||||
path += ` Q${FRAME.left + (index - 0.5) * SCALLOP_WIDTH},${bottom + 6} ${FRAME.left + (index - 1) * SCALLOP_WIDTH},${bottom}`;
|
||||
}
|
||||
return path;
|
||||
};
|
||||
|
||||
const outline = (bottom: number) =>
|
||||
`M${FRAME.left},${FRAME.top} H${FRAME.right} V${bottom}${scallops(bottom)} Z`;
|
||||
|
||||
export const awningShape: CoverShape = {
|
||||
opens: "down",
|
||||
render: ({ position }) => {
|
||||
const bottom = hemY(position);
|
||||
return {
|
||||
cover: svg`
|
||||
<path class="fabric" d=${outline(bottom)}></path>
|
||||
${Array.from(
|
||||
{ length: SCALLOPS - 1 },
|
||||
(_, index) =>
|
||||
svg`<rect class="seam faint" x=${(FRAME.left + (index + 1) * SCALLOP_WIDTH - 0.3).toFixed(1)} y=${FRAME.top} width="0.6" height=${(bottom - FRAME.top).toFixed(1)}></rect>`
|
||||
)}
|
||||
`,
|
||||
front: headrail(10.4),
|
||||
};
|
||||
},
|
||||
handleAt: (value) => [FRAME.centerX, hemY(value)],
|
||||
valueAt: (_x, y) => hem.valueAt(y),
|
||||
targetLine: (value) => {
|
||||
const bottom = hemY(value);
|
||||
return `M${FRAME.right},${bottom}${scallops(bottom)}`;
|
||||
},
|
||||
targetShape: (value) => ghost(svg`<path d=${outline(hemY(value))}></path>`),
|
||||
};
|
||||
@@ -0,0 +1,110 @@
|
||||
import { svg } from "lit";
|
||||
import { clamp } from "../../../common/number/clamp";
|
||||
import type { CoverShape } from "./shared";
|
||||
import { FRAME, ghost, headrail, valueAxis } from "./shared";
|
||||
|
||||
const GATHERED = 22;
|
||||
const ROWS = 12;
|
||||
const FOLDS = 12;
|
||||
const MAX_SPEED = 1.5;
|
||||
const MAX_SWING = 4.8;
|
||||
const SWING_PER_SPEED = 2.6;
|
||||
const HEM_LAG = 4.6;
|
||||
const REST_SWAY = 1.4;
|
||||
const FOLD_SWING = 1.35;
|
||||
const FOLD_REST_SWAY = 1.6;
|
||||
const FOLD_DELAY = 3.2;
|
||||
const FOLD_REST_DELAY = 2.5;
|
||||
|
||||
type Point = [number, number];
|
||||
|
||||
const freeEdge = valueAxis(FRAME.right, FRAME.left + GATHERED);
|
||||
|
||||
const toPath = (points: Point[]) =>
|
||||
points
|
||||
.map(
|
||||
([x, y], index) => `${index ? "L" : "M"}${x.toFixed(1)} ${y.toFixed(1)}`
|
||||
)
|
||||
.join(" ");
|
||||
|
||||
const hang = (t: number) => t ** 1.3;
|
||||
|
||||
const verticalLine = (xAt: (t: number) => number): Point[] =>
|
||||
Array.from({ length: ROWS + 1 }, (_, row) => [
|
||||
xAt(row / ROWS),
|
||||
FRAME.top + (FRAME.height * row) / ROWS,
|
||||
]);
|
||||
|
||||
const swingWave = (t: number, phase: number, delay = 0) =>
|
||||
Math.sin(t * Math.PI * 1.2 + phase - delay) * hang(t) * 1.4;
|
||||
|
||||
const restWave = (t: number, phase: number, delay = 0) =>
|
||||
Math.sin(t * Math.PI * 2 + phase * 0.6 - delay) * hang(t);
|
||||
|
||||
export const curtainShape: CoverShape = {
|
||||
opens: "left",
|
||||
usesWave: true,
|
||||
render: ({ position, wave }) => {
|
||||
const { left, top, bottom } = FRAME;
|
||||
const open = position / 100;
|
||||
const width = freeEdge.coordAt(position) - left;
|
||||
const velocity = clamp(-wave.velocity, -MAX_SPEED, MAX_SPEED);
|
||||
const phase = wave.phase;
|
||||
const swing =
|
||||
Math.min(MAX_SWING, Math.abs(velocity) * SWING_PER_SPEED) *
|
||||
Math.sign(velocity || 1);
|
||||
const rest = open * REST_SWAY;
|
||||
const lag = (t: number) =>
|
||||
-Math.abs(velocity) * HEM_LAG * t ** 1.5 * Math.sign(velocity);
|
||||
|
||||
const hem = verticalLine(
|
||||
(t) =>
|
||||
left +
|
||||
width +
|
||||
lag(t) +
|
||||
swing * swingWave(t, phase) +
|
||||
rest * restWave(t, phase)
|
||||
);
|
||||
const fold = (index: number) => {
|
||||
const distance = 1 - index / (FOLDS + 1);
|
||||
const weight = (1 - distance) ** 1.3;
|
||||
return verticalLine(
|
||||
(t) =>
|
||||
left +
|
||||
(width * index) / (FOLDS + 1) +
|
||||
lag(t) * weight +
|
||||
swing *
|
||||
FOLD_SWING *
|
||||
swingWave(t, phase, distance * FOLD_DELAY) *
|
||||
weight +
|
||||
rest *
|
||||
FOLD_REST_SWAY *
|
||||
restWave(t, phase, distance * FOLD_REST_DELAY) *
|
||||
open *
|
||||
(0.4 + 0.6 * weight)
|
||||
);
|
||||
};
|
||||
const folds = Array.from({ length: FOLDS }, (_, index) => fold(index + 1));
|
||||
const stripes: string[] = [];
|
||||
for (let index = 0; index < folds.length - 1; index += 2) {
|
||||
stripes.push(
|
||||
`${toPath([...folds[index], ...folds[index + 1].slice().reverse()])} Z`
|
||||
);
|
||||
}
|
||||
return {
|
||||
cover: svg`
|
||||
<path class="fabric" d=${`${toPath([[left, top], ...hem, [left, bottom]])} Z`}></path>
|
||||
${stripes.map((d) => svg`<path class="stripe" d=${d}></path>`)}
|
||||
`,
|
||||
front: headrail(6.4),
|
||||
};
|
||||
},
|
||||
handleAt: (value) => [freeEdge.coordAt(value), FRAME.centerY],
|
||||
valueAt: (x) => freeEdge.valueAt(x),
|
||||
targetLine: (value) =>
|
||||
`M${freeEdge.coordAt(value).toFixed(1)} ${FRAME.top} V${FRAME.bottom}`,
|
||||
targetShape: (value) =>
|
||||
ghost(
|
||||
svg`<rect x=${FRAME.left} y=${FRAME.top} width=${(freeEdge.coordAt(value) - FRAME.left).toFixed(1)} height=${FRAME.height}></rect>`
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { CoverControlMode } from "../../../data/cover";
|
||||
import { awningShape } from "./awning";
|
||||
import { curtainShape } from "./curtain";
|
||||
import { garageShape, panelShape, rollerShape, shutterShape } from "./roller";
|
||||
import type { CoverShape } from "./shared";
|
||||
import { slatsShape } from "./slats";
|
||||
import { slideShape } from "./slide";
|
||||
import { venetianShape } from "./venetian";
|
||||
|
||||
const POSITION_SHAPES: Record<string, CoverShape | undefined> = {
|
||||
awning: awningShape,
|
||||
blind: venetianShape,
|
||||
curtain: curtainShape,
|
||||
garage: garageShape,
|
||||
gate: slideShape,
|
||||
shade: rollerShape,
|
||||
shutter: shutterShape,
|
||||
};
|
||||
|
||||
export const coverShape = (
|
||||
deviceClass: string | undefined,
|
||||
mode: CoverControlMode
|
||||
): CoverShape => {
|
||||
if (mode === "tilt") {
|
||||
return slatsShape;
|
||||
}
|
||||
return (deviceClass && POSITION_SHAPES[deviceClass]) || panelShape;
|
||||
};
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { SVGTemplateResult } from "lit";
|
||||
import { svg } from "lit";
|
||||
import type { CoverShape } from "./shared";
|
||||
import { FRAME, ghost, headrail, horizontalLine, valueAxis } from "./shared";
|
||||
|
||||
const HEADRAIL = 10.4;
|
||||
const ROLL = 10;
|
||||
const BOTTOM_BAR = 4;
|
||||
const PANEL_EDGE = 2;
|
||||
const HANDLE_INSET = 2;
|
||||
const SHUTTER_SLAT = 12;
|
||||
const GARAGE_PANELS = 5;
|
||||
|
||||
export const coverBottom = valueAxis(FRAME.bottom, FRAME.top + ROLL);
|
||||
|
||||
const handleY = (value: number) => coverBottom.coordAt(value) - HANDLE_INSET;
|
||||
|
||||
export const rollingGeometry: Pick<
|
||||
CoverShape,
|
||||
"opens" | "handleAt" | "valueAt" | "targetLine" | "targetShape"
|
||||
> = {
|
||||
opens: "up",
|
||||
handleAt: (value) => [FRAME.centerX, handleY(value)],
|
||||
valueAt: (_x, y) => coverBottom.valueAt(y + HANDLE_INSET),
|
||||
targetLine: (value) => horizontalLine(handleY(value)),
|
||||
targetShape: (value) =>
|
||||
ghost(
|
||||
svg`<rect x=${FRAME.left} y=${FRAME.top} width=${FRAME.width} height=${(coverBottom.coordAt(value) - FRAME.top).toFixed(1)}></rect>`
|
||||
),
|
||||
};
|
||||
|
||||
const fabric = (bottom: number) =>
|
||||
svg`<rect class="fabric" x=${FRAME.left} y=${FRAME.top} width=${FRAME.width} height=${(bottom - FRAME.top).toFixed(1)}></rect>`;
|
||||
|
||||
const bottomBar = (bottom: number, height: number) =>
|
||||
svg`<rect class="bottom-bar" x=${FRAME.left} y=${(bottom - height).toFixed(1)} width=${FRAME.width} height=${height}></rect>`;
|
||||
|
||||
const rollingShape = (
|
||||
details: (bottom: number, position: number) => SVGTemplateResult[] = () => []
|
||||
): CoverShape => ({
|
||||
...rollingGeometry,
|
||||
render: ({ position }) => {
|
||||
const bottom = coverBottom.coordAt(position);
|
||||
return {
|
||||
cover: svg`
|
||||
${fabric(bottom)} ${details(bottom, position)}
|
||||
${bottomBar(bottom, BOTTOM_BAR)}
|
||||
`,
|
||||
front: headrail(HEADRAIL),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const shutterSlats = (bottom: number, position: number) => {
|
||||
const parts: SVGTemplateResult[] = [];
|
||||
for (
|
||||
let lineY = bottom - BOTTOM_BAR - SHUTTER_SLAT;
|
||||
lineY > FRAME.top;
|
||||
lineY -= SHUTTER_SLAT
|
||||
) {
|
||||
parts.push(
|
||||
svg`<line class="slat-line" x1=${FRAME.left} y1=${lineY.toFixed(1)} x2=${FRAME.right} y2=${lineY.toFixed(1)}></line>`
|
||||
);
|
||||
if (position > 0) {
|
||||
for (let slotX = FRAME.left + 8; slotX < FRAME.right - 8; slotX += 16) {
|
||||
parts.push(
|
||||
svg`<rect class="slot" x=${slotX} y=${(lineY - 1.2).toFixed(1)} width="7" height="2.4" rx="1.2"></rect>`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return parts;
|
||||
};
|
||||
|
||||
const garagePanels = (bottom: number) => {
|
||||
const panelHeight = FRAME.height / GARAGE_PANELS;
|
||||
const firstPanelTop = bottom - FRAME.height;
|
||||
const lintel = FRAME.top + HEADRAIL;
|
||||
const parts: SVGTemplateResult[] = [];
|
||||
for (let index = 0; index < GARAGE_PANELS; index++) {
|
||||
const top = firstPanelTop + index * panelHeight;
|
||||
const panelBottom = top + panelHeight;
|
||||
if (panelBottom <= lintel) {
|
||||
continue;
|
||||
}
|
||||
parts.push(
|
||||
top < lintel
|
||||
? svg`<rect class="panel-shadow" x=${FRAME.left} y=${lintel} width=${FRAME.width} height=${(panelBottom - lintel).toFixed(1)} opacity=${((0.22 * (lintel - top)) / panelHeight).toFixed(3)}></rect>`
|
||||
: svg`<rect class="seam" x=${FRAME.left} y=${(top - 0.8).toFixed(1)} width=${FRAME.width} height="1.6"></rect>`
|
||||
);
|
||||
}
|
||||
return parts;
|
||||
};
|
||||
|
||||
export const rollerShape = rollingShape();
|
||||
|
||||
export const panelShape: CoverShape = {
|
||||
...rollingGeometry,
|
||||
render: ({ position }) => {
|
||||
const bottom = coverBottom.coordAt(position);
|
||||
return {
|
||||
cover: svg`${fabric(bottom)} ${bottomBar(bottom, PANEL_EDGE)}`,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export const shutterShape = rollingShape(shutterSlats);
|
||||
|
||||
export const garageShape = rollingShape(garagePanels);
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { SVGTemplateResult } from "lit";
|
||||
import { nothing, svg } from "lit";
|
||||
import { clamp } from "../../../common/number/clamp";
|
||||
|
||||
export const VIEWBOX_SIZE = 200;
|
||||
|
||||
export const FRAME = {
|
||||
left: 10,
|
||||
top: 10,
|
||||
right: 190,
|
||||
bottom: 190,
|
||||
width: 180,
|
||||
height: 180,
|
||||
centerX: 100,
|
||||
centerY: 100,
|
||||
} as const;
|
||||
|
||||
export interface CoverWave {
|
||||
velocity: number;
|
||||
phase: number;
|
||||
}
|
||||
|
||||
export interface CoverShapeInput {
|
||||
position: number;
|
||||
tilt: number;
|
||||
wave: CoverWave;
|
||||
}
|
||||
|
||||
type Part = SVGTemplateResult | SVGTemplateResult[] | typeof nothing;
|
||||
|
||||
export interface CoverShapeParts {
|
||||
back?: Part;
|
||||
cover: Part;
|
||||
front?: Part;
|
||||
}
|
||||
|
||||
export type OpeningDirection = "up" | "down" | "left";
|
||||
|
||||
export interface CoverShape {
|
||||
opens: OpeningDirection;
|
||||
handle?: "pill" | "gauge";
|
||||
usesWave?: boolean;
|
||||
render(input: CoverShapeInput): CoverShapeParts;
|
||||
handleAt(value: number): [number, number];
|
||||
valueAt(x: number, y: number): number;
|
||||
targetLine?(value: number): string;
|
||||
targetShape?(value: number): SVGTemplateResult;
|
||||
}
|
||||
|
||||
export const isHorizontal = (shape: CoverShape) => shape.opens === "left";
|
||||
|
||||
export const clampPercent = (value: number) => clamp(value, 0, 100);
|
||||
|
||||
export const valueAxis = (atEmpty: number, atFull: number) => ({
|
||||
coordAt: (value: number) => atEmpty + ((atFull - atEmpty) * value) / 100,
|
||||
valueAt: (coord: number) => ((coord - atEmpty) / (atFull - atEmpty)) * 100,
|
||||
});
|
||||
|
||||
const tiltAxis = valueAxis(FRAME.bottom - 16, FRAME.top + 16);
|
||||
|
||||
export const tiltGeometry: Pick<
|
||||
CoverShape,
|
||||
"opens" | "handle" | "handleAt" | "valueAt"
|
||||
> = {
|
||||
opens: "up",
|
||||
handle: "gauge",
|
||||
handleAt: (value) => [FRAME.right - 14, tiltAxis.coordAt(value)],
|
||||
valueAt: (_x, y) => tiltAxis.valueAt(y),
|
||||
};
|
||||
|
||||
export const ghost = (shape: SVGTemplateResult, opacity = 0.22) =>
|
||||
svg`<g class="ghost" opacity=${opacity}>${shape}</g>`;
|
||||
|
||||
export const horizontalLine = (y: number, inset = 0) =>
|
||||
`M${FRAME.left + inset} ${y.toFixed(1)} H${FRAME.right - inset}`;
|
||||
|
||||
export const headrail = (height: number) => svg`
|
||||
<filter id="headrail-shadow" x="-5%" y="-50%" width="110%" height="300%">
|
||||
<feDropShadow dx="0" dy="1.2" stdDeviation="1.2" flood-color="#000" flood-opacity="0.18"></feDropShadow>
|
||||
</filter>
|
||||
<rect class="fabric" x=${FRAME.left} y=${FRAME.top} width=${FRAME.width} height=${height} filter="url(#headrail-shadow)"></rect>
|
||||
`;
|
||||
|
||||
export const slat = (top: number, thickness: number) => {
|
||||
const face = Math.max(0.4, thickness * 0.114);
|
||||
return svg`
|
||||
<rect class="fabric" x=${FRAME.left} y=${top.toFixed(2)} width=${FRAME.width} height=${Math.max(1, thickness).toFixed(2)}></rect>
|
||||
${
|
||||
thickness > 2.2
|
||||
? svg`
|
||||
<rect class="seam" x=${FRAME.left} y=${(top + thickness - face).toFixed(2)} width=${FRAME.width} height=${face.toFixed(2)}></rect>
|
||||
<rect class="lift" x=${FRAME.left} y=${top.toFixed(2)} width=${FRAME.width} height=${(face * 0.55).toFixed(2)}></rect>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
`;
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { CoverShape } from "./shared";
|
||||
import { FRAME, slat, tiltGeometry } from "./shared";
|
||||
|
||||
const PITCH = 12;
|
||||
|
||||
export const slatsShape: CoverShape = {
|
||||
...tiltGeometry,
|
||||
render: ({ tilt }) => {
|
||||
const count = Math.floor(FRAME.height / PITCH);
|
||||
const thickness = Math.max(1.2, (PITCH - 1) * (1 - tilt / 100));
|
||||
return {
|
||||
cover: Array.from({ length: count }, (_, index) =>
|
||||
slat(FRAME.top + index * PITCH + (PITCH - thickness) / 2, thickness)
|
||||
),
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
import { svg } from "lit";
|
||||
import type { CoverShape } from "./shared";
|
||||
import { FRAME, ghost, valueAxis } from "./shared";
|
||||
|
||||
const TRAVEL = FRAME.width - 28;
|
||||
const GATE_TOP = FRAME.top + FRAME.height * 0.36;
|
||||
const GROUND = FRAME.bottom - 20;
|
||||
const GATE_HEIGHT = GROUND - GATE_TOP;
|
||||
const BOARDS = 6;
|
||||
const BOARD_GAP = 4;
|
||||
const BOARD_HEIGHT = (GATE_HEIGHT - BOARD_GAP * (BOARDS - 1)) / BOARDS;
|
||||
const POST_WIDTH = 7;
|
||||
|
||||
const leadingEdge = valueAxis(FRAME.right, FRAME.right - TRAVEL);
|
||||
|
||||
const gateLeft = (value: number) => leadingEdge.coordAt(value) - FRAME.width;
|
||||
|
||||
const GRASS = (() => {
|
||||
let path = `M${FRAME.left},${FRAME.bottom} V${GROUND}`;
|
||||
for (let x = FRAME.left, index = 0; x < FRAME.right; x += 9, index++) {
|
||||
path += ` Q${x + 4.5},${GROUND - (index % 3 === 1 ? 6 : 4)} ${x + 9},${GROUND}`;
|
||||
}
|
||||
return `${path} V${FRAME.bottom} Z`;
|
||||
})();
|
||||
|
||||
export const slideShape: CoverShape = {
|
||||
opens: "left",
|
||||
render: ({ position }) => {
|
||||
const left = gateLeft(position);
|
||||
return {
|
||||
cover: svg`
|
||||
${Array.from(
|
||||
{ length: BOARDS },
|
||||
(_, index) =>
|
||||
svg`<rect class="metal" x=${left} y=${(GATE_TOP + index * (BOARD_HEIGHT + BOARD_GAP)).toFixed(1)} width=${FRAME.width} height=${BOARD_HEIGHT.toFixed(1)} rx="2"></rect>`
|
||||
)}
|
||||
<rect class="metal" x=${left} y=${GATE_TOP} width=${POST_WIDTH} height=${GATE_HEIGHT} rx="2"></rect>
|
||||
<rect class="metal" x=${left + FRAME.width - POST_WIDTH} y=${GATE_TOP} width=${POST_WIDTH} height=${GATE_HEIGHT} rx="2"></rect>
|
||||
`,
|
||||
front: svg`
|
||||
<linearGradient id="grass" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" class="grass-top"></stop>
|
||||
<stop offset="1" class="grass-bottom"></stop>
|
||||
</linearGradient>
|
||||
<path d=${GRASS} fill="url(#grass)"></path>
|
||||
`,
|
||||
};
|
||||
},
|
||||
handleAt: (value) => [leadingEdge.coordAt(value), GATE_TOP + GATE_HEIGHT / 2],
|
||||
valueAt: (x) => leadingEdge.valueAt(x),
|
||||
targetLine: (value) =>
|
||||
`M${leadingEdge.coordAt(value).toFixed(1)} ${GATE_TOP} V${GROUND}`,
|
||||
targetShape: (value) =>
|
||||
ghost(
|
||||
svg`<rect x=${gateLeft(value)} y=${GATE_TOP} width=${FRAME.width} height=${GATE_HEIGHT} rx="2"></rect>`
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
import { svg } from "lit";
|
||||
import { clamp } from "../../../common/number/clamp";
|
||||
import { coverBottom, rollingGeometry } from "./roller";
|
||||
import type { CoverShape } from "./shared";
|
||||
import { FRAME, clampPercent, headrail, slat } from "./shared";
|
||||
|
||||
const PITCH = 10;
|
||||
const STACK_PITCH = 0.6;
|
||||
const FLAT = 0.8;
|
||||
const CORDS = [0.22, 0.78];
|
||||
|
||||
export const venetianShape: CoverShape = {
|
||||
...rollingGeometry,
|
||||
render: ({ position, tilt }) => {
|
||||
const { left, top, width, height } = FRAME;
|
||||
const thickness = 9 - (7 * clampPercent(tilt)) / 100;
|
||||
const count = Math.ceil(height / PITCH) + 1;
|
||||
const first = top + thickness / 2;
|
||||
const pitch = (top + height - thickness / 2 - first) / (count - 1);
|
||||
const rail = coverBottom.coordAt(position);
|
||||
const centers = Array.from({ length: count }, (_, index) =>
|
||||
Math.max(
|
||||
first + index * STACK_PITCH,
|
||||
Math.min(
|
||||
first + index * pitch,
|
||||
rail - thickness / 2 - (count - 1 - index) * STACK_PITCH
|
||||
)
|
||||
)
|
||||
);
|
||||
const openness: number[] = [];
|
||||
for (let index = 0; index < count - 1; index++) {
|
||||
const gap = centers[index + 1] - centers[index] - STACK_PITCH;
|
||||
openness.push(clamp(gap / (pitch - STACK_PITCH), 0, 1));
|
||||
}
|
||||
openness.push(openness[count - 2]);
|
||||
const last = centers[count - 1];
|
||||
return {
|
||||
cover: svg`
|
||||
${centers.map((center, index) => {
|
||||
const slatHeight = FLAT + (thickness - FLAT) * openness[index];
|
||||
return slat(center - Math.max(0.5, slatHeight / 2), slatHeight);
|
||||
})}
|
||||
${CORDS.map(
|
||||
(fraction) =>
|
||||
svg`<rect class="cord" x=${(left + width * fraction - 0.7).toFixed(1)} y=${top} width="1.4" height=${(last + 1 - top).toFixed(1)}></rect>`
|
||||
)}
|
||||
`,
|
||||
front: headrail(8.8),
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
import { clamp } from "../../common/number/clamp";
|
||||
|
||||
const STEP = 0.016;
|
||||
const REST_DISTANCE = 0.05;
|
||||
const REST_VELOCITY = 0.5;
|
||||
|
||||
export interface SpringOptions {
|
||||
stiffness?: number;
|
||||
damping?: number;
|
||||
}
|
||||
|
||||
export class PercentSpring {
|
||||
public value = 0;
|
||||
|
||||
public velocity = 0;
|
||||
|
||||
public jumpTo(value: number): boolean {
|
||||
this.velocity = 0;
|
||||
if (this.value === value) {
|
||||
return false;
|
||||
}
|
||||
this.value = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
public moveTo(
|
||||
goal: number,
|
||||
dt: number,
|
||||
{ stiffness = 7, damping = 1 }: SpringOptions = {}
|
||||
): boolean {
|
||||
if (
|
||||
Math.abs(goal - this.value) < REST_DISTANCE &&
|
||||
Math.abs(this.velocity) < REST_VELOCITY
|
||||
) {
|
||||
return this.jumpTo(goal);
|
||||
}
|
||||
for (let left = dt; left > 0; left -= STEP) {
|
||||
const step = Math.min(STEP, left);
|
||||
this.velocity +=
|
||||
(stiffness * stiffness * (goal - this.value) -
|
||||
2 * damping * stiffness * this.velocity) *
|
||||
step;
|
||||
this.value += this.velocity * step;
|
||||
if (this.value < 0 || this.value > 100) {
|
||||
this.value = clamp(this.value, 0, 100);
|
||||
this.velocity = 0;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { CoverWave } from "./shapes/shared";
|
||||
|
||||
const FRAME_DURATION = 16.7;
|
||||
const REST_VELOCITY = 0.015;
|
||||
|
||||
export class WaveMotion implements CoverWave {
|
||||
public velocity = 0;
|
||||
|
||||
public phase = 0;
|
||||
|
||||
private _position = 0;
|
||||
|
||||
public reset(position: number): void {
|
||||
this.jumpTo(position);
|
||||
this.phase = 0;
|
||||
}
|
||||
|
||||
public jumpTo(position: number): void {
|
||||
this._position = position;
|
||||
this.velocity = 0;
|
||||
}
|
||||
|
||||
public moveTo(position: number, dt: number): boolean {
|
||||
const frames = Math.max(0.01, (dt * 1000) / FRAME_DURATION);
|
||||
const keep = 0.9 ** frames;
|
||||
const instant = (position - this._position) / frames;
|
||||
this.velocity = this.velocity * keep + instant * (1 - keep);
|
||||
if (Math.abs(this.velocity) < REST_VELOCITY && Math.abs(instant) < 0.001) {
|
||||
this.velocity = 0;
|
||||
}
|
||||
this._position = position;
|
||||
if (!this.velocity) {
|
||||
return false;
|
||||
}
|
||||
this.phase += (0.06 + Math.abs(this.velocity) * 0.03) * frames;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -2069,10 +2069,17 @@
|
||||
"copy_favorites": "Copy favorites to...",
|
||||
"copy_favorites_helper": "Select one or more covers to receive the copied favorites from this cover. Covers must support the same position controls.",
|
||||
"copy_favorites_entities": "[%key:ui::panel::lovelace::editor::card::generic::entities%]",
|
||||
"switch_mode": {
|
||||
"button": "Switch to button mode",
|
||||
"position": "Switch to position mode"
|
||||
},
|
||||
"open": "Open",
|
||||
"close": "Close",
|
||||
"stop": "Stop",
|
||||
"requested": "Requested {value}",
|
||||
"requested_open": "Requested open",
|
||||
"requested_closed": "Requested closed",
|
||||
"currently": "Currently {value}",
|
||||
"currently_unknown": "Currently unknown",
|
||||
"requested_value_text": "{value}, currently {current}",
|
||||
"opens_on_release": "Opens on release",
|
||||
"closes_on_release": "Closes on release",
|
||||
"favorite_position": {
|
||||
"set": "Set position to {value}",
|
||||
"edit": "Set position to {value}",
|
||||
@@ -2156,8 +2163,8 @@
|
||||
"copy_favorites_helper": "Select one or more valves to receive the copied favorites from this valve.",
|
||||
"copy_favorites_entities": "[%key:ui::panel::lovelace::editor::card::generic::entities%]",
|
||||
"switch_mode": {
|
||||
"button": "[%key:ui::dialogs::more_info_control::cover::switch_mode::button%]",
|
||||
"position": "[%key:ui::dialogs::more_info_control::cover::switch_mode::position%]"
|
||||
"button": "Switch to button mode",
|
||||
"position": "Switch to position mode"
|
||||
},
|
||||
"favorite_position": {
|
||||
"set": "[%key:ui::dialogs::more_info_control::cover::favorite_position::set%]",
|
||||
@@ -9976,6 +9983,34 @@
|
||||
"lifetime_used_description": "The drive’s wear level is shown as a percentage, based on endurance indicators reported by the device via NVMe SMART or eMMC lifetime estimate fields.",
|
||||
"disk_metrics": "Disk metrics",
|
||||
"change_chart_type": "Change chart type",
|
||||
"database": {
|
||||
"title": "Database",
|
||||
"description": "Analyze the database to see which tables, entities and statistics use the most space.",
|
||||
"analyzing": "Analyzing the database, this can take a while on a large database...",
|
||||
"analyze": "Analyze",
|
||||
"analyze_again": "Analyze again",
|
||||
"as_of": "as of {time}",
|
||||
"tables": "Tables",
|
||||
"other_tables": "Other tables",
|
||||
"unused_space": "Unused space",
|
||||
"unused_space_of": "{size} unused",
|
||||
"wal": "plus {size} write-ahead log",
|
||||
"unknown": "Without a known entity or statistic",
|
||||
"search": "Search entities",
|
||||
"no_entities": "No recorded entities",
|
||||
"errors": {
|
||||
"recorder_not_ready": "The recorder database is not available yet.",
|
||||
"migration_in_progress": "The recorder database is being migrated. Try again when the migration has finished."
|
||||
},
|
||||
"columns": {
|
||||
"entity": "Entity",
|
||||
"entity_id": "Entity ID",
|
||||
"states": "States",
|
||||
"statistics": "Statistics",
|
||||
"statistics_short_term": "Short-term statistics",
|
||||
"size": "Size"
|
||||
}
|
||||
},
|
||||
"datadisk": {
|
||||
"title": "Move data disk",
|
||||
"description": "You are currently using ''{current_path}'' as data disk. Moving the data disk will reboot your device and it's estimated to take {time} minutes. Your Home Assistant installation will not be accessible during this period. Do not disconnect the power during the move!",
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { assert, describe, it } from "vitest";
|
||||
import { kelvinRangeFromEntityStates } from "../../../src/common/color/color-temp-selector-range";
|
||||
|
||||
const statesFor = (
|
||||
ranges: Record<string, { min?: unknown; max?: unknown } | undefined>
|
||||
) => {
|
||||
const states: Record<string, { attributes: Record<string, unknown> }> = {};
|
||||
for (const [entityId, range] of Object.entries(ranges)) {
|
||||
states[entityId] = {
|
||||
attributes:
|
||||
range === undefined
|
||||
? {}
|
||||
: {
|
||||
min_color_temp_kelvin: range.min,
|
||||
max_color_temp_kelvin: range.max,
|
||||
},
|
||||
};
|
||||
}
|
||||
return states;
|
||||
};
|
||||
|
||||
describe("kelvinRangeFromEntityStates", () => {
|
||||
it("returns undefined when no entity reports a range", () => {
|
||||
assert.strictEqual(kelvinRangeFromEntityStates(undefined), undefined);
|
||||
assert.deepEqual(kelvinRangeFromEntityStates({}), undefined);
|
||||
assert.deepEqual(
|
||||
kelvinRangeFromEntityStates(statesFor({ "light.bulb": undefined })),
|
||||
undefined
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the selected light range", () => {
|
||||
assert.deepEqual(
|
||||
kelvinRangeFromEntityStates(
|
||||
statesFor({ "light.oranzovka": { min: 1600, max: 4000 } })
|
||||
),
|
||||
{ min: 1600, max: 4000 }
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the overlap when several lights are targeted", () => {
|
||||
assert.deepEqual(
|
||||
kelvinRangeFromEntityStates(
|
||||
statesFor({
|
||||
"light.warm": { min: 1600, max: 4000 },
|
||||
"light.daylight": { min: 2000, max: 6500 },
|
||||
})
|
||||
),
|
||||
{ min: 2000, max: 4000 }
|
||||
);
|
||||
});
|
||||
|
||||
it("spans the widest range when the lights do not overlap", () => {
|
||||
assert.deepEqual(
|
||||
kelvinRangeFromEntityStates(
|
||||
statesFor({
|
||||
"light.warm": { min: 1600, max: 2500 },
|
||||
"light.cold": { min: 5000, max: 6500 },
|
||||
})
|
||||
),
|
||||
{ min: 1600, max: 6500 }
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores a light with an invalid range", () => {
|
||||
assert.deepEqual(
|
||||
kelvinRangeFromEntityStates(
|
||||
statesFor({
|
||||
"light.broken": { min: 4000, max: 1600 },
|
||||
"light.bulb": { min: "1600", max: 4000 },
|
||||
"light.oranzovka": { min: 1600, max: 4000 },
|
||||
})
|
||||
),
|
||||
{ min: 1600, max: 4000 }
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,10 @@ import {
|
||||
mdiArrowDown,
|
||||
mdiArrowExpandHorizontal,
|
||||
mdiArrowUp,
|
||||
mdiDoorClosed,
|
||||
mdiDoorOpen,
|
||||
mdiGate,
|
||||
mdiGateOpen,
|
||||
} from "@mdi/js";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
@@ -11,44 +15,35 @@ import {
|
||||
computeCloseIcon,
|
||||
} from "../../../src/common/entity/cover_icon";
|
||||
|
||||
const withDeviceClass = (deviceClass: string) =>
|
||||
({ attributes: { device_class: deviceClass } }) as unknown as HassEntity;
|
||||
|
||||
describe("computeOpenIcon", () => {
|
||||
it("returns mdiArrowExpandHorizontal for awning, door, gate, and curtain", () => {
|
||||
const stateObj = { attributes: { device_class: "awning" } } as HassEntity;
|
||||
expect(computeOpenIcon(stateObj)).toBe(mdiArrowExpandHorizontal);
|
||||
|
||||
stateObj.attributes.device_class = "door";
|
||||
expect(computeOpenIcon(stateObj)).toBe(mdiArrowExpandHorizontal);
|
||||
|
||||
stateObj.attributes.device_class = "gate";
|
||||
expect(computeOpenIcon(stateObj)).toBe(mdiArrowExpandHorizontal);
|
||||
|
||||
stateObj.attributes.device_class = "curtain";
|
||||
expect(computeOpenIcon(stateObj)).toBe(mdiArrowExpandHorizontal);
|
||||
it("returns the device class icon for door, gate, curtain and awning", () => {
|
||||
expect(computeOpenIcon(withDeviceClass("door"))).toBe(mdiDoorOpen);
|
||||
expect(computeOpenIcon(withDeviceClass("gate"))).toBe(mdiGateOpen);
|
||||
expect(computeOpenIcon(withDeviceClass("curtain"))).toBe(
|
||||
mdiArrowExpandHorizontal
|
||||
);
|
||||
expect(computeOpenIcon(withDeviceClass("awning"))).toBe(mdiArrowDown);
|
||||
});
|
||||
|
||||
it("returns mdiArrowUp for other device classes", () => {
|
||||
const stateObj = { attributes: { device_class: "window" } } as HassEntity;
|
||||
expect(computeOpenIcon(stateObj)).toBe(mdiArrowUp);
|
||||
expect(computeOpenIcon(withDeviceClass("window"))).toBe(mdiArrowUp);
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeCloseIcon", () => {
|
||||
it("returns mdiArrowCollapseHorizontal for awning, door, gate, and curtain", () => {
|
||||
const stateObj = { attributes: { device_class: "awning" } } as HassEntity;
|
||||
expect(computeCloseIcon(stateObj)).toBe(mdiArrowCollapseHorizontal);
|
||||
|
||||
stateObj.attributes.device_class = "door";
|
||||
expect(computeCloseIcon(stateObj)).toBe(mdiArrowCollapseHorizontal);
|
||||
|
||||
stateObj.attributes.device_class = "gate";
|
||||
expect(computeCloseIcon(stateObj)).toBe(mdiArrowCollapseHorizontal);
|
||||
|
||||
stateObj.attributes.device_class = "curtain";
|
||||
expect(computeCloseIcon(stateObj)).toBe(mdiArrowCollapseHorizontal);
|
||||
it("returns the device class icon for door, gate, curtain and awning", () => {
|
||||
expect(computeCloseIcon(withDeviceClass("door"))).toBe(mdiDoorClosed);
|
||||
expect(computeCloseIcon(withDeviceClass("gate"))).toBe(mdiGate);
|
||||
expect(computeCloseIcon(withDeviceClass("curtain"))).toBe(
|
||||
mdiArrowCollapseHorizontal
|
||||
);
|
||||
expect(computeCloseIcon(withDeviceClass("awning"))).toBe(mdiArrowUp);
|
||||
});
|
||||
|
||||
it("returns mdiArrowDown for other device classes", () => {
|
||||
const stateObj = { attributes: { device_class: "window" } } as HassEntity;
|
||||
expect(computeCloseIcon(stateObj)).toBe(mdiArrowDown);
|
||||
expect(computeCloseIcon(withDeviceClass("window"))).toBe(mdiArrowDown);
|
||||
});
|
||||
});
|
||||
@@ -264,6 +264,23 @@ describe("downSampleLineData", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops a marker followed by a value that is neither min nor max", () => {
|
||||
// The reading after the gap repeats the one before it, so it loses the
|
||||
// min/max ties. The series then holds still for hours (#55896).
|
||||
const points: GappedPoint[] = [
|
||||
[FIXED_EPOCH_MS, 1.2],
|
||||
[FIXED_EPOCH_MS + 1_000, 1.2],
|
||||
[FIXED_EPOCH_MS + 1_001, 1.2],
|
||||
[FIXED_EPOCH_MS + 1_001, null],
|
||||
[FIXED_EPOCH_MS + 2_000, 1.2],
|
||||
[FIXED_EPOCH_MS + 30_000, 1.2],
|
||||
[FIXED_EPOCH_MS + 31_000, 1.2],
|
||||
];
|
||||
expect(
|
||||
downSampleLineData(points, 3).some((point) => point[1] === null)
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a marker sharing its x with a value after that value", () => {
|
||||
// statistics-chart-data.ts ends the line and breaks it at the same x
|
||||
const points: GappedPoint[] = [
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { computeTimelineColor } from "../../../src/components/chart/timeline-color";
|
||||
import { createMockComputedStyle } from "../../fixtures/computed-style";
|
||||
|
||||
const entity = (
|
||||
entity_id: string,
|
||||
attributes: Record<string, unknown> = {}
|
||||
): HassEntity =>
|
||||
({
|
||||
entity_id,
|
||||
state: "",
|
||||
attributes,
|
||||
last_changed: "",
|
||||
last_updated: "",
|
||||
context: { id: "", parent_id: null, user_id: null },
|
||||
}) as HassEntity;
|
||||
|
||||
describe("computeTimelineColor", () => {
|
||||
it("uses a themed color for a custom state of an uncolored domain", () => {
|
||||
const styles = createMockComputedStyle({
|
||||
"--state-sensor-heating-color": "#ff0000",
|
||||
"--state-sensor-power-heating-color": "#00ff00",
|
||||
});
|
||||
|
||||
expect(
|
||||
computeTimelineColor("Heating", styles, entity("sensor.heat_pump"))
|
||||
).toBe("#ff0000");
|
||||
expect(
|
||||
computeTimelineColor(
|
||||
"Heating",
|
||||
styles,
|
||||
entity("sensor.heat_pump", { device_class: "power" })
|
||||
)
|
||||
).toBe("#00ff00");
|
||||
});
|
||||
|
||||
it("keeps active/inactive fallbacks away from uncolored domains", () => {
|
||||
const styles = createMockComputedStyle({
|
||||
"--state-active-color": "#123456",
|
||||
"--state-sensor-active-color": "#654321",
|
||||
});
|
||||
|
||||
expect(
|
||||
computeTimelineColor("Heating", styles, entity("sensor.heat_pump"))
|
||||
).not.toMatch(/^#(123456|654321)$/);
|
||||
});
|
||||
});
|
||||
@@ -2406,7 +2406,6 @@ describe("getEnergyDataCollection gas energy unit", () => {
|
||||
stat_compensation: null,
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
cost_adjustment_day: 0,
|
||||
},
|
||||
solar: {
|
||||
type: "solar",
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
computeGroupMemberIds,
|
||||
filterGroupsWithListedMembers,
|
||||
} from "../../src/data/group";
|
||||
|
||||
const entity = (
|
||||
entity_id: string,
|
||||
attributes: HassEntity["attributes"] = {}
|
||||
): HassEntity =>
|
||||
({
|
||||
entity_id,
|
||||
state: "on",
|
||||
attributes,
|
||||
}) as HassEntity;
|
||||
|
||||
const toStates = (...entities: HassEntity[]): HassEntities =>
|
||||
Object.fromEntries(entities.map((e) => [e.entity_id, e]));
|
||||
|
||||
// The home summary's lights-on count and the more-info member list rely on
|
||||
// these rules to avoid counting a light twice.
|
||||
describe("computeGroupMemberIds", () => {
|
||||
it("core groups: members from group_entities", () => {
|
||||
expect(
|
||||
computeGroupMemberIds(
|
||||
entity("light.wled", { group_entities: ["light.wled_segment_1"] })
|
||||
)
|
||||
).toEqual(["light.wled_segment_1"]);
|
||||
});
|
||||
|
||||
it("group helpers and Hue rooms: members from entity_id", () => {
|
||||
expect(
|
||||
computeGroupMemberIds(
|
||||
entity("light.living_room", {
|
||||
is_hue_group: true,
|
||||
entity_id: ["light.lamp"],
|
||||
})
|
||||
)
|
||||
).toEqual(["light.lamp"]);
|
||||
});
|
||||
|
||||
it("prefers group_entities over entity_id", () => {
|
||||
expect(
|
||||
computeGroupMemberIds(
|
||||
entity("light.group", {
|
||||
group_entities: ["light.a"],
|
||||
entity_id: ["light.b"],
|
||||
})
|
||||
)
|
||||
).toEqual(["light.a"]);
|
||||
});
|
||||
|
||||
it("the registry copy wins over the state", () => {
|
||||
expect(
|
||||
computeGroupMemberIds(
|
||||
entity("light.group", { group_entities: ["light.b"] }),
|
||||
{ capabilities: { group_entities: ["light.a"] } }
|
||||
)
|
||||
).toEqual(["light.a"]);
|
||||
});
|
||||
|
||||
it("no entry: the state copy", () => {
|
||||
expect(
|
||||
computeGroupMemberIds(
|
||||
entity("light.group", { group_entities: ["light.b"] }),
|
||||
null
|
||||
)
|
||||
).toEqual(["light.b"]);
|
||||
});
|
||||
|
||||
it("not a group: undefined", () => {
|
||||
expect(computeGroupMemberIds(entity("light.lamp"))).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterGroupsWithListedMembers", () => {
|
||||
const lamp = entity("light.lamp");
|
||||
const ceiling = entity("light.ceiling");
|
||||
const helperGroup = entity("light.downstairs", {
|
||||
entity_id: ["light.lamp", "light.ceiling"],
|
||||
});
|
||||
const hueRoom = entity("light.living_room", {
|
||||
is_hue_group: true,
|
||||
entity_id: ["light.lamp"],
|
||||
});
|
||||
|
||||
it("drops a group whose members are counted", () => {
|
||||
const states = toStates(lamp, ceiling, helperGroup, hueRoom);
|
||||
expect(filterGroupsWithListedMembers(Object.keys(states), states)).toEqual([
|
||||
"light.lamp",
|
||||
"light.ceiling",
|
||||
]);
|
||||
});
|
||||
|
||||
it("nested groups: drops the outer group too", () => {
|
||||
const house = entity("light.house", {
|
||||
entity_id: ["light.downstairs"],
|
||||
});
|
||||
const states = toStates(lamp, ceiling, helperGroup, house);
|
||||
expect(filterGroupsWithListedMembers(Object.keys(states), states)).toEqual([
|
||||
"light.lamp",
|
||||
"light.ceiling",
|
||||
]);
|
||||
});
|
||||
|
||||
it("hidden members: the group still counts once", () => {
|
||||
// Only the group is listed, so dropping it would read "All off".
|
||||
const states = toStates(lamp, ceiling, helperGroup);
|
||||
expect(filterGroupsWithListedMembers(["light.downstairs"], states)).toEqual(
|
||||
["light.downstairs"]
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps an entity missing from states", () => {
|
||||
expect(filterGroupsWithListedMembers(["light.gone"], {})).toEqual([
|
||||
"light.gone",
|
||||
]);
|
||||
});
|
||||
|
||||
it("hidden intermediate group: drops the outer group", () => {
|
||||
// House contains the hidden Downstairs group, which contains the lamp.
|
||||
const house = entity("light.house", {
|
||||
entity_id: ["light.downstairs"],
|
||||
});
|
||||
const states = toStates(lamp, ceiling, helperGroup, house);
|
||||
expect(
|
||||
filterGroupsWithListedMembers(["light.house", "light.lamp"], states)
|
||||
).toEqual(["light.lamp"]);
|
||||
});
|
||||
|
||||
it("groups that contain each other, both listed: one stays", () => {
|
||||
const a = entity("light.a", { entity_id: ["light.b"] });
|
||||
const b = entity("light.b", { entity_id: ["light.a"] });
|
||||
const states = toStates(a, b);
|
||||
expect(
|
||||
filterGroupsWithListedMembers(["light.a", "light.b"], states)
|
||||
).toEqual(["light.b"]);
|
||||
});
|
||||
|
||||
it("groups that contain each other: no infinite loop", () => {
|
||||
const a = entity("light.a", { entity_id: ["light.b"] });
|
||||
const b = entity("light.b", { entity_id: ["light.a"] });
|
||||
const states = toStates(a, b);
|
||||
expect(filterGroupsWithListedMembers(["light.a"], states)).toEqual([
|
||||
"light.a",
|
||||
]);
|
||||
});
|
||||
});
|
||||
Vendored
-1
@@ -45,7 +45,6 @@ export const generateEnergyPreferences = (
|
||||
stat_compensation: null,
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
cost_adjustment_day: 0,
|
||||
});
|
||||
}
|
||||
if (options.solar) {
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { RecorderDatabaseUsage } from "../../../../src/data/recorder";
|
||||
import {
|
||||
UNKNOWN_ROW_ID,
|
||||
databaseUsageRows,
|
||||
groupSmallTables,
|
||||
} from "../../../../src/panels/config/storage/storage-database-card";
|
||||
|
||||
describe("groupSmallTables", () => {
|
||||
it("sums tables below the share into other bytes", () => {
|
||||
expect(
|
||||
groupSmallTables(
|
||||
[
|
||||
{ table: "states", bytes: 900 },
|
||||
{ table: "statistics", bytes: 95 },
|
||||
{ table: "schema_changes", bytes: 4 },
|
||||
{ table: "sqlite_stat1", bytes: 1 },
|
||||
{ table: "empty", bytes: 0 },
|
||||
],
|
||||
0.01
|
||||
)
|
||||
).toEqual({
|
||||
tables: [
|
||||
{ table: "states", bytes: 900 },
|
||||
{ table: "statistics", bytes: 95 },
|
||||
],
|
||||
otherBytes: 5,
|
||||
totalBytes: 1000,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps everything when no table is small", () => {
|
||||
expect(groupSmallTables([{ table: "states", bytes: 10 }])).toEqual({
|
||||
tables: [{ table: "states", bytes: 10 }],
|
||||
otherBytes: 0,
|
||||
totalBytes: 10,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const USAGE: RecorderDatabaseUsage = {
|
||||
generated_at: "2026-11-12T10:00:00+00:00",
|
||||
duration: 1.5,
|
||||
total_bytes: 1000,
|
||||
free_bytes: 100,
|
||||
wal_bytes: 50,
|
||||
tables: [{ table: "states", bytes: 900 }],
|
||||
entities: [
|
||||
{
|
||||
entity_id: "sensor.energy",
|
||||
states: 10,
|
||||
states_bytes: 100,
|
||||
attributes_bytes: 20,
|
||||
},
|
||||
{ entity_id: null, states: 1, states_bytes: 10, attributes_bytes: 0 },
|
||||
],
|
||||
statistics: [
|
||||
{
|
||||
statistic_id: "sensor.energy",
|
||||
source: "recorder",
|
||||
statistics: 5,
|
||||
statistics_short_term: 7,
|
||||
statistics_bytes: 50,
|
||||
statistics_short_term_bytes: 70,
|
||||
},
|
||||
{
|
||||
statistic_id: "sensor:external",
|
||||
source: "sensor",
|
||||
statistics: 3,
|
||||
statistics_short_term: 0,
|
||||
statistics_bytes: 30,
|
||||
statistics_short_term_bytes: 0,
|
||||
},
|
||||
{
|
||||
statistic_id: null,
|
||||
source: null,
|
||||
statistics: 1,
|
||||
statistics_short_term: 0,
|
||||
statistics_bytes: 10,
|
||||
statistics_short_term_bytes: 0,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("databaseUsageRows", () => {
|
||||
it("merges the statistics of an entity into its row", () => {
|
||||
expect(databaseUsageRows(USAGE)).toEqual([
|
||||
{
|
||||
id: "sensor.energy",
|
||||
states: 10,
|
||||
statistics: 5,
|
||||
statistics_short_term: 7,
|
||||
bytes: 240,
|
||||
},
|
||||
{
|
||||
id: UNKNOWN_ROW_ID,
|
||||
states: 1,
|
||||
statistics: 1,
|
||||
statistics_short_term: 0,
|
||||
bytes: 20,
|
||||
},
|
||||
{
|
||||
id: "sensor:external",
|
||||
states: 0,
|
||||
statistics: 3,
|
||||
statistics_short_term: 0,
|
||||
bytes: 30,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("has no sizes when the database cannot report table sizes", () => {
|
||||
expect(
|
||||
databaseUsageRows({
|
||||
...USAGE,
|
||||
tables: null,
|
||||
entities: [
|
||||
{
|
||||
entity_id: "sensor.energy",
|
||||
states: 10,
|
||||
states_bytes: null,
|
||||
attributes_bytes: null,
|
||||
},
|
||||
],
|
||||
statistics: [
|
||||
{
|
||||
statistic_id: "sensor:external",
|
||||
source: "sensor",
|
||||
statistics: 3,
|
||||
statistics_short_term: 0,
|
||||
statistics_bytes: null,
|
||||
statistics_short_term_bytes: null,
|
||||
},
|
||||
],
|
||||
})
|
||||
).toEqual([
|
||||
{
|
||||
id: "sensor.energy",
|
||||
states: 10,
|
||||
statistics: 0,
|
||||
statistics_short_term: 0,
|
||||
bytes: null,
|
||||
},
|
||||
{
|
||||
id: "sensor:external",
|
||||
states: 0,
|
||||
statistics: 3,
|
||||
statistics_short_term: 0,
|
||||
bytes: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import "../../../../src/panels/lovelace/components/hui-generic-entity-row";
|
||||
import { createMockEntityState, createMockHass } from "../../../fixtures/hass";
|
||||
|
||||
const mountRow = async (catchInteraction = false) => {
|
||||
const row = document.createElement("hui-generic-entity-row");
|
||||
row.hass = createMockHass({
|
||||
"input_boolean.porch": createMockEntityState("input_boolean.porch", "off"),
|
||||
});
|
||||
row.config = { entity: "input_boolean.porch" };
|
||||
row.catchInteraction = catchInteraction;
|
||||
const control = document.createElement("button");
|
||||
row.append(control);
|
||||
document.body.append(row);
|
||||
await row.updateComplete;
|
||||
const moreInfo = vi.fn();
|
||||
row.addEventListener("hass-more-info", moreInfo);
|
||||
return {
|
||||
control,
|
||||
moreInfo,
|
||||
rowElement: row.shadowRoot!.querySelector(".row")!,
|
||||
name: row.shadowRoot!.querySelector(".info")!,
|
||||
};
|
||||
};
|
||||
|
||||
const press = (element: Element) =>
|
||||
element.dispatchEvent(
|
||||
new PointerEvent("pointerdown", { bubbles: true, composed: true })
|
||||
);
|
||||
|
||||
const click = (element: Element) =>
|
||||
element.dispatchEvent(
|
||||
new MouseEvent("click", { bubbles: true, composed: true, detail: 1 })
|
||||
);
|
||||
|
||||
describe("hui-generic-entity-row", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("ignores the row click that follows a press on the control", async () => {
|
||||
const { control, moreInfo, rowElement } = await mountRow();
|
||||
press(control);
|
||||
click(rowElement);
|
||||
expect(moreInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lets a click without a press through after a click on the control", async () => {
|
||||
const { control, moreInfo, rowElement } = await mountRow();
|
||||
press(control);
|
||||
click(control);
|
||||
click(rowElement);
|
||||
expect(moreInfo).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("lets a click without a pointer through after an unfinished press on the control", async () => {
|
||||
const { control, moreInfo, rowElement } = await mountRow();
|
||||
press(control);
|
||||
rowElement.dispatchEvent(
|
||||
new MouseEvent("click", { bubbles: true, composed: true, detail: 0 })
|
||||
);
|
||||
expect(moreInfo).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("lets a click on the control reach the control", async () => {
|
||||
const { control, moreInfo } = await mountRow();
|
||||
const controlClick = vi.fn();
|
||||
control.addEventListener("click", controlClick);
|
||||
press(control);
|
||||
click(control);
|
||||
expect(controlClick).toHaveBeenCalledOnce();
|
||||
expect(moreInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("opens more info for a press on the name after a press on the control", async () => {
|
||||
const { control, moreInfo, name } = await mountRow();
|
||||
press(control);
|
||||
press(name);
|
||||
click(name);
|
||||
expect(moreInfo).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("opens more info for a press on the state of a row without a control", async () => {
|
||||
const { control: state, moreInfo, rowElement } = await mountRow(true);
|
||||
press(state);
|
||||
click(rowElement);
|
||||
expect(moreInfo).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
computeCssColor,
|
||||
computeCssVariableName,
|
||||
} from "../../../src/common/color/compute-color";
|
||||
import * as helpers from "../../../src/panels/lovelace/custom-card-helpers";
|
||||
|
||||
// Keep this public API test independent of element registration and rendering.
|
||||
vi.mock(
|
||||
"../../../src/panels/lovelace/create-element/create-badge-element",
|
||||
() => ({ createBadgeElement: vi.fn() })
|
||||
);
|
||||
vi.mock(
|
||||
"../../../src/panels/lovelace/create-element/create-card-element",
|
||||
() => ({ createCardElement: vi.fn() })
|
||||
);
|
||||
vi.mock(
|
||||
"../../../src/panels/lovelace/create-element/create-header-footer-element",
|
||||
() => ({ createHeaderFooterElement: vi.fn() })
|
||||
);
|
||||
vi.mock(
|
||||
"../../../src/panels/lovelace/create-element/create-hui-element",
|
||||
() => ({ createHuiElement: vi.fn() })
|
||||
);
|
||||
vi.mock(
|
||||
"../../../src/panels/lovelace/create-element/create-row-element",
|
||||
() => ({ createRowElement: vi.fn() })
|
||||
);
|
||||
|
||||
describe("custom card color helpers", () => {
|
||||
it("exposes the canonical color functions through the public helper module", () => {
|
||||
expect(helpers.computeCssColor).toBe(computeCssColor);
|
||||
expect(helpers.computeCssVariableName).toBe(computeCssVariableName);
|
||||
});
|
||||
|
||||
it.each(["primary", "amber", "deep-purple", "primary-text"])(
|
||||
"returns theme references for %s without resolving them to fixed colors",
|
||||
(color) => {
|
||||
expect(helpers.computeCssVariableName(color)).toBe(`--${color}-color`);
|
||||
expect(helpers.computeCssColor(color)).toBe(`var(--${color}-color)`);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(["#488fc2", "rgba(12, 34, 56, 0.5)", "var(--custom-color)"])(
|
||||
"leaves the custom CSS color %s unchanged",
|
||||
(color) => {
|
||||
expect(helpers.computeCssVariableName(color)).toBe(color);
|
||||
expect(helpers.computeCssColor(color)).toBe(color);
|
||||
}
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { ReactiveControllerHost } from "lit";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { CoverEntity } from "../../../src/data/cover";
|
||||
import { CoverEntityFeature } from "../../../src/data/cover";
|
||||
import { CoverRequestController } from "../../../src/state-control/cover/cover-request-controller";
|
||||
|
||||
const createHost = (): ReactiveControllerHost => ({
|
||||
addController: vi.fn(),
|
||||
removeController: vi.fn(),
|
||||
requestUpdate: vi.fn(),
|
||||
updateComplete: Promise.resolve(true),
|
||||
});
|
||||
|
||||
const positionCover = (state: string, position: number, tilt?: number) =>
|
||||
({
|
||||
entity_id: "cover.living_room",
|
||||
state,
|
||||
attributes: {
|
||||
supported_features: CoverEntityFeature.SET_POSITION,
|
||||
current_position: position,
|
||||
current_tilt_position: tilt,
|
||||
},
|
||||
}) as CoverEntity;
|
||||
|
||||
const openCloseCover = (state: string) =>
|
||||
({
|
||||
entity_id: "cover.garage",
|
||||
state,
|
||||
attributes: {},
|
||||
}) as CoverEntity;
|
||||
|
||||
describe("CoverRequestController", () => {
|
||||
let controller: CoverRequestController;
|
||||
|
||||
beforeEach(() => {
|
||||
controller = new CoverRequestController(createHost());
|
||||
});
|
||||
|
||||
it("keeps the request until the cover reaches the value", () => {
|
||||
controller.commandSent(
|
||||
{ mode: "position", action: "set", value: 40 },
|
||||
positionCover("open", 100)
|
||||
);
|
||||
expect(controller.request).toEqual({ mode: "position", value: 40 });
|
||||
|
||||
controller.stateChanged(positionCover("closing", 70));
|
||||
expect(controller.request).toEqual({ mode: "position", value: 40 });
|
||||
|
||||
controller.stateChanged(positionCover("open", 40));
|
||||
expect(controller.request).toBeUndefined();
|
||||
});
|
||||
|
||||
it("has no request when the cover is already at the value", () => {
|
||||
controller.commandSent(
|
||||
{ mode: "position", action: "close" },
|
||||
positionCover("closed", 0)
|
||||
);
|
||||
expect(controller.request).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps the request while the cover has not reacted yet", () => {
|
||||
controller.commandSent(
|
||||
{ mode: "position", action: "set", value: 40 },
|
||||
positionCover("open", 100)
|
||||
);
|
||||
controller.stateChanged(positionCover("open", 100));
|
||||
expect(controller.request).toEqual({ mode: "position", value: 40 });
|
||||
});
|
||||
|
||||
it("drops the request when a moving cover stops somewhere else", () => {
|
||||
controller.commandSent(
|
||||
{ mode: "position", action: "set", value: 40 },
|
||||
positionCover("open", 100)
|
||||
);
|
||||
controller.stateChanged(positionCover("closing", 80));
|
||||
controller.stateChanged(positionCover("open", 65));
|
||||
expect(controller.request).toBeUndefined();
|
||||
});
|
||||
|
||||
it("drops the request when the position changes without the cover reporting moving", () => {
|
||||
controller.commandSent(
|
||||
{ mode: "position", action: "set", value: 40 },
|
||||
positionCover("open", 100)
|
||||
);
|
||||
controller.stateChanged(positionCover("open", 80));
|
||||
expect(controller.request).toBeUndefined();
|
||||
});
|
||||
|
||||
it("follows a cover that only opens and closes", () => {
|
||||
controller.commandSent(
|
||||
{ mode: "position", action: "open" },
|
||||
openCloseCover("closed")
|
||||
);
|
||||
expect(controller.request).toEqual({ mode: "position", value: 100 });
|
||||
|
||||
controller.stateChanged(openCloseCover("opening"));
|
||||
expect(controller.request).toEqual({ mode: "position", value: 100 });
|
||||
|
||||
controller.stateChanged(openCloseCover("open"));
|
||||
expect(controller.request).toBeUndefined();
|
||||
});
|
||||
|
||||
it("only drops the request of the stopped mode", () => {
|
||||
const cover = positionCover("open", 100, 100);
|
||||
controller.commandSent({ mode: "tilt", action: "set", value: 20 }, cover);
|
||||
|
||||
controller.commandSent({ mode: "position", action: "stop" }, cover);
|
||||
expect(controller.request).toEqual({ mode: "tilt", value: 20 });
|
||||
|
||||
controller.commandSent({ mode: "tilt", action: "stop" }, cover);
|
||||
expect(controller.request).toBeUndefined();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user