Compare commits

..
Author SHA1 Message Date
Petar Petrov 75aad938d7 Test that the legend shows a hidden dataset again 2026-11-30 14:43:10 +02:00
Petar Petrov 1265060c89 Show or hide devices on the energy devices bar chart
The bar chart gets a header button with a device list, sharing its hidden devices with the pie legend. Hidden devices drop out of the bars, so the axis rescales to the rest.
2026-11-30 14:39:11 +02:00
41 changed files with 579 additions and 1380 deletions

No files matched your search

+12 -12
View File
@@ -54,15 +54,15 @@
"@codemirror/view": "6.44.2",
"@date-fns/tz": "1.5.0",
"@egjs/hammerjs": "2.0.17",
"@formatjs/intl-datetimeformat": "8.2.2",
"@formatjs/intl-displaynames": "8.0.5",
"@formatjs/intl-durationformat": "0.13.2",
"@formatjs/intl-getcanonicallocales": "3.4.2",
"@formatjs/intl-listformat": "9.1.2",
"@formatjs/intl-locale": "5.5.2",
"@formatjs/intl-numberformat": "10.1.2",
"@formatjs/intl-pluralrules": "7.1.2",
"@formatjs/intl-relativetimeformat": "13.0.5",
"@formatjs/intl-datetimeformat": "8.0.3",
"@formatjs/intl-displaynames": "8.0.3",
"@formatjs/intl-durationformat": "0.13.0",
"@formatjs/intl-getcanonicallocales": "3.4.0",
"@formatjs/intl-listformat": "9.1.0",
"@formatjs/intl-locale": "5.5.0",
"@formatjs/intl-numberformat": "10.1.0",
"@formatjs/intl-pluralrules": "7.1.0",
"@formatjs/intl-relativetimeformat": "13.0.3",
"@home-assistant/webawesome": "3.14.0-ha.2",
"@lezer/common": "1.5.7",
"@lezer/highlight": "1.2.5",
@@ -102,13 +102,13 @@
"hls.js": "1.7.4",
"home-assistant-js-websocket": "9.9.0",
"idb-keyval": "6.3.0",
"intl-messageformat": "12.2.1",
"intl-messageformat": "12.2.0",
"js-yaml": "5.5.0",
"leaflet": "1.9.4",
"leaflet.markercluster": "1.5.3",
"lit": "3.3.3",
"lit-html": "3.3.3",
"maplibre-gl": "6.20.0",
"maplibre-gl": "6.19.0",
"marked": "18.3.0",
"memoize-one": "7.0.0",
"nanoid": "6.0.2",
@@ -178,7 +178,7 @@
"core-js-compat": "3.51.0",
"del": "9.0.1",
"eslint": "10.15.0",
"eslint-config-prettier": "10.1.9",
"eslint-config-prettier": "10.1.8",
"eslint-import-resolver-webpack": "0.13.11",
"eslint-plugin-import-x": "4.18.1",
"eslint-plugin-lit": "2.3.1",
+117 -109
View File
@@ -241,32 +241,32 @@ importers:
specifier: 2.0.17
version: 2.0.17
'@formatjs/intl-datetimeformat':
specifier: 8.2.2
version: 8.2.2
specifier: 8.0.3
version: 8.0.3
'@formatjs/intl-displaynames':
specifier: 8.0.5
version: 8.0.5
specifier: 8.0.3
version: 8.0.3
'@formatjs/intl-durationformat':
specifier: 0.13.2
version: 0.13.2
specifier: 0.13.0
version: 0.13.0
'@formatjs/intl-getcanonicallocales':
specifier: 3.4.2
version: 3.4.2
specifier: 3.4.0
version: 3.4.0
'@formatjs/intl-listformat':
specifier: 9.1.2
version: 9.1.2
specifier: 9.1.0
version: 9.1.0
'@formatjs/intl-locale':
specifier: 5.5.2
version: 5.5.2
specifier: 5.5.0
version: 5.5.0
'@formatjs/intl-numberformat':
specifier: 10.1.2
version: 10.1.2
specifier: 10.1.0
version: 10.1.0
'@formatjs/intl-pluralrules':
specifier: 7.1.2
version: 7.1.2
specifier: 7.1.0
version: 7.1.0
'@formatjs/intl-relativetimeformat':
specifier: 13.0.5
version: 13.0.5
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])
@@ -296,7 +296,7 @@ importers:
version: 1.0.3
'@maplibre/maplibre-gl-leaflet':
specifier: 0.1.4
version: 0.1.4(@types/[email protected])([email protected])(maplibre-gl@6.20.0)
version: 0.1.4(@types/[email protected])([email protected])(maplibre-gl@6.19.0)
'@mdi/js':
specifier: 7.4.47
version: 7.4.47
@@ -317,7 +317,7 @@ importers:
version: 4.5.4
'@versatiles/style':
specifier: 9.1.3
version: 9.1.3(maplibre-gl@6.20.0)
version: 9.1.3(maplibre-gl@6.19.0)
'@vibrant/color':
specifier: 4.0.4
version: 4.0.4
@@ -385,8 +385,8 @@ importers:
specifier: 6.3.0
version: 6.3.0
intl-messageformat:
specifier: 12.2.1
version: 12.2.1
specifier: 12.2.0
version: 12.2.0
js-yaml:
specifier: 5.5.0
version: 5.5.0
@@ -403,8 +403,8 @@ importers:
specifier: 3.3.3
version: 3.3.3
maplibre-gl:
specifier: 6.20.0
version: 6.20.0
specifier: 6.19.0
version: 6.19.0
marked:
specifier: 18.3.0
version: 18.3.0
@@ -608,8 +608,8 @@ importers:
specifier: 10.15.0
version: 10.15.0([email protected])
eslint-config-prettier:
specifier: 10.1.9
version: 10.1.9([email protected]([email protected]))
specifier: 10.1.8
version: 10.1.8([email protected]([email protected]))
eslint-import-resolver-webpack:
specifier: 0.13.11
version: 0.13.11([email protected])
@@ -1969,8 +1969,8 @@ packages:
'@floating-ui/[email protected]':
resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==}
'@formatjs/[email protected]2':
resolution: {integrity: sha512-KSFLj/KBZfanDW3BpMytGLrZFB8gGvxbtJkB2NBkw3SW0nR8Yno2Ea2s62vCFaJ4GHfGMWDoXfBxzpfKwOfgAg==}
'@formatjs/[email protected]0':
resolution: {integrity: sha512-npIs6UARNOg5amJY5UOVsd6HUQQfzYjet0sa0SWIqzsnVhxLSpaIx2DjoIVrr/vqmjURjvroeW6dItjfy3Uf8A==}
'@formatjs/[email protected]':
resolution: {integrity: sha512-qrycXDeaORzIqNhBOx0btnhpD1c+/qFIHAN9znofuMJX6QBwtbrmlpWfD4oiUUD2vJUOIYFA/gYtg2KAMGG7sA==}
@@ -1978,8 +1978,8 @@ packages:
'@formatjs/[email protected]':
resolution: {integrity: sha512-Yabmi9nSvyOMrlSeGGWDiH7rf3a7sIwplbvo/dlz9WCIjzIQAfy1RMf4S0X3yG724n5Ghu2GmEl5NJIV6O9sZQ==}
'@formatjs/[email protected].8':
resolution: {integrity: sha512-Y9YFFfeBDkAWmLWD3LVNHbHlyELsP2lYRNoY6+QhtPh1/ujCiX5QYBzAqe0cWdkCxKVezHLt0qjWz1veEUV7UA==}
'@formatjs/[email protected].7':
resolution: {integrity: sha512-zXfhLpvA6T7+efdt9JLbBwZ00tT7NsBMDVnDu8rpHeNNv8KfRZAMo2gkG0k9lK/Nzc//3kJ9pImsfuJxk3KhUA==}
'@formatjs/[email protected]':
resolution: {integrity: sha512-AfiMi5NOSo2TQImsYAg8UYddsNJ/vUEv/HaNqiFjnI3ZFfWihUtD5QtuX6kHl8+H+d3qvnE/3HZrfzgdWpsLNA==}
@@ -1993,41 +1993,41 @@ packages:
'@formatjs/[email protected]':
resolution: {integrity: sha512-IdAJ9NrHn7AF0zqncD9UpxQozTYyJtbwwrZnJMEKVxTcOOXtVkUb2XYTpNOGTAv58NCsk0rjRB9G+i2SvBmGAQ==}
'@formatjs/intl-datetimeformat@8.2.2':
resolution: {integrity: sha512-J1NBeAs3GJRfZRXyLDxK43OMBk+5UDUa7bgwoUNLvr1lUfXACfl+K6DvdQ/mpPaPHimfPOBzGGIX6oDfRlVZNQ==}
'@formatjs/intl-datetimeformat@8.0.3':
resolution: {integrity: sha512-LQed+WhJBlceMJ4Zbe7dDe7Wn15le9t5HXfOFGdJYM/MGDyn56LTHlSzPzFjsJA0rvyp4FjN28jRQiMwtsji6A==}
'@formatjs/[email protected].5':
resolution: {integrity: sha512-1hMhtc8xVlidZ0olqI3MFmOXb2oWXio1wz7QBP3EsLnegmbBeOGU05TxCnIuxClrXNlg+J5I5ossg6Xs2TmsIQ==}
'@formatjs/[email protected].3':
resolution: {integrity: sha512-UhKG1OwrbQzZNKIcmZu+/JR5SOxE25RWmUzxaNfQ04AJ4OwxNkTvAbVX0ojnkm0i8Qs4E8ElIoBdA6F8XTkJXw==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-fP3mpM/8S1L9OXQPkli28xmQhZMEfg/EGub1Yw7/nYKkQqqhdX7xMFZ1QTUFC8epbhM5eIgtGmTqXZ/tNRcAuw==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-hZMyYyxZOb41/WuBaA3F3AQtIR0z3H8kGephf5yaqwiVmEamPh6b7ElWEUEl1xlQsg4Z6/AIHEX0SaWfw2SHAg==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-b0Ywtqh1DS5bc3NXqm2VMbtDN9mYQPVVIEDPkxIi8SlV5eq7NkE0ZET0IHDWgl1lLh74hjGJv8iPy7D/y/SNNA==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-7VfxOKr+ZUL4r5XO+LWiabp+m5595LacC+upPqSYf5RXxY5NDWEs/DJfHrjv59SWXt6UicKZbtNuHcAUZ45AEw==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-9FDt0zvn3IzULi4RrPwU9W5EQ0shaJLIRdet+w85IDwJ6teK729KqCUlEtqfhLfztim0fJ7pt3jD2mDBdZXIrw==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-Hh2kjuXQAsoadfb8ZR7+NRu6txiPJ7qo+3c87C/Ii55CO2lVPFjMp7uxsWUQECCfnuhD6D1HBVdUhmBv66MOwA==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-4v0ZW2KQ8874I4L74zTqk1sWwxogxJzvJV3asaIyyAOJAK5Rjwe9r+SGmLm2HleDq60reuaSRxuiUKIFalWlUw==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-PmM3wB2Uo5Bu8y8itD5Z4NZGOak+1NKsiQydFgxuSXVzOV1GQd3ytkqQ/jOCLDNowcqw7xbL42fYBN9xzm08gA==}
'@formatjs/[email protected].3':
resolution: {integrity: sha512-qHGNMjYbewa1uteT7VFPot2+q9glcBMVRQhmQNXgNYia35Arzln7vJ4Zyj6ktm6POzRc3SW/CTAhhSnMQSFvJg==}
'@formatjs/[email protected].1':
resolution: {integrity: sha512-gBqglQK9rXuHsLmM8wzTMBy4Xo4d0jamirIVKuEL8F1rwbskWdpMA1kZarSkny+uvr5q/K6GSzE0Rcq1wZLl3g==}
'@formatjs/[email protected]':
resolution: {integrity: sha512-ePEgLgVCqi2BBFnTMWPfIghu6FkbZnnBVhO2sSxvLfrdFw7wCHAHiDoM2h4NRgjbaY7+B7HgOLZGkK187pZTZg==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-lBLFsZYJTTvh2oRs+vExpd4Yy+kVe4zPZRwlMohpMQihLLboXicIa2MgN68FwQYqQseeJTBkEWh6dyN1PR4zYA==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-/uAIUEKpVleUU6MMIOHVcA4EetRsEZeMkOeKbQUvWLsDYlVCXl25jDFIbcCjG8uGrBD4fT5p6j3JDXgNYnqodQ==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-ZsLZvUmRH1eZWqiYEj5/e7rtlIBUddSo4u73itGeetxFqbxYCE7nOBcHMH49HgGfmoMSXHW5NWQ7eGfFoM2hhg==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-4uPvqKd9uke8VuimXDbPlK8jEdqpH9q0wFTCOtth15F2xtjLOOfadnCxBNn5eZjOt/7dbTmMCsN8W6FGSDftzg==}
'@formatjs/[email protected].5':
resolution: {integrity: sha512-mqtN0lrWIUkSZu4bluWqCWZ7v5umpWN2JFMv2M3PkqTNqz7h57m3o9lHcAd1yK6gjF+Zs2+RQWaxKQqJ8EN1Mg==}
'@formatjs/[email protected].3':
resolution: {integrity: sha512-5nyIp4F/59A5hcfU6lZphSslpildVSirqudWfygBENGdGSHmggZVjhoad458XWEgtUd6d0JoiwsiUBFLfbqJ9Q==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-PKUOWdNCTmQ9JTKdvsmWYwNRb78dfkb4hKY7XqCFc5sPH2c079NTR9G6VeDEnno+BEMAowAvrQcd0fAjziUXIw==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-JPnyvQq+ze3ek7A4xqjYUDaOLT9uE2OGnovxdkDHPoKHTz2MuxuuMyDyv37jrSn6NJgbR3vtu2VFTvBUdql99Q==}
'@formatjs/[email protected]':
resolution: {integrity: sha512-tDkXnA4qpIFcDWac8CyVJq6oW8DR7W44QDUBsfXWIIJD/FYYen0QoH46W7XsVMFfPOVKkvbufjboZrrWbEfmww==}
@@ -2287,8 +2287,8 @@ packages:
'@mapbox/[email protected]':
resolution: {integrity: sha512-Qf10S1uIHMk20ri/IVBnpS+esUEkVaR5Hftmz88jTInrpmWgPGJfPe3LVjjlE77trLx8tH6qjTG7uWH9hIq/0Q==}
'@maplibre/geojson-vt@7.0.1':
resolution: {integrity: sha512-xq3+TiG4hZtx9lHjq/oZginEBtJLJTJqRVmEIhPDSznlkl231z/p4foorEqASpD233EHO9+GVnnu6GNA4Pl+YQ==}
'@maplibre/geojson-vt@6.3.2':
resolution: {integrity: sha512-7WFEEkeEjg2foQleJOYl7e2ldi4ZiXp8XV2ibqyquFAA/4iaJgtdEKBrfEpPPVem/VkXS1OXqZsHl6V/MwQYeQ==}
'@maplibre/[email protected]':
resolution: {integrity: sha512-k57wcndZIvq3m08g2je4pjUPGr43ffNW3j+gXbymt8Vi2l1lUERUi1UmdTZcTPN8LuDDYOMWRNBaSLwpAu02ew==}
@@ -2297,8 +2297,8 @@ packages:
leaflet: ^1.9.3
maplibre-gl: ^2.4.0 || ^3.3.1 || ^4.3.2 || ^5.0.0 || ^6.0.0
'@maplibre/maplibre-gl-style-spec@26.11.0':
resolution: {integrity: sha512-MQMBqOkmVm7fLLun2l/bwOv9bURkvyEVISo/OYleb9/nsnfjQ6gs29isysARt5FK/k9RFM4SmH4eMTUQGlv0Pw==}
'@maplibre/maplibre-gl-style-spec@26.9.0':
resolution: {integrity: sha512-cQZK2lG3d6I5FjriPZCgJx/LiVMpWqoVibF+cgp2mkQ/P4BIGOsrA3WsvLw1wB28Q9JU9v2fapsQUJUbjjwa6g==}
hasBin: true
'@maplibre/[email protected]':
@@ -5039,8 +5039,8 @@ packages:
resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}
engines: {node: '>=10'}
[email protected].9:
resolution: {integrity: sha512-JnOR0K4u67CWOiSS3vaduGlLUWS32lGiyglMIV6AyvK9DBRpS+QhR2ESKaUe2eWGRsdVmrxy77yaOk2hzDa4Bg==}
[email protected].8:
resolution: {integrity: sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==}
hasBin: true
peerDependencies:
eslint: '>=7.0.0'
@@ -5669,8 +5669,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-UmdmHUmp5CIKKjSoE10la5yfU+AYJAaiYLsodbjL4lji83JNvgOQUjGaGhGrpFCb0Uh7sl7qfP1IyILa8Z40ug==}
[email protected].1:
resolution: {integrity: sha512-GvlBHj5Blu0ro39QT/QEbX3I23GAYvDh9/B+l33NnXjmYe/UoqFgZjNZoqPa6QdWwAliP/i27y5JeKjFkqlbRA==}
[email protected].0:
resolution: {integrity: sha512-zFzW80iYSSJm4V185g3ItJQ96lBZ2RDO8O8qmRiPAAVKYXJeHfDQN2ITdtLlV+CjSi9Lo7zVW9xGt9CPCx7J6A==}
[email protected]:
resolution: {integrity: sha512-7H/2gFSIitxc0hG3nOI1glS8QLo/EHBFFLk8vEUjXY/xu0AdL8jZ9U1IzO2PUm0d2D/ofQcAifb0g6OBkt8U7w==}
@@ -6216,8 +6216,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-C0X0KQmGm3N2ftbTGBhSyuydQ+vV1LC3f3zPvT3RXHXNZrvfPZcoXp/N5DOa8vedX/rTMm2CjTtivFg2STJMRQ==}
maplibre-gl@6.20.0:
resolution: {integrity: sha512-7manvqXeNoN0mKRzenYDopkb3VW9j7iag45RvopkOVFZ7c+La7CBWtK8eBS5bKrI6NyxqAIxPxIG1PMcotcY1w==}
maplibre-gl@6.19.0:
resolution: {integrity: sha512-3bOrnfddggUYudLGJFsYFvqulUyvSxy4iQzd/uURI7ZhgYEZifdSrECujRSghaCpc+v/ZsFI0Y6ZsGSilEtE+w==}
engines: {node: '>=16.14.0', npm: '>=8.1.0'}
[email protected]:
@@ -6717,8 +6717,8 @@ packages:
resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==}
engines: {node: '>=8'}
pbf@5.2.0:
resolution: {integrity: sha512-R6YptaRZl0t9SVO6MllszYq1IkaOQawzprndmvQxEoFrtvX7fT+oNIPoVD152NOllmLWEC3ThxzUTqBX12q5FQ==}
pbf@5.1.2:
resolution: {integrity: sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==}
hasBin: true
[email protected]:
@@ -6994,6 +6994,9 @@ packages:
[email protected]:
resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==}
[email protected]:
resolution: {integrity: sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==}
[email protected]:
resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==}
engines: {node: '>= 0.4'}
@@ -9813,7 +9816,7 @@ snapshots:
'@floating-ui/[email protected]': {}
'@formatjs/[email protected]2': {}
'@formatjs/[email protected]0': {}
'@formatjs/[email protected]':
dependencies:
@@ -9826,7 +9829,7 @@ snapshots:
dependencies:
tslib: 2.9.1
'@formatjs/[email protected].8': {}
'@formatjs/[email protected].7': {}
'@formatjs/[email protected]':
dependencies:
@@ -9845,55 +9848,56 @@ snapshots:
'@formatjs/[email protected]': {}
'@formatjs/intl-datetimeformat@8.2.2':
'@formatjs/intl-datetimeformat@8.0.3':
dependencies:
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/bigdecimal': 0.2.10
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/[email protected].5':
'@formatjs/[email protected].3':
dependencies:
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/[email protected].2':
'@formatjs/[email protected].0':
dependencies:
'@formatjs/bigdecimal': 0.2.12
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/bigdecimal': 0.2.10
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/[email protected].2': {}
'@formatjs/[email protected].0': {}
'@formatjs/[email protected].2':
'@formatjs/[email protected].0':
dependencies:
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/[email protected].2':
'@formatjs/[email protected].0':
dependencies:
'@formatjs/intl-getcanonicallocales': 3.4.2
'@formatjs/intl-supportedvaluesof': 3.1.2
'@formatjs/intl-getcanonicallocales': 3.4.0
'@formatjs/intl-supportedvaluesof': 3.1.0
'@formatjs/[email protected].3':
'@formatjs/[email protected].1':
dependencies:
'@formatjs/fast-memoize': 3.1.8
'@formatjs/fast-memoize': 3.1.7
'@formatjs/[email protected]':
dependencies:
tslib: 2.9.1
'@formatjs/[email protected].2':
'@formatjs/[email protected].0':
dependencies:
'@formatjs/bigdecimal': 0.2.12
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/bigdecimal': 0.2.10
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/[email protected].2':
'@formatjs/[email protected].0':
dependencies:
'@formatjs/bigdecimal': 0.2.12
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/bigdecimal': 0.2.10
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/[email protected].5':
'@formatjs/[email protected].3':
dependencies:
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/[email protected].2':
'@formatjs/[email protected].0':
dependencies:
'@formatjs/fast-memoize': 3.1.8
'@formatjs/fast-memoize': 3.1.7
'@formatjs/[email protected]([email protected])':
dependencies:
@@ -10225,19 +10229,19 @@ snapshots:
dependencies:
'@mapbox/point-geometry': 1.1.0
'@types/geojson': 7946.0.16
pbf: 5.2.0
pbf: 5.1.2
'@maplibre/geojson-vt@7.0.1':
'@maplibre/geojson-vt@6.3.2':
dependencies:
kdbush: 4.1.0
'@maplibre/[email protected](@types/[email protected])([email protected])(maplibre-gl@6.20.0)':
'@maplibre/[email protected](@types/[email protected])([email protected])(maplibre-gl@6.19.0)':
dependencies:
'@types/leaflet': 1.9.23
leaflet: 1.9.4
maplibre-gl: 6.20.0
maplibre-gl: 6.19.0
'@maplibre/maplibre-gl-style-spec@26.11.0':
'@maplibre/maplibre-gl-style-spec@26.9.0':
dependencies:
'@mapbox/jsonlint-lines-primitives': 2.0.3
'@mapbox/unitbezier': 1.0.0
@@ -10254,7 +10258,7 @@ snapshots:
dependencies:
'@mapbox/point-geometry': 1.1.0
'@types/geojson': 7946.0.16
pbf: 5.2.0
pbf: 5.1.2
'@marijn/[email protected]': {}
@@ -11755,11 +11759,11 @@ snapshots:
'@unrs/[email protected]':
optional: true
'@versatiles/[email protected](maplibre-gl@6.20.0)':
'@versatiles/[email protected](maplibre-gl@6.19.0)':
dependencies:
'@maplibre/maplibre-gl-style-spec': 26.11.0
'@maplibre/maplibre-gl-style-spec': 26.9.0
optionalDependencies:
maplibre-gl: 6.20.0
maplibre-gl: 6.19.0
'@vibrant/[email protected]': {}
@@ -12929,7 +12933,7 @@ snapshots:
[email protected]: {}
[email protected].9([email protected]([email protected])):
[email protected].8([email protected]([email protected])):
dependencies:
eslint: 10.15.0([email protected])
@@ -13675,9 +13679,9 @@ snapshots:
'@formatjs/icu-messageformat-parser': 2.11.2
tslib: 2.9.1
[email protected].1:
[email protected].0:
dependencies:
'@formatjs/fast-memoize': 3.1.8
'@formatjs/fast-memoize': 3.1.7
'@formatjs/icu-messageformat-parser': 3.5.23
[email protected]: {}
@@ -14228,14 +14232,14 @@ snapshots:
[email protected]: {}
maplibre-gl@6.20.0:
maplibre-gl@6.19.0:
dependencies:
'@mapbox/point-geometry': 1.1.0
'@mapbox/tiny-sdf': 2.3.0
'@mapbox/unitbezier': 1.0.0
'@mapbox/vector-tile': 3.0.0
'@maplibre/geojson-vt': 7.0.1
'@maplibre/maplibre-gl-style-spec': 26.11.0
'@maplibre/geojson-vt': 6.3.2
'@maplibre/maplibre-gl-style-spec': 26.9.0
'@maplibre/mlt': 1.3.0
'@maplibre/vt-pbf': 4.3.3
'@types/geojson': 7946.0.16
@@ -14244,7 +14248,7 @@ snapshots:
gl-matrix: 3.4.4
kdbush: 4.1.0
murmurhash-js: 1.0.0
pbf: 5.2.0
pbf: 5.1.2
potpack: 2.1.0
quickselect: 3.0.0
tinyqueue: 3.0.0
@@ -14822,9 +14826,9 @@ snapshots:
[email protected]: {}
pbf@5.2.0:
pbf@5.1.2:
dependencies:
protocol-buffers-schema: 3.6.1
resolve-protobuf-schema: 2.1.0
[email protected]: {}
@@ -15054,6 +15058,10 @@ snapshots:
[email protected]: {}
[email protected]:
dependencies:
protocol-buffers-schema: 3.6.1
[email protected]:
dependencies:
es-errors: 1.3.0
@@ -1,74 +0,0 @@
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
import type {
ConditionContext,
VisibilityCondition,
} from "../../panels/lovelace/common/validate-condition";
import { addEntityToCondition } from "../../panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../types";
import type { ConditionEvaluation } from "../controllers/condition-evaluator-controller";
import { ConditionEvaluatorController } from "../controllers/condition-evaluator-controller";
import { dropInvalidConditions } from "./sanitize";
export interface VisibilitySubscription {
/** Pass each new hass object so client-side conditions check again. */
update(hass: HomeAssistant): void;
/** Close the subscriptions. `onChange` is not called again. */
unsubscribe(): void;
}
/**
* Live visibility of a list of dashboard visibility conditions, for code
* without a Lit host, such as custom cards and plugins. Conditions core
* evaluates are subscribed to; the rest are checked locally. Reports
* `unknown` until core replies.
*/
export const subscribeVisibility = (
hass: HomeAssistant,
conditions: VisibilityCondition[],
onChange: (result: ConditionEvaluation, error?: string) => void,
context: ConditionContext = {}
): VisibilitySubscription => {
// The controller only needs a host to register with and to re-render.
const host: ReactiveControllerHost = {
addController: () => undefined,
removeController: () => undefined,
requestUpdate: () => undefined,
updateComplete: Promise.resolve(true),
};
let active = true;
const controller = new ConditionEvaluatorController(host, {
resubscribeDelay: 0,
onResult: (result, error) => {
if (active) {
onChange(result, error);
}
},
});
const sanitized = dropInvalidConditions(conditions);
const { entity_id: entityId } = context;
// Core-evaluated conditions never see the context, so fold its entity in
// first, as the dashboard mixin does.
const validConditions = entityId
? sanitized.map((condition) => addEntityToCondition(condition, entityId))
: sanitized;
const getContext = () => context;
controller.hostConnected();
controller.observe(validConditions, hass, getContext);
return {
update: (newHass) => {
if (active) {
controller.observe(validConditions, newHass, getContext);
}
},
unsubscribe: () => {
active = false;
controller.hostDisconnected();
},
};
};
@@ -1,33 +0,0 @@
import { mdiVideoOffOutline } from "@mdi/js";
import { css, html, LitElement } from "lit";
import { customElement } from "lit/decorators";
import "../ha-svg-icon";
/**
* @element ha-camera-placeholder
*
* @summary Shows instead of a camera's picture when there is none, like
* while the camera is unavailable.
*/
@customElement("ha-camera-placeholder")
export class HaCameraPlaceholder extends LitElement {
protected render() {
return html`<ha-svg-icon .path=${mdiVideoOffOutline}></ha-svg-icon>`;
}
static styles = css`
:host {
display: flex;
align-items: center;
justify-content: center;
color: var(--secondary-text-color);
--mdc-icon-size: 40px;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-camera-placeholder": HaCameraPlaceholder;
}
}
+12 -66
View File
@@ -22,16 +22,12 @@ import type { LocalizeFunc } from "../../common/translations/localize";
import { nextRender } from "../../common/util/render-status";
import type { CameraCapabilities, CameraEntity } from "../../data/camera";
import type { CameraStreamStatus } from "../../data/camera-streams";
import {
showCameraStreamInfoDialog,
type CameraStreamInfo,
} from "../../dialogs/camera/show-dialog-camera-stream-info";
import { showCameraStreamInfoDialog } from "../../dialogs/camera/show-dialog-camera-stream-info";
import "../ha-camera-stream";
import type { HaCameraStream } from "../ha-camera-stream";
import "../ha-icon-button";
import "../ha-spinner";
import "../ha-svg-icon";
import "./ha-camera-placeholder";
import "./ha-camera-stream-badge";
import {
fitPicture,
@@ -111,8 +107,6 @@ export class HaCameraPlayer extends LitElement {
@state() private _capabilities?: CameraCapabilities;
private _streamInfoCallbacks = new Set<(info: CameraStreamInfo) => void>();
@state() private _video?: HTMLVideoElement;
@state() private _muted = false;
@@ -218,7 +212,6 @@ export class HaCameraPlayer extends LitElement {
);
clearTimeout(this._controlsTimeout);
clearTimeout(this._wheelHintTimeout);
this._streamInfoCallbacks.clear();
this._unbindVideo(this._video);
this._video = undefined;
this._pointers.clear();
@@ -258,10 +251,6 @@ export class HaCameraPlayer extends LitElement {
this._unbindVideo(changedProps.get("_video") as HTMLVideoElement);
this._bindVideo(this._video);
}
if (changedProps.has("_status") || changedProps.has("_capabilities")) {
const info = this._streamInfo();
this._streamInfoCallbacks.forEach((callback) => callback(info));
}
}
protected render() {
@@ -273,12 +262,11 @@ export class HaCameraPlayer extends LitElement {
// controls and zoom of this one can't reach, so it shows just the stream
const inApp = Boolean(status.inApp);
const zoomed = !inApp && isZoomed(this._zoom);
// Stays while not live, so the user sees what happens
// Stays while the connection changes, so the user sees what happens
const badgeVisible =
this._controlsVisible ||
status.connecting ||
Boolean(status.unavailable) ||
Boolean(status.disconnected);
status.upgrading !== undefined;
return html`
<div
@@ -331,11 +319,6 @@ export class HaCameraPlayer extends LitElement {
@camera-capabilities-changed=${this._capabilitiesChanged}
@camera-poster-size-changed=${this._posterSizeChanged}
></ha-camera-stream>
${
status.unavailable
? html`<ha-camera-placeholder></ha-camera-placeholder>`
: nothing
}
</div>
${inApp ? nothing : this._renderControls(status, zoomed, badgeVisible)}
</div>
@@ -349,10 +332,7 @@ export class HaCameraPlayer extends LitElement {
) {
return html`
${
this._paused &&
!status.connecting &&
!status.unavailable &&
!status.disconnected
this._paused && !status.connecting
? html`<ha-icon-button
class="control pinned play"
.label=${this._localize("ui.components.camera-player.play")}
@@ -563,21 +543,15 @@ export class HaCameraPlayer extends LitElement {
) {
const oldStatus = this._status;
this._status = ev.detail;
if (ev.detail.inApp || ev.detail.unavailable) {
if (ev.detail.inApp) {
this._zoom = ZOOM_PAN_IDENTITY;
}
if (
oldStatus.connecting !== ev.detail.connecting ||
oldStatus.unavailable !== ev.detail.unavailable ||
oldStatus.disconnected !== ev.detail.disconnected
) {
// Shows the new state for a moment
this._showControls();
}
if (
oldStatus.connecting !== ev.detail.connecting ||
oldStatus.type !== ev.detail.type
) {
// Shows the new connection for a moment
this._showControls();
this._updateVideo();
}
}
@@ -612,26 +586,10 @@ export class HaCameraPlayer extends LitElement {
this._posterSize = ev.detail.size;
}
private _streamInfo(): CameraStreamInfo {
return {
status: this._status,
supportedTypes: this._capabilities?.frontend_stream_types,
};
}
private _subscribeStreamInfo = (
callback: (info: CameraStreamInfo) => void
) => {
this._streamInfoCallbacks.add(callback);
callback(this._streamInfo());
return () => {
this._streamInfoCallbacks.delete(callback);
};
};
private _showStreamInfo() {
showCameraStreamInfoDialog(this, {
subscribe: this._subscribeStreamInfo,
status: this._status,
supportedTypes: this._capabilities?.frontend_stream_types,
});
}
@@ -862,17 +820,12 @@ export class HaCameraPlayer extends LitElement {
this._zoom = refitZoomPan(this._zoom, oldViewport, viewport);
};
// The app's own player and a camera without picture can't be zoomed
private _canZoom(): boolean {
return !this._status.inApp && !this._status.unavailable;
}
private _resetZoom() {
this._zoom = ZOOM_PAN_IDENTITY;
}
private _wheel(ev: WheelEvent) {
if (!this._viewport || !this._canZoom()) {
if (!this._viewport || this._status.inApp) {
return;
}
// A pinch on a touchpad scrolls with ctrl held
@@ -916,7 +869,7 @@ export class HaCameraPlayer extends LitElement {
}
private _doubleClick(ev: MouseEvent) {
if (!this._viewport || !this._canZoom()) {
if (!this._viewport || this._status.inApp) {
return;
}
if (isZoomed(this._zoom)) {
@@ -959,8 +912,7 @@ export class HaCameraPlayer extends LitElement {
this._showControls();
}
const pointer = this._pointers.get(ev.pointerId);
// Taps still toggle the controls when the picture can't be zoomed
if (!pointer || !this._viewport || !this._canZoom()) {
if (!pointer || !this._viewport) {
return;
}
const { rect, viewport } = this._measureViewport();
@@ -1154,12 +1106,6 @@ export class HaCameraPlayer extends LitElement {
transition: transform var(--ha-animation-duration-fast) ease-out;
}
ha-camera-placeholder {
position: absolute;
inset: 0;
color: rgba(255, 255, 255, 0.5);
}
.viewport.gesture ha-camera-stream {
transition: none;
will-change: transform;
+52 -25
View File
@@ -6,6 +6,7 @@ import type {
CameraStreamStatus,
CameraStreamType,
} from "../../data/camera-streams";
import "../ha-spinner";
/** Names of the protocols, the same in every language. */
export const CAMERA_STREAM_TYPE_NAMES: Record<CameraStreamType, string> = {
@@ -15,10 +16,8 @@ export const CAMERA_STREAM_TYPE_NAMES: Record<CameraStreamType, string> = {
};
/**
* @element ha-camera-stream-badge
*
* @summary Shows over a camera stream whether it is live. Selecting it
* shows how it is connected.
* Shows over a camera stream how it is connected. A faster stream that still
* connects in the background is shown next to the current one.
*/
@customElement("ha-camera-stream-badge")
export class HaCameraStreamBadge extends LitElement {
@@ -33,27 +32,51 @@ export class HaCameraStreamBadge extends LitElement {
if (!status) {
return nothing;
}
const connection = status.disconnected
? "disconnected"
: status.unavailable
? "unavailable"
: status.connecting || !status.type
? "connecting"
: "live";
const connecting = status.connecting || !status.type;
const label = connecting
? this._localize("ui.components.camera-player.connecting")
: CAMERA_STREAM_TYPE_NAMES[status.type!];
return html`
<button type="button" class=${connection} aria-describedby="details">
<span class="dot"></span>
<span class="label"
>${this._localize(`ui.components.camera-player.${connection}`)}</span
>
</button>
<span id="details" hidden
>${this._localize("ui.components.camera-player.show_details")}</span
<button
type="button"
aria-label=${this._ariaLabel(status)}
class=${connecting ? "connecting" : "live"}
>
<span class="dot"></span>
<span class="label">${label}</span>
${
status.upgrading
? html`<span class="upgrading" aria-hidden="true">
<ha-spinner></ha-spinner>
${CAMERA_STREAM_TYPE_NAMES[status.upgrading]}
</span>`
: nothing
}
</button>
`;
}
private _ariaLabel(status: CameraStreamStatus): string {
if (status.connecting || !status.type) {
return this._localize(
"ui.components.camera-player.stream_info_connecting"
);
}
if (status.upgrading) {
return this._localize(
"ui.components.camera-player.stream_info_upgrading",
{
type: CAMERA_STREAM_TYPE_NAMES[status.type],
upgrading: CAMERA_STREAM_TYPE_NAMES[status.upgrading],
}
);
}
return this._localize("ui.components.camera-player.stream_info", {
type: CAMERA_STREAM_TYPE_NAMES[status.type],
});
}
static styles = css`
:host {
display: inline-flex;
@@ -97,12 +120,16 @@ export class HaCameraStreamBadge extends LitElement {
animation: pulse 1.2s ease-in-out infinite;
}
.unavailable .dot {
background-color: rgba(255, 255, 255, 0.5);
}
.disconnected .dot {
background-color: var(--ha-color-red-60);
.upgrading {
display: inline-flex;
align-items: center;
gap: var(--ha-space-1);
padding-inline-start: var(--ha-space-1);
border-inline-start: 1px solid rgba(255, 255, 255, 0.3);
opacity: 0.7;
--ha-spinner-indicator-color: var(--ha-color-white);
--ha-spinner-size: 10px;
--ha-spinner-divider-color: rgba(255, 255, 255, 0.3);
}
@keyframes pulse {
+11 -9
View File
@@ -1048,22 +1048,24 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
return [primaryId, ...(customLegendItem?.secondaryIds || [])];
}
// Parses the options structure and adds all ids of unselected legend items to hiddenDatasets.
// No known need to remove items at this time.
// Hides the datasets of legend items selected as false and shows those selected as true.
private _updateHiddenStatsFromOptions(options: HaECOption | undefined) {
if (!options) return;
const legend = ensureArray(this.options?.legend || [])[0] as
LegendComponentOption | undefined;
const hiddenCount = this._hiddenDatasets.size;
let changed = false;
Object.entries(legend?.selected || {}).forEach(([stat, selected]) => {
if (selected === false) {
this._getAllIdsFromLegend(options, stat).forEach((id) =>
this._hiddenDatasets.add(id)
);
}
this._getAllIdsFromLegend(options, stat).forEach((id) => {
if (selected === false && !this._hiddenDatasets.has(id)) {
this._hiddenDatasets.add(id);
changed = true;
} else if (selected === true && this._hiddenDatasets.delete(id)) {
changed = true;
}
});
});
// Flagging this rebuilds and downsamples every series, so only when needed
if (this._hiddenDatasets.size !== hiddenCount) {
if (changed) {
this.requestUpdate("_hiddenDatasets");
}
}
+17 -116
View File
@@ -34,8 +34,6 @@ import {
connectionContext,
formattersContext,
} from "../data/context";
import { UNAVAILABLE } from "../data/entity/entity";
import "./camera/ha-camera-placeholder";
import "./ha-hls-player";
import type { HaHLSPlayer } from "./ha-hls-player";
import "./ha-mjpeg-player";
@@ -113,13 +111,6 @@ export class HaCameraStream extends LitElement {
// The app plays the HLS stream in its own player, over the page
@state() private _hlsInApp = false;
// WebRTC is the only stream and failed, its player shows why
@state() private _webRtcFailed = false;
// The MJPEG image failed, it is tried again with the next access token or
// once Home Assistant reconnects
@state() private _mjpegImageFailed = false;
@query("ha-web-rtc-player") private _webRtcPlayer?: HaWebRtcPlayer;
@query("ha-mjpeg-player") private _mjpegPlayer?: HaMjpegPlayer;
@@ -162,32 +153,9 @@ export class HaCameraStream extends LitElement {
this._config.config.state === STATE_RUNNING &&
oldConfig.config?.state !== STATE_RUNNING;
const oldStateObj = changedProps.get("stateObj") as
CameraEntity | undefined;
const becameAvailable =
!entityChanged &&
this.stateObj !== undefined &&
oldStateObj?.state === UNAVAILABLE &&
!this._unavailable;
if (entityChanged || backendStarted || becameAvailable) {
if (this._unavailable) {
// Core often doesn't know the camera then, as its integration
// didn't load. Its capabilities are fetched once it is back.
this._clearCapabilities();
} else {
this._getCapabilities();
this._getPosterUrl();
}
}
if (
oldStateObj &&
oldStateObj.attributes.access_token !==
this.stateObj?.attributes.access_token
) {
// A new token gives a new MJPEG address, worth another try
this._mjpegImageFailed = false;
if (entityChanged || backendStarted) {
this._getCapabilities();
this._getPosterUrl();
}
const oldConnection = changedProps.get("_connection") as
@@ -202,10 +170,6 @@ export class HaCameraStream extends LitElement {
}
}
private get _unavailable(): boolean {
return this.stateObj?.state === UNAVAILABLE;
}
/** The microphone track sent to the camera, only on WebRTC streams. */
public get microphoneTrack(): MediaStreamTrack | undefined {
return this._webRtcPlayer?.microphoneTrack;
@@ -274,63 +238,29 @@ export class HaCameraStream extends LitElement {
this._visibleStreamType = visibleStreamType;
fireEvent(this, "stream-type-changed", { type: visibleStreamType });
}
const status = this._computeStatus(streams, visibleStreamType);
const status: CameraStreamStatus = {
...computeCameraStreamStatus(
streams,
// Nothing plays while Home Assistant is disconnected
this._connection.connected ? this._loadedStreams : new Set(),
this._hlsStreams,
this._webRtcStreams
),
inApp: visibleStreamType === STREAM_TYPE_HLS && this._hlsInApp,
};
if (
!this._status ||
status.type !== this._status.type ||
status.connecting !== this._status.connecting ||
status.upgrading !== this._status.upgrading ||
status.hasAudio !== this._status.hasAudio ||
status.inApp !== this._status.inApp ||
status.unavailable !== this._status.unavailable ||
status.disconnected !== this._status.disconnected
status.inApp !== this._status.inApp
) {
this._status = status;
fireEvent(this, "camera-stream-status-changed", status);
}
}
private _computeStatus(
streams: CameraStream[],
visibleStreamType?: CameraStreamType
): CameraStreamStatus {
// A playing WebRTC stream can come straight from the camera or an
// external go2rtc, it then keeps playing without Home Assistant
const playsWithoutHomeAssistant =
visibleStreamType === STREAM_TYPE_WEB_RTC &&
this._loadedStreams.has(STREAM_TYPE_WEB_RTC);
const inApp = visibleStreamType === STREAM_TYPE_HLS && this._hlsInApp;
if (!this._connection.connected && !playsWithoutHomeAssistant) {
// Kept so the player still shows its placeholder instead of nothing
return {
connecting: false,
hasAudio: false,
inApp,
disconnected: "home_assistant",
unavailable: this._unavailable,
};
}
if (this._unavailable) {
return { connecting: false, hasAudio: false, unavailable: true };
}
if (this._webRtcFailed) {
return {
connecting: false,
hasAudio: false,
disconnected: "stream_failed",
};
}
return {
...computeCameraStreamStatus(
streams,
this._loadedStreams,
this._hlsStreams,
this._webRtcStreams
),
inApp,
};
}
protected render() {
if (!this.stateObj) {
return nothing;
@@ -367,11 +297,6 @@ export class HaCameraStream extends LitElement {
@load=${this._handleMjpegLoad}
></ha-mjpeg-player>`;
}
if (this._mjpegImageFailed) {
return html`<ha-camera-placeholder
style=${styleMap({ aspectRatio: this.aspectRatio ?? 16 / 9 })}
></ha-camera-placeholder>`;
}
return html`<img
.src=${streamUrl}
style=${styleMap({
@@ -380,7 +305,6 @@ export class HaCameraStream extends LitElement {
})}
alt=${`Preview of the ${this._formatters?.formatEntityName(this.stateObj) ?? ""} camera.`}
@load=${this._handleImageLoad}
@error=${this._handleImageError}
/>`;
}
@@ -422,9 +346,6 @@ export class HaCameraStream extends LitElement {
}
private _currentStreams() {
if (this._unavailable) {
return [];
}
return this._streams(
this._capabilities?.frontend_stream_types,
this._hlsStreams,
@@ -432,15 +353,10 @@ export class HaCameraStream extends LitElement {
);
}
/** Returns the request number, so an older request can be dropped. */
private _clearCapabilities() {
private async _getCapabilities() {
this._capabilities = undefined;
this._resetStreams();
return ++this._capabilitiesRequest;
}
private async _getCapabilities() {
const request = this._clearCapabilities();
const request = ++this._capabilitiesRequest;
if (!supportsFeature(this.stateObj!, CameraEntityFeature.STREAM)) {
this._capabilities = {
frontend_stream_types: [],
@@ -463,14 +379,11 @@ export class HaCameraStream extends LitElement {
this._webRtcStreams = undefined;
this._loadedStreams = new Set();
this._hlsInApp = false;
this._webRtcFailed = false;
this._mjpegImageFailed = false;
this._mjpegPlayer?.restart();
}
private _restartMjpeg() {
this._setLoaded(MJPEG_STREAM, false);
this._mjpegImageFailed = false;
this._mjpegPlayer?.restart();
}
@@ -530,11 +443,6 @@ export class HaCameraStream extends LitElement {
fireEvent(this, "load");
}
private _handleImageError() {
this._mjpegImageFailed = true;
this._setLoaded(MJPEG_STREAM, false);
}
private _handleMjpegLoad() {
this._setLoaded(MJPEG_STREAM, true);
}
@@ -550,7 +458,6 @@ export class HaCameraStream extends LitElement {
}
private _handleWebRtcLoad() {
this._webRtcFailed = false;
this._setLoaded(STREAM_TYPE_WEB_RTC, true);
}
@@ -570,7 +477,6 @@ export class HaCameraStream extends LitElement {
) {
// Without another stream type, keep the player to show why it failed.
// Only a browser without WebRTC falls back to MJPEG.
this._webRtcFailed = true;
this._setLoaded(STREAM_TYPE_WEB_RTC, false);
return;
}
@@ -604,15 +510,10 @@ export class HaCameraStream extends LitElement {
display: block;
}
img,
ha-camera-placeholder {
img {
width: 100%;
}
ha-camera-placeholder {
background-color: var(--ha-color-fill-neutral-normal-resting);
}
ha-web-rtc-player {
width: 100%;
height: 100%;
+1 -6
View File
@@ -139,17 +139,12 @@ export class HaControlCircularSlider extends LitElement {
protected updated(changedProps: PropertyValues): void {
super.updated(changedProps);
const activeValue = this._getActiveValue();
if (
this._activeSlider &&
activeValue != null &&
changedProps.has(this._activeSlider) &&
this[this._activeSlider] !== this._lastChanging
) {
this._lastChanging = this._steppedValue(activeValue);
fireEvent(this, `${this._activeSlider}-changing`, {
value: this._lastChanging,
});
this._lastChanging = undefined;
}
if (!this._activeSlider) {
if (changedProps.has("value")) {
-9
View File
@@ -73,15 +73,6 @@ export class HaDropdown extends Dropdown {
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/naming-convention
private override async showMenu() {
// Flip away from the safe areas instead of opening into them, where the
// max-height below would squeeze the menu.
const styles = getComputedStyle(this);
// @ts-ignore flipPadding is typed as a number, floating-ui accepts sides
this.popup.flipPadding = {
top: parseFloat(styles.getPropertyValue("--safe-area-inset-top")) || 0,
bottom:
parseFloat(styles.getPropertyValue("--safe-area-inset-bottom")) || 0,
};
// @ts-ignore
await super.showMenu();
const triggerElement = this.getTrigger();
+17 -1
View File
@@ -9,6 +9,12 @@ import "./ha-svg-icon";
*/
@customElement("ha-filter-pane-chip")
export class HaFilterPaneChip extends LitElement {
// A dropdown returns focus to its trigger, which is this host
static override shadowRootOptions: ShadowRootInit = {
...LitElement.shadowRootOptions,
delegatesFocus: true,
};
@property() public label = "";
/** SVG path of the leading icon. */
@@ -21,10 +27,15 @@ export class HaFilterPaneChip extends LitElement {
@property({ type: Boolean }) public disabled = false;
/** Shows only the icon and moves the label to the tooltip. */
@property({ type: Boolean, reflect: true, attribute: "hide-label" })
public hideLabel = false;
protected render() {
return html`
<ha-assist-chip
.label=${this.label}
.label=${this.hideLabel ? "" : this.label}
.title=${this.hideLabel ? this.label : ""}
.active=${this.active}
.disabled=${this.disabled}
>
@@ -45,6 +56,11 @@ export class HaFilterPaneChip extends LitElement {
--ha-assist-chip-container-shape: 10px;
}
:host([hide-label]) {
--ha-assist-chip-icon-label-space: 0;
--ha-assist-chip-trailing-space: 8px;
}
.badge {
position: absolute;
top: -4px;
+14 -30
View File
@@ -42,8 +42,6 @@ export class HaMjpegPlayer extends LitElement {
private _drawInterval?: number;
private _copyingFrame = false;
/** The video for picture in picture, undefined when it can't be shown. */
public get videoElement(): HTMLVideoElement | undefined {
return this._canCopy ? this._videoEl : undefined;
@@ -68,13 +66,12 @@ export class HaMjpegPlayer extends LitElement {
}
try {
if (!this._stream) {
// The canvas already has a frame from the copy test
this._copyFrame();
this._drawFrame();
// Captures a frame whenever the canvas is drawn
this._stream = this._canvas!.captureStream();
video.srcObject = this._stream;
this._drawInterval = window.setInterval(
() => this._copyFrame(),
() => this._drawFrame(),
1000 / PICTURE_IN_PICTURE_FRAME_RATE
);
}
@@ -181,45 +178,32 @@ export class HaMjpegPlayer extends LitElement {
/** An image from another origin can't be copied out of a canvas. */
private _testCopy(): boolean {
const image = this._imageEl!;
try {
this._drawFrame(image, image.naturalWidth, image.naturalHeight);
this._canvas!.getContext("2d")?.getImageData(0, 0, 1, 1);
return true;
this._drawFrame();
this._canvas?.getContext("2d")?.getImageData(0, 0, 1, 1);
return Boolean(this._canvas);
} catch (_err: unknown) {
return false;
}
}
// Firefox only draws the first frame of an MJPEG image, a bitmap of it
// has the current one
private async _copyFrame() {
private _drawFrame() {
const image = this._imageEl;
if (this._copyingFrame || !image?.naturalWidth) {
if (!image?.naturalWidth) {
return;
}
this._copyingFrame = true;
try {
const bitmap = await createImageBitmap(image);
this._drawFrame(bitmap, bitmap.width, bitmap.height);
bitmap.close();
} catch (_err: unknown) {
// The stream is between frames or restarting, the next copy tries again
} finally {
this._copyingFrame = false;
}
}
private _drawFrame(frame: CanvasImageSource, width: number, height: number) {
if (!this._canvas) {
this._canvas = document.createElement("canvas");
}
const canvas = this._canvas;
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
if (
canvas.width !== image.naturalWidth ||
canvas.height !== image.naturalHeight
) {
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
}
canvas.getContext("2d")?.drawImage(frame, 0, 0);
canvas.getContext("2d")?.drawImage(image, 0, 0);
}
private _stopVideo = () => {
+15 -47
View File
@@ -23,7 +23,6 @@ import {
getPanelIcon,
getPanelIconPath,
getPanelTitle,
getSelectedPanelUrlPath,
} from "../data/panel";
import type { PersistentNotification } from "../data/persistent_notification";
import { subscribeNotifications } from "../data/persistent_notification";
@@ -232,36 +231,12 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
return nothing;
}
const selectedPanel = this.hass.panelUrl;
// prettier-ignore
return html`
${this._renderHeader()}
${this._renderAllPanels()}`;
}
private _computeSidebarPanels(): [PanelInfo[], PanelInfo[]] | undefined {
if (!this._panelOrder || !this._hiddenPanels) {
return undefined;
}
return computePanels(
this.hass.panels,
getDefaultPanelUrlPath(this.hass),
this._panelOrder,
this._hiddenPanels,
this.hass.locale
);
}
private _computeSelectedPanel(
sidebarPanels: [PanelInfo[], PanelInfo[]] | undefined,
route: Route | undefined
): string {
if (!route) {
return this.hass.panelUrl;
}
const urlPaths = (sidebarPanels ?? [[], []])
.flat()
.map((panel) => panel.url_path);
return getSelectedPanelUrlPath(urlPaths, route.path);
${this._renderAllPanels(selectedPanel)}`;
}
protected shouldUpdate(changedProps: PropertyValues): boolean {
@@ -279,20 +254,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
) {
return true;
}
if (!this.hass) {
return false;
}
if (changedProps.has("route")) {
const sidebarPanels = this._computeSidebarPanels();
const oldRoute = changedProps.get("route") as Route | undefined;
if (
this._computeSelectedPanel(sidebarPanels, oldRoute) !==
this._computeSelectedPanel(sidebarPanels, this.route)
) {
return true;
}
}
if (!changedProps.has("hass")) {
if (!this.hass || !changedProps.has("hass")) {
return false;
}
const oldHass = changedProps.get("hass") as HomeAssistant;
@@ -393,9 +355,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
</div>`;
}
private _renderAllPanels() {
const sidebarPanels = this._computeSidebarPanels();
const selectedPanel = this._computeSelectedPanel(sidebarPanels, this.route);
private _renderAllPanels(selectedPanel: string) {
const renderList = (content, cls: string, scrollable: boolean) =>
html`<ha-list-nav
class=${classMap({
@@ -405,7 +365,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
>${content}</ha-list-nav
>`;
if (!sidebarPanels) {
if (!this._panelOrder || !this._hiddenPanels) {
return html`<div class="panels-list">
<div class="wrapper">
${renderList(
@@ -430,7 +390,15 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
</div>`;
}
const [beforeSpacer, afterSpacer] = sidebarPanels;
const defaultPanel = getDefaultPanelUrlPath(this.hass);
const [beforeSpacer, afterSpacer] = computePanels(
this.hass.panels,
defaultPanel,
this._panelOrder,
this._hiddenPanels,
this.hass.locale
);
// prettier-ignore
return html`<div class="panels-list">
-1
View File
@@ -200,7 +200,6 @@ class HaEntityMarker extends LitElement {
}
.entity-picture {
background-size: cover;
background-position: center;
height: 100%;
width: 100%;
}
-6
View File
@@ -79,8 +79,6 @@ export const selectCameraStreams = ({
];
};
export type CameraStreamDisconnectReason = "home_assistant" | "stream_failed";
/** What the player tells the user about the connection of its stream. */
export interface CameraStreamStatus {
/** The stream that is shown, undefined until the camera's types are known */
@@ -93,10 +91,6 @@ export interface CameraStreamStatus {
hasAudio: boolean;
/** The app plays the shown stream in its own player, over the page */
inApp?: boolean;
/** The camera is unavailable, no stream is started */
unavailable?: boolean;
/** Home Assistant is disconnected, or the only stream failed */
disconnected?: CameraStreamDisconnectReason;
}
export const computeCameraStreamStatus = (
-15
View File
@@ -196,21 +196,6 @@ export const getPanelIconPath = (panel: PanelInfo): string | undefined => {
export const FIXED_PANELS = [PROFILE_PANEL, "config", NOT_FOUND_PANEL];
// A panel's url_path can span several segments (e.g. "config/logs"), so the
// most specific url_path matching the path wins over its first segment.
export const getSelectedPanelUrlPath = (
urlPaths: string[],
path: string
): string =>
urlPaths.reduce(
(selected, urlPath) =>
urlPath.length > selected.length &&
(path === `/${urlPath}` || path.startsWith(`/${urlPath}/`))
? urlPath
: selected,
path.split("/")[1] ?? ""
);
export interface PanelMutableParams {
title?: string | null;
icon?: string | null;
@@ -28,10 +28,7 @@ import { fetchCloudStatus } from "../../data/cloud";
import { apiContext, configContext } from "../../data/context";
import { haStyleDialog, haStyleDialogFixedTop } from "../../resources/styles";
import { DialogMixin } from "../dialog-mixin";
import type {
CameraStreamInfo,
CameraStreamInfoDialogParams,
} from "./show-dialog-camera-stream-info";
import type { CameraStreamInfoDialogParams } from "./show-dialog-camera-stream-info";
// Ordered from the fastest to the most compatible
const STREAM_TYPES: { type: CameraStreamType; icon: string }[] = [
@@ -56,23 +53,6 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
@state() private _cloudIceServers = false;
@state() private _info?: CameraStreamInfo;
private _unsubscribe?: () => void;
public connectedCallback() {
super.connectedCallback();
this._unsubscribe = this.params?.subscribe((info) => {
this._info = info;
});
}
public disconnectedCallback() {
this._unsubscribe?.();
this._unsubscribe = undefined;
super.disconnectedCallback();
}
protected firstUpdated() {
this._fetchCloudIceServers();
}
@@ -94,10 +74,10 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
}
protected render() {
if (!this._info) {
if (!this.params) {
return nothing;
}
const { status, supportedTypes } = this._info;
const { status, supportedTypes } = this.params;
// Without a video stream, still images are all the camera has
const stillImagesOnly = supportedTypes?.length === 0;
// MJPEG is only the fallback, only worth explaining while it shows
@@ -126,22 +106,6 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
: "ui.dialogs.camera_stream_info.intro"
)}
</p>
${
status.disconnected
? html`<ha-alert alert-type="error">
${this._localize(
`ui.dialogs.camera_stream_info.disconnected.${status.disconnected}`
)}
</ha-alert>`
: nothing
}
${
status.unavailable
? html`<ha-alert alert-type="warning">
${this._localize("ui.dialogs.camera_stream_info.unavailable")}
</ha-alert>`
: nothing
}
${
mjpegInUse && !stillImagesOnly
? html`<ha-alert alert-type="info">
@@ -181,7 +145,7 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
type: CameraStreamType;
icon: string;
}) {
const { status } = this._info!;
const { status } = this.params!;
const current = !status.connecting && status.type === type;
const upgrading = status.upgrading === type;
return html`
@@ -1,17 +1,12 @@
import { fireEvent } from "../../common/dom/fire_event";
import type { CameraStreamStatus, StreamType } from "../../data/camera-streams";
export interface CameraStreamInfo {
export interface CameraStreamInfoDialogParams {
status: CameraStreamStatus;
/** The stream types the camera supports, undefined while unknown */
supportedTypes?: StreamType[];
}
export interface CameraStreamInfoDialogParams {
/** Calls back with the current info right away and on every change */
subscribe: (callback: (info: CameraStreamInfo) => void) => () => void;
}
export const showCameraStreamInfoDialog = (
element: HTMLElement,
params: CameraStreamInfoDialogParams
@@ -324,10 +324,6 @@ class MoreInfoCamera extends LitElement {
ev: HASSDomEvent<HASSDomEvents["stream-type-changed"]>
) {
this._streamType = ev.detail.type;
// A removed WebRTC player can't tell that its microphone stopped
if (ev.detail.type !== STREAM_TYPE_WEB_RTC && !this._useAppMicrophone) {
this._microphoneState = "off";
}
}
private _capabilitiesChanged(
-6
View File
@@ -2,10 +2,4 @@ import "@webcomponents/scoped-custom-element-registry/scoped-custom-element-regi
import "../resources/scoped-registry-ready";
import "../layouts/home-assistant";
// Custom cards and plugins can reach the helpers on any page, not only once a
// dashboard has loaded.
Object.assign(window, {
loadCardHelpers: () => import("../panels/lovelace/custom-card-helpers"),
});
import("../resources/append-ha-style");
+2
View File
@@ -11,6 +11,7 @@ import {
import { loadTokens, saveTokens } from "../common/auth/token_storage";
import { hassUrl } from "../data/auth";
import { isExternal } from "../data/external";
import { subscribeFrontendUserData } from "../data/frontend";
import { fetchConfig } from "../data/lovelace/config/types";
import { fetchResources } from "../data/lovelace/resource";
import { MAIN_WINDOW_NAME } from "../data/main_window";
@@ -187,6 +188,7 @@ window.hassConnection.then(({ conn }) => {
subscribePanels(conn, noop);
subscribeThemes(conn, noop);
subscribeUser(conn, noop);
subscribeFrontendUserData(conn, "core", noop);
subscribeRepairsIssueRegistry(conn, noop);
const preloadWindow = window as WindowWithPreloads;
+19 -14
View File
@@ -1,9 +1,21 @@
import { supportsFeatureFromAttributes } from "../../common/entity/supports-feature";
import { ClimateEntityFeature } from "../../data/climate";
import {
CLIMATE_HVAC_ACTION_TO_MODE,
ClimateEntityFeature,
} from "../../data/climate";
import type { HvacAction } from "../../data/climate";
import { MockBaseEntity } from "./base-entity";
import type { EntityAttributes } from "./types";
// Reverse mapping: mode → action (e.g. "cool" → "cooling")
const HVAC_MODE_TO_ACTION: Partial<Record<string, HvacAction>> =
Object.fromEntries(
Object.entries(CLIMATE_HVAC_ACTION_TO_MODE).map(([action, mode]) => [
mode,
action as HvacAction,
])
);
export class MockClimateEntity extends MockBaseEntity {
public async handleService(
domain: string,
@@ -231,13 +243,10 @@ export class MockClimateEntity extends MockBaseEntity {
return "off";
}
// Heat and cool get their action from the temperatures below
if (state === "dry") {
return "drying";
}
if (state === "fan_only") {
return "fan";
// Use the reverse mapping for direct mode → action (e.g. "fan_only" → "fan", "dry" → "drying")
const directAction = HVAC_MODE_TO_ACTION[state];
if (directAction && directAction !== "idle" && directAction !== "off") {
return directAction;
}
if (
@@ -267,17 +276,13 @@ export class MockClimateEntity extends MockBaseEntity {
const current = attrs.current_temperature;
const lowTarget = attrs.target_temp_low;
const highTarget = attrs.target_temp_high;
// Heat mode can only heat and cool mode only cool, while auto and
// heat_cool use both ends of the range
if (current != null) {
if (state !== "cool" && lowTarget != null && lowTarget > current) {
if (lowTarget != null && lowTarget > current) {
return "heating";
}
if (state !== "heat" && highTarget != null && highTarget < current) {
if (highTarget != null && highTarget < current) {
return "cooling";
}
return "idle";
}
}
-16
View File
@@ -607,22 +607,6 @@ export const ENTITY_COMPONENT_ICONS: Record<string, ComponentIcons> = {
atmospheric_pressure: {
default: "mdi:thermometer-lines",
},
battery: {
default: "mdi:battery-unknown",
range: {
"0": "mdi:battery-alert",
"10": "mdi:battery-10",
"20": "mdi:battery-20",
"30": "mdi:battery-30",
"40": "mdi:battery-40",
"50": "mdi:battery-50",
"60": "mdi:battery-60",
"70": "mdi:battery-70",
"80": "mdi:battery-80",
"90": "mdi:battery-90",
"100": "mdi:battery",
},
},
carbon_dioxide: {
default: "mdi:molecule-co2",
},
-71
View File
@@ -27,12 +27,6 @@ import {
import { updateHassGroups } from "../data/context/updateContext";
import type { IconCategory } from "../data/icons";
import type { EntityRegistryDisplayEntry } from "../data/entity/entity_registry";
import { evaluateConditionsLocally } from "../common/condition/evaluate-locally";
import {
isLogicalCondition,
logicalChildren,
} from "../common/condition/translate";
import type { VisibilityCondition } from "../panels/lovelace/common/validate-condition";
import {
DateFormat,
FirstWeekday,
@@ -59,24 +53,6 @@ import type { EntityInput } from "./entities/types";
const ensureArray = <T>(val: T | T[]): T[] =>
Array.isArray(val) ? val : [val];
// Core's `not` passes when none of its conditions pass, and the frontend's
// unless all of them pass, so each `not` gets one `or` of its conditions
const withCoreNot = (condition: VisibilityCondition): VisibilityCondition => {
if (!isLogicalCondition(condition) || condition.conditions === undefined) {
return condition;
}
const conditions = logicalChildren(condition).map(withCoreNot);
return {
...condition,
conditions:
condition.condition === "not"
? [{ condition: "or", conditions }]
: conditions,
};
};
type MockServiceCallback = (
data: Record<string, any> | undefined,
target: Record<string, any> | undefined,
@@ -245,8 +221,6 @@ export const provideHass = (
return lazyLoaderPromise;
};
const eventListeners: Record<string, ((event) => void)[]> = {};
// Checks each subscribed condition again, for when the states change.
const conditionChecks = new Set<() => void>();
const entities = {};
let localResources: Resources = {};
@@ -690,51 +664,6 @@ export const provideHass = (
resources: category === "entity_component" ? ENTITY_COMPONENT_ICONS : {},
}));
// Core answers the visibility conditions of cards and rows that depend on
// states. Here they are checked against the mock states, as the frontend
// does itself before Core answers, and again each time the states change.
// A condition only Core can check, such as a template, gets an error, so
// a `not` around it can't show the card.
hassObj.mockWS(
"subscribe_condition",
({ condition }: { condition: VisibilityCondition }, _hass, onChange) => {
const check = () => {
const result = evaluateConditionsLocally(
[withCoreNot(condition)],
hass(),
{}
);
onChange?.(
result === undefined
? {
error: {
code: "not_supported",
message: "The demo can't check this condition",
},
}
: { result }
);
};
conditionChecks.add(check);
check();
return () => conditionChecks.delete(check);
}
);
// Check the conditions again after each state update, also when the host
// passed its own updateHass, as the demo does
const applyUpdate = hassObj.updateHass;
hassObj.updateHass = (obj: Partial<MockHomeAssistant>) => {
applyUpdate(obj);
if (obj.states) {
conditionChecks.forEach((check) => check());
}
};
// Set hass if required
if (setHassProperty) {
elements.forEach((el) => {
@@ -514,16 +514,8 @@ class AddIntegrationDialog extends LitElement {
return [...integrations]
.filter((item) => !brand || item.domain === brand)
.sort(byName)
.flatMap((item) =>
this._brandRows(item)
.filter((row) => !row.is_header)
// The brand on the second line, so its entries read as a group
.map((row) =>
brand || !this._isBrand(item)
? row
: { ...row, description: item.name }
)
);
.flatMap((item) => this._brandRows(item))
.filter((row) => !brand || !row.is_header);
}
// A brand shows its integrations here, not itself, like the website
if (category) {
@@ -1215,11 +1207,17 @@ class AddIntegrationDialog extends LitElement {
})}
>
${
this._stickyBrand
? html`<ha-section-title class="sticky">
${this._stickyBrand}
</ha-section-title>`
: nothing
!this._stickyBrand
? nothing
: this._filter
? html`<ha-section-title class="sticky">
${this._stickyBrand}
</ha-section-title>`
: html`<ha-integration-list-title
class="sticky raised"
>
${this._stickyBrand}
</ha-integration-list-title>`
}
<ha-list-virtualized
.rows=${this._filter ? rows : this._withEndSpace(rows)}
@@ -1773,7 +1771,7 @@ class AddIntegrationDialog extends LitElement {
);
}
// The virtualizer positions rows, so CSS sticky can't hold the section title
// The virtualizer positions rows, so CSS sticky can't hold the brand
@eventOptions({ passive: true })
private _visibilityChanged(ev: HASSDomEvent<HaListVisibilityChangedDetail>) {
const rows = this._getRows();
@@ -1796,7 +1794,11 @@ class AddIntegrationDialog extends LitElement {
return html`<div style="height: var(--ha-space-2)"></div>`;
}
if (integration.is_header) {
return html`<ha-section-title>${integration.name}</ha-section-title>`;
return this._filter
? html`<ha-section-title>${integration.name}</ha-section-title>`
: html`<ha-integration-list-title>
${integration.name}
</ha-integration-list-title>`;
}
return html`
<ha-integration-list-item
@@ -26,7 +26,6 @@ import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import memoizeOne from "memoize-one";
import { navigate } from "../../../common/navigate";
import { formatListWithAnds } from "../../../common/string/format-list";
import { copyToClipboard } from "../../../common/util/copy-clipboard";
import "../../../components/ha-dropdown";
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
@@ -96,9 +95,6 @@ export class HaConfigEntryRow extends LitElement {
@property({ attribute: false }) public data!: ConfigEntryData;
/** The loaded integrations that lose this integration with this entry. */
@property({ attribute: false }) public dependents?: IntegrationManifest[];
@state() private _expanded = true;
@state() private _devicesExpanded = true;
@@ -816,33 +812,14 @@ export class HaConfigEntryRow extends LitElement {
const applicationCredentialsId =
await this._applicationCredentialForRemove(entryId);
const text = this.hass.localize(
"ui.panel.config.integrations.config_entry.delete_confirm_text"
);
const confirmed = await showConfirmationDialog(this, {
title: this.hass.localize(
"ui.panel.config.integrations.config_entry.delete_confirm_title",
{ title: this.data.entry.title }
),
text: this.dependents?.length
? html`${text}<br /><br />${this.hass.localize(
"ui.panel.config.integrations.config_entry.delete_confirm_dependents",
{
count: this.dependents.length,
integrations: formatListWithAnds(
this.hass.locale,
this.dependents.map((manifest) =>
domainToName(this.hass.localize, manifest.domain, manifest)
)
),
name: domainToName(
this.hass.localize,
this.data.entry.domain,
this.manifest
),
}
)}`
: text,
text: this.hass.localize(
"ui.panel.config.integrations.config_entry.delete_confirm_text"
),
confirmText: this.hass!.localize("ui.common.delete"),
dismissText: this.hass!.localize("ui.common.cancel"),
destructive: true,
@@ -21,7 +21,7 @@ import memoizeOne from "memoize-one";
import { ensureArray } from "../../../common/array/ensure-array";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import { QueryParamsController } from "../../../common/controllers/query-params-controller";
import { consume } from "../../../common/decorators/consume";
import { ContextSubscriptionController } from "../../../common/decorators/consume";
import type { HASSDomTargetEvent } from "../../../common/dom/fire_event";
import { computeDeviceNameDisplay } from "../../../common/entity/compute_device_name";
import {
@@ -176,9 +176,9 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
@state() private _manifest?: IntegrationManifest;
/** The manifests of all loaded integrations, to find the dependents. */
@consume({ context: manifestsContext, subscribe: true })
@state()
private _loadedManifests?: DomainManifestLookup;
@state() private _loadedManifests?: DomainManifestLookup;
private _manifestsConsumer?: ContextSubscriptionController<DomainManifestLookup>;
@state() private _extraConfigEntries?: ConfigEntry[];
@@ -432,23 +432,17 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
this.domain
);
const dependents = this._getDependents(
this.domain,
this._loadedManifests,
this.hass.localize,
this.hass.locale.language
);
// Without the dependents, a dependency looks like a YAML integration.
const dependencyOnly =
normalEntries.length === 0 &&
dependents.length > 0 &&
!this._manifest?.config_flow;
// Deleting the last entry in use leaves the dependents without it.
const entriesInUse = configEntries.filter(
(entry) => entry.source !== "ignore" && !entry.disabled_by
);
const lastEntryId =
entriesInUse.length === 1 ? entriesInUse[0].entry_id : undefined;
const dependents =
this._manifest && !this._manifest.config_flow
? this._getDependents(
this.domain,
this._loadedManifests,
this.hass.localize,
this.hass.locale.language
)
: [];
const showDependents = normalEntries.length === 0 && dependents.length > 0;
// Hold back the YAML texts and "Add entry" until the manifest and the
// dependents are known. Entries do not wait, so a failed request cannot
// hide them.
@@ -467,7 +461,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
const showAddEntry =
this._manifest?.integration_type !== "hardware" &&
!dependencyOnly &&
!showDependents &&
!dependentsLoading &&
!setUpInPanel &&
(!this._manifest?.single_config_entry ||
@@ -659,7 +653,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
}
${
normalEntries.length === 0 &&
!dependencyOnly &&
!showDependents &&
!dependentsLoading &&
!setUpInPanel &&
this._manifest &&
@@ -1016,11 +1010,6 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
.diagnosticHandler=${this._diagnosticHandler}
.entities=${this._entities}
.data=${data}
.dependents=${
data.entry.entry_id === lastEntryId
? dependents
: undefined
}
data-entry-id=${data.entry.entry_id}
></ha-config-entry-row>`
)}
@@ -1029,7 +1018,19 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
: nothing
}
${
dependencyOnly ||
showDependents
? html`<div class="section">
<h3 class="section-header">
${this.hass.localize(
"ui.panel.config.integrations.integration_page.used_by"
)}
</h3>
${this._renderDependents(dependents)}
</div>`
: nothing
}
${
showDependents ||
dependentsLoading ||
(setUpInPanel && normalEntries.length === 0)
? nothing
@@ -1076,11 +1077,6 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
.diagnosticHandler=${this._diagnosticHandler}
.entities=${this._entities}
.data=${data}
.dependents=${
data.entry.entry_id === lastEntryId
? dependents
: undefined
}
data-entry-id=${data.entry.entry_id}
></ha-config-entry-row>`
)}
@@ -1088,23 +1084,26 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
}
</div>`
}
${
dependents.length
? html`<div class="section">
<h3 class="section-header">
${this.hass.localize(
"ui.panel.config.integrations.integration_page.used_by"
)}
</h3>
${this._renderDependents(dependents)}
</div>`
: nothing
}
</div>
</hass-subpage>
`;
}
// Only an integration without a config flow needs the loaded manifests, so
// other integration pages do not make the context fetch them.
private _watchLoadedManifests(): void {
if (this._manifestsConsumer) {
return;
}
this._manifestsConsumer = new ContextSubscriptionController(
this,
manifestsContext,
(manifests) => {
this._loadedManifests = manifests;
}
);
}
private _getDependents = memoizeOne(
(
domain: string,
@@ -1200,6 +1199,9 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
return;
}
this._manifest = await fetchIntegrationManifest(this.hass, this.domain);
if (!this._manifest.config_flow) {
this._watchLoadedManifests();
}
if (
this._manifest.integration_type &&
!["device", "hub", "service"].includes(this._manifest.integration_type)
@@ -2,7 +2,8 @@ import type { HassEntities } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { mdiChartDonut, mdiChartBar } from "@mdi/js";
import "@home-assistant/webawesome/dist/components/divider/divider";
import { mdiChartBar, mdiChartDonut, mdiFormatListChecks } from "@mdi/js";
import { classMap } from "lit/directives/class-map";
import memoizeOne from "memoize-one";
import type { BarSeriesOption, PieSeriesOption } from "echarts/charts";
@@ -48,6 +49,10 @@ import type { LovelaceCard } from "../../types";
import type { EnergyDevicesGraphCardConfig } from "../types";
import type { HaECOption } from "../../../../resources/echarts/echarts";
import "../../../../components/ha-card";
import "../../../../components/ha-dropdown";
import type { HaDropdownSelectEvent } from "../../../../components/ha-dropdown";
import "../../../../components/ha-dropdown-item";
import "../../../../components/ha-filter-pane-chip";
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
import { fireEvent } from "../../../../common/dom/fire_event";
import { measureTextWidth } from "../../../../util/text";
@@ -56,6 +61,9 @@ import { storage } from "../../../../common/decorators/storage";
import { getEnergyColor } from "./common/color";
import type { CustomLegendOption } from "../../../../components/chart/ha-chart-base";
const SELECT_ALL = "__select_all__";
const SELECT_NONE = "__select_none__";
@customElement("hui-energy-devices-graph-card")
export class HuiEnergyDevicesGraphCard
extends MobileAwareMixin(LitElement)
@@ -169,26 +177,38 @@ export class HuiEnergyDevicesGraphCard
}
const modes = this._getAllowedModes();
const shownCount = this._legendData.filter(
(d) => !this._hiddenStats.includes(d.id!)
).length;
const rows =
this._chartType === "bar" ? shownCount : this._legendData.length;
return html`
<ha-card>
<div class="card-header">
<span>${this._config.title ? this._config.title : nothing}</span>
${
modes.length > 1
? html`
<ha-icon-button
.path=${
this._chartType === "pie" ? mdiChartBar : mdiChartDonut
}
.label=${this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_devices_graph.change_chart_type"
)}
@click=${this._handleChartTypeChange}
></ha-icon-button>
`
: nothing
}
<div class="actions">
${
this._chartType === "bar" && this._legendData.length
? this._renderDeviceSelect(shownCount)
: nothing
}
${
modes.length > 1
? html`
<ha-icon-button
.path=${
this._chartType === "pie" ? mdiChartBar : mdiChartDonut
}
.label=${this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_devices_graph.change_chart_type"
)}
@click=${this._handleChartTypeChange}
></ha-icon-button>
`
: nothing
}
</div>
</div>
<div
class="content ${classMap({
@@ -202,7 +222,7 @@ export class HuiEnergyDevicesGraphCard
this._chartType,
this._legendData
)}
.height=${`${Math.max(modes.includes("pie") ? 300 : 100, (this._legendData?.length || 0) * 28 + 50)}px`}
.height=${`${Math.max(modes.includes("pie") ? 300 : 100, rows * 28 + 50)}px`}
.sonificationLabelFormatter=${this._sonificationLabel}
.extraComponents=${[PieChart]}
.expandLegend=${this._config.expand_legend}
@@ -217,6 +237,45 @@ export class HuiEnergyDevicesGraphCard
`;
}
private _renderDeviceSelect(shownCount: number) {
const filtered = shownCount < this._legendData.length;
return html`
<ha-dropdown
placement="bottom-end"
@wa-select=${this._handleDeviceSelect}
>
<ha-filter-pane-chip
slot="trigger"
hide-label
.label=${this._i18n.localize(
"ui.panel.lovelace.cards.energy.energy_devices_graph.select_devices"
)}
.path=${mdiFormatListChecks}
.count=${filtered ? shownCount : 0}
.active=${filtered}
></ha-filter-pane-chip>
<ha-dropdown-item value=${SELECT_ALL}>
${this._i18n.localize("ui.components.subpage-data-table.select_all")}
</ha-dropdown-item>
<ha-dropdown-item value=${SELECT_NONE}>
${this._i18n.localize("ui.components.subpage-data-table.select_none")}
</ha-dropdown-item>
<wa-divider></wa-divider>
${this._legendData.map(
(d) => html`
<ha-dropdown-item
type="checkbox"
.value=${d.id!}
.checked=${!this._hiddenStats.includes(d.id!)}
>
${d.name}
</ha-dropdown-item>
`
)}
</ha-dropdown>
`;
}
private _renderTooltip = (params: any) => {
const deviceName = this._getDeviceName(params.name);
const area = computeEnergyStatisticArea(this._registries, params.name);
@@ -334,12 +393,11 @@ export class HuiEnergyDevicesGraphCard
type: "custom",
show: true,
data: legendData,
selected: legendData
.filter((d) => d.id && this._hiddenStats.includes(d.id))
.reduce((acc, d) => {
acc[d.id!] = false;
return acc;
}, {}),
selected: Object.fromEntries(
legendData
.filter((d) => d.id)
.map((d) => [d.id, !this._hiddenStats.includes(d.id!)])
),
};
}
return options;
@@ -698,6 +756,25 @@ export class HuiEnergyDevicesGraphCard
this._getStatistics(this._data!);
}
private _handleDeviceSelect(ev: HaDropdownSelectEvent) {
ev.preventDefault(); // keep the dropdown open to pick several devices
const { value, checked } = ev.detail.item;
const ids = this._legendData.map((d) => d.id!);
if (value === SELECT_ALL) {
this._hiddenStats = this._hiddenStats.filter((id) => !ids.includes(id));
} else if (value === SELECT_NONE) {
this._hiddenStats = [
...this._hiddenStats,
...ids.filter((id) => !this._hiddenStats.includes(id)),
];
} else if (checked) {
this._hiddenStats = this._hiddenStats.filter((id) => id !== value);
} else {
this._hiddenStats = [...this._hiddenStats, value];
}
this._getStatistics(this._data!);
}
private _datasetHidden(ev: CustomEvent<{ id: string }>) {
this._hiddenStats = [...this._hiddenStats, ev.detail.id];
this._getStatistics(this._data!);
@@ -717,6 +794,11 @@ export class HuiEnergyDevicesGraphCard
align-items: center;
padding-bottom: 0;
}
.actions {
display: flex;
align-items: center;
gap: var(--ha-space-2);
}
.content {
padding: 16px;
}
+63 -90
View File
@@ -11,7 +11,6 @@ import type {
} from "../../../common/dom/fire_event";
import { computeDomain } from "../../../common/entity/compute_domain";
import parseAspectRatio from "../../../common/util/parse-aspect-ratio";
import "../../../components/camera/ha-camera-placeholder";
import "../../../components/ha-camera-stream";
import type { HaCameraStream } from "../../../components/ha-camera-stream";
import "../../../components/ha-spinner";
@@ -136,12 +135,6 @@ export class HuiImage extends LitElement {
if (this._shouldStartCameraUpdates(oldHass)) {
this._startIntersectionObserver();
} else if (
this._cameraBecameAvailable(oldHass) &&
this._imageVisible &&
this.cameraView !== "live"
) {
this._updateCameraImageSrc();
} else if (!this.hass!.connected) {
this._stopUpdateCameraInterval();
this._stopIntersectionObserver();
@@ -271,13 +264,6 @@ export class HuiImage extends LitElement {
// Snapshots load only once the card is on screen; skip the spinner until then.
const showSpinner = !this.cameraImage || this._imageVisible;
const cameraUnavailable = this._cameraUnavailable();
const placeholderHeight = !useRatio
? this._lastImageHeight
? `${this._lastImageHeight}px`
: "100%"
: undefined;
return html`
<div
style=${styleMap({
@@ -302,66 +288,71 @@ export class HuiImage extends LitElement {
})}"
>
${
cameraUnavailable
? nothing
: this.cameraImage && this.cameraView === "live"
? html`
<ha-camera-stream
muted
.stateObj=${cameraObj}
.fitMode=${this.fitMode}
.aspectRatio=${
this._ratio ? this._ratio.w / this._ratio.h : undefined
}
@load=${this._onVideoLoad}
></ha-camera-stream>
this.cameraImage && this.cameraView === "live"
? html`
<ha-camera-stream
muted
.stateObj=${cameraObj}
.fitMode=${this.fitMode}
.aspectRatio=${
this._ratio ? this._ratio.w / this._ratio.h : undefined
}
@load=${this._onVideoLoad}
></ha-camera-stream>
`
: imageSrc === undefined
? nothing
: html`
<img
id="image"
src=${this._reconnectImg ? nothing : live(imageSrc)}
alt=${this.entity || ""}
@error=${this._onImageError}
@load=${this._onImageLoad}
style=${styleMap({
display:
useRatio || this._loadState === LoadState.Loaded
? "block"
: "none",
})}
/>
`
: imageSrc === undefined
? nothing
: html`
<img
id="image"
src=${this._reconnectImg ? nothing : live(imageSrc)}
alt=${this.entity || ""}
@error=${this._onImageError}
@load=${this._onImageLoad}
style=${styleMap({
display:
useRatio || this._loadState === LoadState.Loaded
? "block"
: "none",
})}
/>
`
}
${
this.cameraImage &&
(cameraUnavailable || this._loadState === LoadState.Error)
? html`<ha-camera-placeholder
style=${styleMap({ height: placeholderHeight })}
></ha-camera-placeholder>`
: this._loadState === LoadState.Error
this._loadState === LoadState.Error
? html`<div
id="brokenImage"
style=${styleMap({
height: !useRatio
? this._lastImageHeight
? `${this._lastImageHeight}px`
: "100%"
: undefined,
})}
></div>`
: this.cameraView !== "live" &&
(imageSrc === undefined ||
this._loadState === LoadState.Loading)
? html`<div
id="brokenImage"
style=${styleMap({ height: placeholderHeight })}
></div>`
: this.cameraView !== "live" &&
(imageSrc === undefined ||
this._loadState === LoadState.Loading)
? html`<div
class="progress-container"
style=${styleMap({ height: placeholderHeight })}
>
${
showSpinner
? html`<ha-spinner
class="render-spinner"
size="small"
></ha-spinner>`
: nothing
}
</div>`
: ""
class="progress-container"
style=${styleMap({
height: !useRatio
? this._lastImageHeight
? `${this._lastImageHeight}px`
: "100%"
: undefined,
})}
>
${
showSpinner
? html`<ha-spinner
class="render-spinner"
size="small"
></ha-spinner>`
: nothing
}
</div>`
: ""
}
</div>
`;
@@ -375,18 +366,6 @@ export class HuiImage extends LitElement {
);
}
private _cameraUnavailable(hass = this.hass): boolean {
return Boolean(
this.cameraImage && hass?.states[this.cameraImage]?.state === UNAVAILABLE
);
}
private _cameraBecameAvailable(oldHass?: HomeAssistant): boolean {
return Boolean(
oldHass && this._cameraUnavailable(oldHass) && !this._cameraUnavailable()
);
}
private _startIntersectionObserver(): void {
if (!this._intersectionObserver) {
this._intersectionObserver = new IntersectionObserver(
@@ -455,8 +434,7 @@ export class HuiImage extends LitElement {
}
private async _updateCameraImageSrc(): Promise<void> {
// Its picture can't load, a placeholder shows instead
if (!this.hass || !this.cameraImage || this._cameraUnavailable()) {
if (!this.hass || !this.cameraImage) {
return;
}
@@ -547,8 +525,7 @@ export class HuiImage extends LitElement {
}
.ratio img,
.ratio div,
.ratio ha-camera-placeholder {
.ratio div {
position: absolute;
top: 0;
left: 0;
@@ -560,10 +537,6 @@ export class HuiImage extends LitElement {
visibility: hidden;
}
ha-camera-placeholder {
background-color: var(--ha-color-fill-neutral-normal-resting);
}
#brokenImage {
background: grey url("/static/images/image-broken.svg") center/36px
no-repeat;
@@ -9,8 +9,6 @@ export {
showPromptDialog,
} from "../../dialogs/generic/show-dialog-box";
export { importMoreInfoControl } from "../../dialogs/more-info/state_more_info_control";
export { subscribeVisibility } from "../../common/condition/subscribe-visibility";
export { createBadgeElement } from "./create-element/create-badge-element";
export { createCardElement } from "./create-element/create-card-element";
export { createHeaderFooterElement } from "./create-element/create-header-footer-element";
@@ -1,6 +1,6 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { DOMAINS_TOGGLE } from "../../../common/const";
import { computeDomain } from "../../../common/entity/compute_domain";
import "../../../components/ha-button";
@@ -29,7 +29,7 @@ const EMPTY_STATE_OBJ = {
@customElement("hui-button-row")
export class HuiButtonRow extends LitElement implements LovelaceRow {
@property({ attribute: false }) public hass?: HomeAssistant;
public hass?: HomeAssistant;
@state() private _config?: ButtonRowConfig;
@@ -3,7 +3,6 @@ import { mdiMinus, mdiPlus, mdiWaterPercent } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators";
import { keyed } from "lit/directives/keyed";
import { styleMap } from "lit/directives/style-map";
import { consume } from "../../common/decorators/consume";
import type { HASSDomEvent } from "../../common/dom/fire_event";
@@ -53,8 +52,6 @@ export class HaStateControlClimateHumidity extends LitElement {
@state() private _targetHumidity?: number;
@state() private _changingHumidity?: number;
private _sizeController = createStateControlCircularSliderController(this);
private _pendingSync = new PendingValueSync();
@@ -64,11 +61,7 @@ export class HaStateControlClimateHumidity extends LitElement {
if (!changedProp.has("stateObj")) {
return;
}
if (this.stateObj.state === UNAVAILABLE) {
this._changingHumidity = undefined;
}
if (changedProp.get("stateObj")?.entity_id !== this.stateObj.entity_id) {
this._changingHumidity = undefined;
this._debouncedCallService.cancel();
this._pendingSync.reset();
this._syncTargetHumidity();
@@ -78,9 +71,6 @@ export class HaStateControlClimateHumidity extends LitElement {
}
private _syncTargetHumidity() {
if (this.stateObj.attributes.humidity !== this._targetHumidity) {
this._changingHumidity = undefined;
}
this._targetHumidity = this.stateObj.attributes.humidity;
}
@@ -106,11 +96,8 @@ export class HaStateControlClimateHumidity extends LitElement {
private _valueChanging(ev: HASSDomEvent<HASSDomEvents["value-changing"]>) {
const { value } = ev.detail;
if (typeof value !== "number" || isNaN(value)) {
this._changingHumidity = undefined;
return;
}
this._changingHumidity = value;
if (typeof value !== "number" || isNaN(value)) return;
this._targetHumidity = value;
}
private _debouncedCallService = debounce(() => this._callService(), 1000);
@@ -225,10 +212,6 @@ export class HaStateControlClimateHumidity extends LitElement {
}
protected render() {
return keyed(this.stateObj.entity_id, this._renderControl());
}
private _renderControl() {
const supportsTargetHumidity = supportsFeature(
this.stateObj,
ClimateEntityFeature.TARGET_HUMIDITY
@@ -281,8 +264,7 @@ export class HaStateControlClimateHumidity extends LitElement {
>
</ha-control-circular-slider>
<div class="info">
${this._renderLabel()}
${this._renderTarget(this._changingHumidity ?? targetHumidity)}
${this._renderLabel()} ${this._renderTarget(targetHumidity)}
${this._renderCurrentHumidity(
this.stateObj.attributes.current_humidity
)}
@@ -4,7 +4,6 @@ import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { keyed } from "lit/directives/keyed";
import { styleMap } from "lit/directives/style-map";
import { consume } from "../../common/decorators/consume";
import { UNIT_F } from "../../common/const";
@@ -82,8 +81,6 @@ export class HaStateControlClimateTemperature extends LitElement {
@state() private _targetTemperature: Partial<Record<Target, number>> = {};
@state() private _changingTemperature: Partial<Record<Target, number>> = {};
@state() private _selectTargetTemperature: Target = "low";
private _sizeController = createStateControlCircularSliderController(this);
@@ -95,11 +92,7 @@ export class HaStateControlClimateTemperature extends LitElement {
if (!changedProp.has("stateObj")) {
return;
}
if (this.stateObj.state === UNAVAILABLE) {
this._changingTemperature = {};
}
if (changedProp.get("stateObj")?.entity_id !== this.stateObj.entity_id) {
this._changingTemperature = {};
this._debouncedCallService.cancel();
this._pendingSync.reset();
this._syncTargetTemperature();
@@ -109,20 +102,11 @@ export class HaStateControlClimateTemperature extends LitElement {
}
private _syncTargetTemperature() {
const targetTemperature: Partial<Record<Target, number>> = {
this._targetTemperature = {
value: this.stateObj.attributes.temperature,
low: this.stateObj.attributes.target_temp_low,
high: this.stateObj.attributes.target_temp_high,
};
if (
(Object.keys(this._changingTemperature) as Target[]).some(
(target) =>
targetTemperature[target] !== this._targetTemperature[target]
)
) {
this._changingTemperature = {};
}
this._targetTemperature = targetTemperature;
}
private get _step() {
@@ -143,31 +127,27 @@ export class HaStateControlClimateTemperature extends LitElement {
private _valueChanged(ev: HASSDomEvent<HASSDomEvents["value-changed"]>) {
const { value } = ev.detail;
if (typeof value !== "number" || isNaN(value)) return;
const target = ev.type.replace("-changed", "") as Target;
const target = ev.type.replace("-changed", "");
this._targetTemperature = {
...this._targetTemperature,
[target]: this._clampToRange(target, value),
[target]: value,
};
this._selectTargetTemperature = target;
this._selectTargetTemperature = target as Target;
this._debouncedCallService.cancel();
this._callService(target);
}
private _valueChanging(ev: HASSDomEvent<HASSDomEvents["value-changing"]>) {
const { value } = ev.detail;
if (typeof value !== "number" || isNaN(value)) {
this._changingTemperature = {};
return;
}
if (typeof value !== "number" || isNaN(value)) return;
const target = ev.type.replace("-changing", "");
this._changingTemperature = { [target]: value };
this._targetTemperature = {
...this._targetTemperature,
[target]: value,
};
this._selectTargetTemperature = target as Target;
}
private get _displayedTemperature() {
return { ...this._targetTemperature, ...this._changingTemperature };
}
private _debouncedCallService = debounce(
(target: Target) => this._callService(target),
1000
@@ -200,25 +180,21 @@ export class HaStateControlClimateTemperature extends LitElement {
let temp = this._targetTemperature[target] ?? defaultValue;
temp += step;
temp = clamp(temp, this._min, this._max);
if (target === "high" && this._targetTemperature.low != null) {
temp = clamp(temp, this._targetTemperature.low, this._max);
}
if (target === "low" && this._targetTemperature.high != null) {
temp = clamp(temp, this._min, this._targetTemperature.high);
}
this._targetTemperature = {
...this._targetTemperature,
[target]: this._clampToRange(target, temp),
[target]: temp,
};
this._pendingSync.schedule();
this._debouncedCallService(target);
}
private _clampToRange(target: Target, temp: number) {
if (target === "high" && this._targetTemperature.low != null) {
return clamp(temp, this._targetTemperature.low, this._max);
}
if (target === "low" && this._targetTemperature.high != null) {
return clamp(temp, this._min, this._targetTemperature.high);
}
return temp;
}
private _handleSelectTemp(ev) {
const target = ev.currentTarget.target as Target;
this._selectTargetTemperature = target;
@@ -378,7 +354,7 @@ export class HaStateControlClimateTemperature extends LitElement {
}
if (this._supportsTargetTemperature && !this.showCurrentAsPrimary) {
return this._renderTarget(this._displayedTemperature.value!, "big");
return this._renderTarget(this._targetTemperature.value!, "big");
}
if (this._supportsTargetTemperatureRange && !this.showCurrentAsPrimary) {
@@ -398,7 +374,7 @@ export class HaStateControlClimateTemperature extends LitElement {
"target_temp_low"
)}
</span>
${this._renderTarget(this._displayedTemperature.low!, "big")}
${this._renderTarget(this._targetTemperature.low!, "big")}
</button>
<button
@click=${this._handleSelectTemp}
@@ -414,7 +390,7 @@ export class HaStateControlClimateTemperature extends LitElement {
"target_temp_high"
)}
</span>
${this._renderTarget(this._displayedTemperature.high!, "big")}
${this._renderTarget(this._targetTemperature.high!, "big")}
</button>
</div>
`;
@@ -451,7 +427,7 @@ export class HaStateControlClimateTemperature extends LitElement {
return html`
<p class="label secondary">
<ha-svg-icon .path=${mdiThermostat}></ha-svg-icon>
${this._renderTarget(this._displayedTemperature.value!, "normal")}
${this._renderTarget(this._targetTemperature.value!, "normal")}
</p>
`;
}
@@ -474,7 +450,7 @@ export class HaStateControlClimateTemperature extends LitElement {
"target_temp_low"
)}
</span>
${this._renderTarget(this._displayedTemperature.low!, "normal", true)}
${this._renderTarget(this._targetTemperature.low!, "normal", true)}
</button>
<span>·</span>
<button
@@ -491,7 +467,7 @@ export class HaStateControlClimateTemperature extends LitElement {
"target_temp_high"
)}
</span>
${this._renderTarget(this._displayedTemperature.high!, "normal", true)}
${this._renderTarget(this._targetTemperature.high!, "normal", true)}
</button>
</p>
`;
@@ -527,10 +503,6 @@ export class HaStateControlClimateTemperature extends LitElement {
}
protected render() {
return keyed(this.stateObj.entity_id, this._renderControl());
}
private _renderControl() {
const mode = this.stateObj.state;
const action = this.stateObj.attributes.hvac_action;
const active = stateActive(this.stateObj);
@@ -577,7 +549,7 @@ export class HaStateControlClimateTemperature extends LitElement {
.preventInteractionOnScroll=${this.preventInteractionOnScroll}
.inactive=${!active}
.mode=${sliderMode}
.value=${this._displayedTemperature.value}
.value=${this._targetTemperature.value}
.min=${this._min}
.max=${this._max}
.step=${this._step}
@@ -613,8 +585,8 @@ export class HaStateControlClimateTemperature extends LitElement {
.preventInteractionOnScroll=${this.preventInteractionOnScroll}
.inactive=${!active}
dual
.low=${this._displayedTemperature.low}
.high=${this._displayedTemperature.high}
.low=${this._targetTemperature.low}
.high=${this._targetTemperature.high}
.min=${this._min}
.max=${this._max}
.step=${this._step}
@@ -3,7 +3,6 @@ import { mdiMinus, mdiPlus, mdiThermostat, mdiWaterPercent } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { keyed } from "lit/directives/keyed";
import { styleMap } from "lit/directives/style-map";
import { consume } from "../../common/decorators/consume";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
@@ -58,8 +57,6 @@ export class HaStateControlHumidifierHumidity extends LitElement {
@state() private _targetHumidity?: number;
@state() private _changingHumidity?: number;
private _sizeController = createStateControlCircularSliderController(this);
private _pendingSync = new PendingValueSync();
@@ -69,11 +66,7 @@ export class HaStateControlHumidifierHumidity extends LitElement {
if (!changedProp.has("stateObj")) {
return;
}
if (this.stateObj.state === UNAVAILABLE) {
this._changingHumidity = undefined;
}
if (changedProp.get("stateObj")?.entity_id !== this.stateObj.entity_id) {
this._changingHumidity = undefined;
this._debouncedCallService.cancel();
this._pendingSync.reset();
this._syncTargetHumidity();
@@ -83,9 +76,6 @@ export class HaStateControlHumidifierHumidity extends LitElement {
}
private _syncTargetHumidity() {
if (this.stateObj.attributes.humidity !== this._targetHumidity) {
this._changingHumidity = undefined;
}
this._targetHumidity = this.stateObj.attributes.humidity;
}
@@ -111,11 +101,8 @@ export class HaStateControlHumidifierHumidity extends LitElement {
private _valueChanging(ev: HASSDomEvent<HASSDomEvents["value-changing"]>) {
const { value } = ev.detail;
if (typeof value !== "number" || isNaN(value)) {
this._changingHumidity = undefined;
return;
}
this._changingHumidity = value;
if (typeof value !== "number" || isNaN(value)) return;
this._targetHumidity = value;
}
private _debouncedCallService = debounce(() => this._callService(), 1000);
@@ -213,10 +200,7 @@ export class HaStateControlHumidifierHumidity extends LitElement {
}
if (this._targetHumidity != null && !this.showCurrentAsPrimary) {
return this._renderTarget(
this._changingHumidity ?? this._targetHumidity,
"big"
);
return this._renderTarget(this._targetHumidity!, "big");
}
if (this.stateObj.state !== UNAVAILABLE) {
@@ -250,10 +234,7 @@ export class HaStateControlHumidifierHumidity extends LitElement {
return html`
<p class="label">
<ha-svg-icon .path=${mdiThermostat}></ha-svg-icon>
${this._renderCurrent(
this._changingHumidity ?? this._targetHumidity,
"normal"
)}
${this._renderCurrent(this._targetHumidity, "normal")}
</p>
`;
}
@@ -318,10 +299,6 @@ export class HaStateControlHumidifierHumidity extends LitElement {
}
protected render() {
return keyed(this.stateObj.entity_id, this._renderControl());
}
private _renderControl() {
const stateColor = stateColorCss(this.stateObj);
const active = stateActive(this.stateObj);
@@ -3,7 +3,6 @@ import { mdiMinus, mdiPlus } from "@mdi/js";
import type { CSSResultGroup, PropertyValues } from "lit";
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators";
import { keyed } from "lit/directives/keyed";
import { styleMap } from "lit/directives/style-map";
import { consume } from "../../common/decorators/consume";
import { UNIT_F } from "../../common/const";
@@ -61,8 +60,6 @@ export class HaStateControlWaterHeaterTemperature extends LitElement {
@state() private _targetTemperature?: number;
@state() private _changingTemperature?: number;
private _sizeController = createStateControlCircularSliderController(this);
private _pendingSync = new PendingValueSync();
@@ -72,11 +69,7 @@ export class HaStateControlWaterHeaterTemperature extends LitElement {
if (!changedProp.has("stateObj")) {
return;
}
if (this.stateObj.state === UNAVAILABLE) {
this._changingTemperature = undefined;
}
if (changedProp.get("stateObj")?.entity_id !== this.stateObj.entity_id) {
this._changingTemperature = undefined;
this._debouncedCallService.cancel();
this._pendingSync.reset();
this._syncTargetTemperature();
@@ -86,9 +79,6 @@ export class HaStateControlWaterHeaterTemperature extends LitElement {
}
private _syncTargetTemperature() {
if (this.stateObj.attributes.temperature !== this._targetTemperature) {
this._changingTemperature = undefined;
}
this._targetTemperature = this.stateObj.attributes.temperature;
}
@@ -117,11 +107,8 @@ export class HaStateControlWaterHeaterTemperature extends LitElement {
private _valueChanging(ev: HASSDomEvent<HASSDomEvents["value-changing"]>) {
const { value } = ev.detail;
if (typeof value !== "number" || isNaN(value)) {
this._changingTemperature = undefined;
return;
}
this._changingTemperature = value;
if (typeof value !== "number" || isNaN(value)) return;
this._targetTemperature = value;
}
private _debouncedCallService = debounce(() => this._callService(), 1000);
@@ -244,10 +231,6 @@ export class HaStateControlWaterHeaterTemperature extends LitElement {
}
protected render() {
return keyed(this.stateObj.entity_id, this._renderControl());
}
private _renderControl() {
const supportsTargetTemperature = supportsFeature(
this.stateObj,
WaterHeaterEntityFeature.TARGET_TEMPERATURE
@@ -288,9 +271,7 @@ export class HaStateControlWaterHeaterTemperature extends LitElement {
</ha-control-circular-slider>
<div class="info">
${this._renderLabel()}
${this._renderTargetTemperature(
this._changingTemperature ?? this._targetTemperature
)}
${this._renderTargetTemperature(this._targetTemperature)}
${this._renderCurrentTemperature(
this.stateObj.attributes.current_temperature
)}
+4 -10
View File
@@ -1394,10 +1394,9 @@
"reset_zoom": "Reset zoom",
"zoom_hint": "Use {modifier} + scroll to zoom",
"connecting": "Connecting",
"live": "Live",
"unavailable": "[%key:state::default::unavailable%]",
"disconnected": "Disconnected",
"show_details": "Show connection details"
"stream_info": "Streaming with {type}. Show connection details",
"stream_info_connecting": "Connecting to the camera. Show connection details",
"stream_info_upgrading": "Streaming with {type}, connecting with {upgrading} in the background. Show connection details"
},
"web-rtc-player": {
"not_supported": "WebRTC is not supported in this browser.",
@@ -2855,11 +2854,6 @@
"intro": "Home Assistant starts with the connection that works most reliably and switches to a faster one as soon as it is ready.",
"still_images_only": "This camera has no video stream, so it shows a series of still images.",
"fallback_in_use": "The video streams of this camera could not be started, so still images are shown instead.",
"unavailable": "The camera is unavailable, so no stream can start. It connects again as soon as the camera is back.",
"disconnected": {
"home_assistant": "The connection to Home Assistant was lost, so the stream stopped. It starts again as soon as Home Assistant is reachable.",
"stream_failed": "WebRTC could not connect, and this camera has no other stream to fall back to. The player shows what went wrong."
},
"in_use": "In use",
"connecting": "Connecting",
"not_supported_count": "Not supported by this camera ({count})",
@@ -8266,7 +8260,6 @@
"delete": "Delete",
"delete_confirm_title": "Delete {title}?",
"delete_confirm_text": "Its devices and entities will be permanently deleted.",
"delete_confirm_dependents": "{integrations} {count, plural,\n one {depends}\n other {depend}\n} on {name} and may stop working.",
"enable_debug_logging": "Enable debug logging",
"reconfigure": "Reconfigure",
"reload": "Reload",
@@ -10684,6 +10677,7 @@
"previous_energy_usage": "Previous energy",
"total_energy_usage": "Total",
"change_chart_type": "Change chart type",
"select_devices": "Select devices",
"untracked_consumption": "Untracked consumption",
"untracked": "untracked"
},
@@ -1,109 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { subscribeVisibility } from "../../../src/common/condition/subscribe-visibility";
import type { VisibilityCondition } from "../../../src/panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../../src/types";
interface CapturedSubscription {
push: (message: { result?: boolean }) => void;
unsub: ReturnType<typeof vi.fn>;
condition: unknown;
}
let subs: CapturedSubscription[];
const tick = () =>
new Promise<void>((resolve) => {
setTimeout(resolve, 10);
});
const createHass = (userId = "user1"): HomeAssistant =>
({
connection: {
subscribeMessage: vi.fn(
(
onChange: CapturedSubscription["push"],
msg: { condition: unknown }
) => {
const unsub = vi.fn();
subs.push({ push: onChange, unsub, condition: msg.condition });
return Promise.resolve(unsub);
}
),
},
states: {},
user: { id: userId },
locale: { time_zone: "local" },
config: { time_zone: "America/New_York" },
}) as unknown as HomeAssistant;
describe("subscribeVisibility", () => {
beforeEach(() => {
subs = [];
});
it("checks client conditions again with each hass passed to update", async () => {
const onChange = vi.fn();
const conditions: VisibilityCondition[] = [
{ condition: "user", users: ["user1"] },
];
const subscription = subscribeVisibility(
createHass("user1"),
conditions,
onChange
);
await tick();
expect(onChange).toHaveBeenLastCalledWith("visible", undefined);
subscription.update(createHass("user2"));
expect(onChange).toHaveBeenLastCalledWith("hidden", undefined);
});
it("closes core subscriptions and stops reporting after unsubscribe", async () => {
const onChange = vi.fn();
const conditions: VisibilityCondition[] = [
{ condition: "state", entity: "light.kitchen", state: "on" },
];
const subscription = subscribeVisibility(
createHass(),
conditions,
onChange
);
await tick();
expect(subs).toHaveLength(1);
subs[0].push({ result: true });
expect(onChange).toHaveBeenLastCalledWith("visible", undefined);
onChange.mockClear();
subscription.unsubscribe();
await tick();
expect(subs[0].unsub).toHaveBeenCalled();
expect(onChange).not.toHaveBeenCalled();
});
it("sends the context entity to core for conditions without one", async () => {
const conditions: VisibilityCondition[] = [
{ condition: "state", state: "on" },
];
subscribeVisibility(createHass(), conditions, vi.fn(), {
entity_id: "light.kitchen",
});
await tick();
expect(subs).toHaveLength(1);
expect(subs[0].condition).toEqual({
condition: "state",
entity_id: "light.kitchen",
state: "on",
});
});
});
+6 -1
View File
@@ -66,7 +66,7 @@ describe("ha-chart-base updates", () => {
expect(dispose).not.toHaveBeenCalled();
});
it("only flags the hidden datasets when the legend hides a new one", () => {
it("only flags the hidden datasets when the legend changes one", () => {
const { element, internals } = createChart();
const requestUpdate = vi.spyOn(element as any, "requestUpdate");
const hiddenUpdates = () =>
@@ -84,5 +84,10 @@ describe("ha-chart-base updates", () => {
internals._updateHiddenStatsFromOptions(internals.options);
expect(hiddenUpdates()).toBe(1);
internals.options = { legend: { selected: { power: true } } };
internals._updateHiddenStatsFromOptions(internals.options);
expect(hiddenUpdates()).toBe(2);
expect(internals._hiddenDatasets.has("power")).toBe(false);
});
});
+1 -44
View File
@@ -1,8 +1,5 @@
import { describe, expect, it } from "vitest";
import {
getConfigSubpageTitle,
getSelectedPanelUrlPath,
} from "../../src/data/panel";
import { getConfigSubpageTitle } from "../../src/data/panel";
import type { PageNavigation } from "../../src/layouts/hass-tabs-subpage";
import type { HomeAssistant } from "../../src/types";
@@ -86,43 +83,3 @@ describe("getConfigSubpageTitle", () => {
).toBeUndefined();
});
});
describe("getSelectedPanelUrlPath", () => {
const urlPaths = ["lovelace", "history", "config/logs", "config/logs/raw"];
it("falls back to the first path segment", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/config/automation")).toBe(
"config"
);
expect(getSelectedPanelUrlPath(urlPaths, "/profile/general")).toBe(
"profile"
);
});
it("selects a panel whose url_path has several segments", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/config/logs")).toBe(
"config/logs"
);
expect(getSelectedPanelUrlPath(urlPaths, "/config/logs/details")).toBe(
"config/logs"
);
});
it("prefers the most specific url_path", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/config/logs/raw")).toBe(
"config/logs/raw"
);
});
it("only matches whole segments", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/config/logsfoo")).toBe("config");
});
it("keeps matching single segment panels on their subpaths", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/lovelace/0")).toBe("lovelace");
});
it("returns an empty url_path for the root path", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/")).toBe("");
});
});
@@ -1,63 +0,0 @@
import { describe, expect, it } from "vitest";
import { ClimateEntityFeature } from "../../../src/data/climate";
import { MockClimateEntity } from "../../../src/fake_data/entities/climate-entity";
const hvacAction = (state: string, current: number, target: number) =>
new MockClimateEntity({
entity_id: "climate.demo",
state,
attributes: {
supported_features: ClimateEntityFeature.TARGET_TEMPERATURE,
current_temperature: current,
temperature: target,
},
}).toState().attributes.hvac_action;
// A range of 20° to 24° only, like climate.upstairs in the arsaboo demo
const rangeHvacAction = (state: string, current: number) =>
new MockClimateEntity({
entity_id: "climate.demo",
state,
attributes: {
supported_features:
ClimateEntityFeature.TARGET_TEMPERATURE +
ClimateEntityFeature.TARGET_TEMPERATURE_RANGE,
current_temperature: current,
temperature: null,
target_temp_low: 20,
target_temp_high: 24,
},
}).toState().attributes.hvac_action;
describe("MockClimateEntity", () => {
it.each([
["heat", 18, 21, "heating"],
["heat", 21, 21, "idle"],
["cool", 25, 21, "cooling"],
["cool", 20, 21, "idle"],
["dry", 20, 21, "drying"],
["fan_only", 20, 21, "fan"],
["off", 18, 21, "off"],
])(
"in %s at %d° with a target of %d° is %s",
(state, current, target, action) => {
expect(hvacAction(state, current, target)).toBe(action);
}
);
it.each([
["heat", 18, "heating"],
["heat", 25, "idle"],
["cool", 25, "cooling"],
["cool", 18, "idle"],
["heat_cool", 18, "heating"],
["heat_cool", 25, "cooling"],
["auto", 22, "idle"],
])(
"in %s at %d° with a range of 20° to 24° is %s",
(state, current, action) => {
expect(rangeHvacAction(state, current)).toBe(action);
}
);
});
@@ -1,109 +0,0 @@
import { describe, expect, it } from "vitest";
import type { Condition } from "../../src/data/automation";
import type { MockHomeAssistant } from "../../src/fake_data/provide_hass";
import { provideHass } from "../../src/fake_data/provide_hass";
type Host = HTMLElement & { hass?: Partial<MockHomeAssistant> };
// `ownUpdateHass` replaces updateHass as the full demo does, see
// demo/src/ha-demo.ts
const setup = (ownUpdateHass = false) => {
const host: Host = document.createElement("div");
const overrides: Partial<MockHomeAssistant> = ownUpdateHass
? {
updateHass: (update: Partial<MockHomeAssistant>) => {
host.hass = { ...host.hass, ...update };
},
}
: {};
const hass = provideHass(host, overrides);
hass.addEntities([
{ entity_id: "light.kitchen", state: "on", attributes: {} },
{ entity_id: "light.hallway", state: "off", attributes: {} },
]);
return hass;
};
const subscribe = async (hass: MockHomeAssistant, condition: Condition) => {
const messages: unknown[] = [];
await hass.connection.subscribeMessage(
(message) => {
messages.push(message);
},
{ type: "subscribe_condition", condition }
);
return messages;
};
const kitchenOn: Condition = {
condition: "state",
entity_id: "light.kitchen",
state: "on",
};
const hallwayOn: Condition = {
condition: "state",
entity_id: "light.hallway",
state: "on",
};
describe("subscribe_condition in the mock backend", () => {
it.each([
["its own", false],
["the host's", true],
])(
"checks a condition again when a state changes, with %s updateHass",
async (_name, ownUpdateHass) => {
const hass = setup(ownUpdateHass);
const messages = await subscribe(hass, hallwayOn);
hass.addEntities({
entity_id: "light.hallway",
state: "on",
attributes: {},
});
expect(messages).toEqual([{ result: false }, { result: true }]);
}
);
it("passes a not only when none of its conditions pass, as in Core", async () => {
const hass = setup();
expect(
await subscribe(hass, {
condition: "not",
conditions: [kitchenOn, hallwayOn],
})
).toEqual([{ result: false }]);
});
it("skips disabled conditions", async () => {
const hass = setup();
expect(
await subscribe(hass, {
condition: "and",
conditions: [kitchenOn, { ...hallwayOn, enabled: false }],
})
).toEqual([{ result: true }]);
});
it("answers a not around a template with an error", async () => {
const hass = setup();
const [message] = await subscribe(hass, {
condition: "not",
conditions: [{ condition: "template", value_template: "{{ true }}" }],
});
expect(message).toHaveProperty("error");
});
});