Compare commits

...
Author SHA1 Message Date
Aidan Timson 9083641ae7 Let custom cards subscribe to visibility conditions (#56284)
* Let custom cards subscribe to visibility on any page

* Send the context entity to core-evaluated conditions
2026-11-30 18:12:32 +02:00
Rodrigo Roque 5fc4ad4e0c Highlight sidebar panels whose url_path has several segments (#56144) 2026-11-30 15:18:20 +00:00
Marcin BauerandClaude Fable 5.2 ba33d2897b Replace brand titles in All brands with the brand name on each card (#56262)
Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-30 16:15:58 +01:00
Christian Wiedel 9484d51694 Flip dropdown menus away from safe areas (#56167)
Pass the safe-area insets to the popup's flip padding, so menus open on
the side with room instead of being squeezed against a navigation bar,
notch or home indicator.
2026-11-30 16:07:04 +01:00
Felipe Santos 55739f2666 Show which integrations use an integration and warn before deleting it (#56188) 2026-11-30 16:01:26 +01:00
Paul Bottein 483b8d1c76 Keep the camera stream details in sync with the player (#56286) 2026-11-30 15:50:41 +01:00
renovate[bot] f589ae2113 Update dependency maplibre-gl to v6.20.0 (#56281)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-30 15:36:06 +01:00
Maarten Lakerveld 1c01df1d6c Center cropped entity pictures in map markers (#56283)
Non-square entity pictures, such as the 16:9 vehicle renders from the
Skoda integration, were cropped from the top-left corner because the
marker background had no position set.
2026-11-30 14:33:21 +00:00
WendelinandClaude Opus 5.5 3216ebc19a Keep MJPEG picture in picture updating in Firefox (#56282)
Firefox only draws the first frame of an MJPEG image into a canvas, so
the picture in picture video froze. A bitmap of the image has the
current frame.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 16:27:08 +02:00
Martin Salinas f18ccc28c6 Don't keep a cancelled circular slider drag as the target (#56152)
* Put the target back when a circular slider drag ends without a change

The climate, humidifier and water heater controls copy the value being dragged into their target. When the drag ended without a change, for example a cancelled touch, that value stayed: the control showed a target that was never sent, the +/- buttons stepped from it, and a change still waiting from the buttons sent it. Keep the target from before the drag and put it back when it ends; a committed drag sets its value right after.

* Drop the kept target when the entity state is synced

A state update during a drag replaced the target, but the target kept from before the drag was put back when the drag ended: a cancelled drag showed the older target, and a committed drag of one bound of a range sent the older other bound.

* Send the kept target while a drag is in progress

A change from the buttons whose debounce ran out during a drag sent the dragged value, which is only a preview, and a cancelled drag then showed the button's value instead of what was sent.

* Keep the dragged value apart from the target

Putting the target from before the drag back needed fixes for state updates, a pending change from the buttons and the buttons used during a drag. Keeping the dragged value apart and only showing it leaves the target to what was set or synced, so all of them work on it as they did before the drag.

* Drop the dragged value when the entity state is synced

The slider takes the synced value, so a keyboard change that a state update overtook committed that value while the dragged one was still shown, and a drag the entity's unavailable state interrupted could be shown after it came back.

* Drop the dragged value only when its synced target changed

The slider only takes a synced value that differs from the one it has. Dropping the dragged value on every state update showed the target while a keyboard change the slider kept was still sent.

* Drop the dragged value when the entity goes unavailable or changes

* Render the control anew when it switches to another entity

* Keep a committed low or high target within the other one

* Pass the shown temperature to the circular slider so a clamped commit moves its handle
2026-11-30 16:23:16 +02:00
WendelinandClaude Opus 5.5 483fb4093f Show a placeholder instead of a broken image for cameras (#56271)
* Show a placeholder instead of a broken image for cameras

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

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

* Show the camera placeholder when a live MJPEG picture fails

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 16:22:15 +02:00
WendelinandClaude Opus 5.5 0f54967037 Simplify the camera stream badge and handle unavailable cameras (#56270)
* Simplify the camera stream badge and handle unavailable cameras

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

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

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

* Move the picture card placeholder to its own pull request

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

* Keep the unavailable placeholder while Home Assistant is disconnected

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

* Skip the camera capabilities while unavailable and explain Disconnected

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 16:22:14 +02:00
Martin Salinas 21ba8fbf79 Keep showing a circular slider's dragged value when its target changes during a drag (#56178)
Keep a circular slider drag's value when its value changes from outside
2026-11-30 16:14:06 +02:00
ChrisandClaude Fable 5.2 ad8cea50d7 Stop subscribing to core user data twice on page load (#56214)
Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-11-30 14:06:51 +00:00
renovate[bot] 7df3f5ca88 Update formatjs (#56070)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-30 13:47:38 +00:00
Aidan Timson 50e61275d5 Fix the demo gaps found by the live demos in the docs (#56166)
* Give the demo's heating and cooling thermostats their action from the temperatures

* Answer state visibility conditions in the demo's mock backend

* Add the battery level icons of sensors to the demo

* Check demo visibility conditions as Core does, also with the demo's own updateHass

* Let a demo thermostat in heat or cool mode only heat or cool for its range
2026-11-30 14:39:16 +01:00
Aidan Timson 91a941475c Redraw the button row when hass changes (#56266) 2026-11-30 14:22:35 +01:00
renovate[bot] cf79aecca9 Update dependency eslint-config-prettier to v10.1.9 (#56264)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-30 14:25:26 +02:00
37 changed files with 1345 additions and 438 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.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",
"@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",
"@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.0",
"intl-messageformat": "12.2.1",
"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.19.0",
"maplibre-gl": "6.20.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.8",
"eslint-config-prettier": "10.1.9",
"eslint-import-resolver-webpack": "0.13.11",
"eslint-plugin-import-x": "4.18.1",
"eslint-plugin-lit": "2.3.1",
+109 -117
View File
@@ -241,32 +241,32 @@ importers:
specifier: 2.0.17
version: 2.0.17
'@formatjs/intl-datetimeformat':
specifier: 8.0.3
version: 8.0.3
specifier: 8.2.2
version: 8.2.2
'@formatjs/intl-displaynames':
specifier: 8.0.3
version: 8.0.3
specifier: 8.0.5
version: 8.0.5
'@formatjs/intl-durationformat':
specifier: 0.13.0
version: 0.13.0
specifier: 0.13.2
version: 0.13.2
'@formatjs/intl-getcanonicallocales':
specifier: 3.4.0
version: 3.4.0
specifier: 3.4.2
version: 3.4.2
'@formatjs/intl-listformat':
specifier: 9.1.0
version: 9.1.0
specifier: 9.1.2
version: 9.1.2
'@formatjs/intl-locale':
specifier: 5.5.0
version: 5.5.0
specifier: 5.5.2
version: 5.5.2
'@formatjs/intl-numberformat':
specifier: 10.1.0
version: 10.1.0
specifier: 10.1.2
version: 10.1.2
'@formatjs/intl-pluralrules':
specifier: 7.1.0
version: 7.1.0
specifier: 7.1.2
version: 7.1.2
'@formatjs/intl-relativetimeformat':
specifier: 13.0.3
version: 13.0.3
specifier: 13.0.5
version: 13.0.5
'@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.19.0)
version: 0.1.4(@types/[email protected])([email protected])(maplibre-gl@6.20.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.19.0)
version: 9.1.3(maplibre-gl@6.20.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.0
version: 12.2.0
specifier: 12.2.1
version: 12.2.1
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.19.0
version: 6.19.0
specifier: 6.20.0
version: 6.20.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.8
version: 10.1.8([email protected]([email protected]))
specifier: 10.1.9
version: 10.1.9([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]0':
resolution: {integrity: sha512-npIs6UARNOg5amJY5UOVsd6HUQQfzYjet0sa0SWIqzsnVhxLSpaIx2DjoIVrr/vqmjURjvroeW6dItjfy3Uf8A==}
'@formatjs/[email protected]2':
resolution: {integrity: sha512-KSFLj/KBZfanDW3BpMytGLrZFB8gGvxbtJkB2NBkw3SW0nR8Yno2Ea2s62vCFaJ4GHfGMWDoXfBxzpfKwOfgAg==}
'@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].7':
resolution: {integrity: sha512-zXfhLpvA6T7+efdt9JLbBwZ00tT7NsBMDVnDu8rpHeNNv8KfRZAMo2gkG0k9lK/Nzc//3kJ9pImsfuJxk3KhUA==}
'@formatjs/[email protected].8':
resolution: {integrity: sha512-Y9YFFfeBDkAWmLWD3LVNHbHlyELsP2lYRNoY6+QhtPh1/ujCiX5QYBzAqe0cWdkCxKVezHLt0qjWz1veEUV7UA==}
'@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.0.3':
resolution: {integrity: sha512-LQed+WhJBlceMJ4Zbe7dDe7Wn15le9t5HXfOFGdJYM/MGDyn56LTHlSzPzFjsJA0rvyp4FjN28jRQiMwtsji6A==}
'@formatjs/intl-datetimeformat@8.2.2':
resolution: {integrity: sha512-J1NBeAs3GJRfZRXyLDxK43OMBk+5UDUa7bgwoUNLvr1lUfXACfl+K6DvdQ/mpPaPHimfPOBzGGIX6oDfRlVZNQ==}
'@formatjs/[email protected].3':
resolution: {integrity: sha512-UhKG1OwrbQzZNKIcmZu+/JR5SOxE25RWmUzxaNfQ04AJ4OwxNkTvAbVX0ojnkm0i8Qs4E8ElIoBdA6F8XTkJXw==}
'@formatjs/[email protected].5':
resolution: {integrity: sha512-1hMhtc8xVlidZ0olqI3MFmOXb2oWXio1wz7QBP3EsLnegmbBeOGU05TxCnIuxClrXNlg+J5I5ossg6Xs2TmsIQ==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-hZMyYyxZOb41/WuBaA3F3AQtIR0z3H8kGephf5yaqwiVmEamPh6b7ElWEUEl1xlQsg4Z6/AIHEX0SaWfw2SHAg==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-fP3mpM/8S1L9OXQPkli28xmQhZMEfg/EGub1Yw7/nYKkQqqhdX7xMFZ1QTUFC8epbhM5eIgtGmTqXZ/tNRcAuw==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-7VfxOKr+ZUL4r5XO+LWiabp+m5595LacC+upPqSYf5RXxY5NDWEs/DJfHrjv59SWXt6UicKZbtNuHcAUZ45AEw==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-b0Ywtqh1DS5bc3NXqm2VMbtDN9mYQPVVIEDPkxIi8SlV5eq7NkE0ZET0IHDWgl1lLh74hjGJv8iPy7D/y/SNNA==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-Hh2kjuXQAsoadfb8ZR7+NRu6txiPJ7qo+3c87C/Ii55CO2lVPFjMp7uxsWUQECCfnuhD6D1HBVdUhmBv66MOwA==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-9FDt0zvn3IzULi4RrPwU9W5EQ0shaJLIRdet+w85IDwJ6teK729KqCUlEtqfhLfztim0fJ7pt3jD2mDBdZXIrw==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-PmM3wB2Uo5Bu8y8itD5Z4NZGOak+1NKsiQydFgxuSXVzOV1GQd3ytkqQ/jOCLDNowcqw7xbL42fYBN9xzm08gA==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-4v0ZW2KQ8874I4L74zTqk1sWwxogxJzvJV3asaIyyAOJAK5Rjwe9r+SGmLm2HleDq60reuaSRxuiUKIFalWlUw==}
'@formatjs/[email protected].1':
resolution: {integrity: sha512-gBqglQK9rXuHsLmM8wzTMBy4Xo4d0jamirIVKuEL8F1rwbskWdpMA1kZarSkny+uvr5q/K6GSzE0Rcq1wZLl3g==}
'@formatjs/[email protected].3':
resolution: {integrity: sha512-qHGNMjYbewa1uteT7VFPot2+q9glcBMVRQhmQNXgNYia35Arzln7vJ4Zyj6ktm6POzRc3SW/CTAhhSnMQSFvJg==}
'@formatjs/[email protected]':
resolution: {integrity: sha512-ePEgLgVCqi2BBFnTMWPfIghu6FkbZnnBVhO2sSxvLfrdFw7wCHAHiDoM2h4NRgjbaY7+B7HgOLZGkK187pZTZg==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-/uAIUEKpVleUU6MMIOHVcA4EetRsEZeMkOeKbQUvWLsDYlVCXl25jDFIbcCjG8uGrBD4fT5p6j3JDXgNYnqodQ==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-lBLFsZYJTTvh2oRs+vExpd4Yy+kVe4zPZRwlMohpMQihLLboXicIa2MgN68FwQYqQseeJTBkEWh6dyN1PR4zYA==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-4uPvqKd9uke8VuimXDbPlK8jEdqpH9q0wFTCOtth15F2xtjLOOfadnCxBNn5eZjOt/7dbTmMCsN8W6FGSDftzg==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-ZsLZvUmRH1eZWqiYEj5/e7rtlIBUddSo4u73itGeetxFqbxYCE7nOBcHMH49HgGfmoMSXHW5NWQ7eGfFoM2hhg==}
'@formatjs/[email protected].3':
resolution: {integrity: sha512-5nyIp4F/59A5hcfU6lZphSslpildVSirqudWfygBENGdGSHmggZVjhoad458XWEgtUd6d0JoiwsiUBFLfbqJ9Q==}
'@formatjs/[email protected].5':
resolution: {integrity: sha512-mqtN0lrWIUkSZu4bluWqCWZ7v5umpWN2JFMv2M3PkqTNqz7h57m3o9lHcAd1yK6gjF+Zs2+RQWaxKQqJ8EN1Mg==}
'@formatjs/[email protected].0':
resolution: {integrity: sha512-JPnyvQq+ze3ek7A4xqjYUDaOLT9uE2OGnovxdkDHPoKHTz2MuxuuMyDyv37jrSn6NJgbR3vtu2VFTvBUdql99Q==}
'@formatjs/[email protected].2':
resolution: {integrity: sha512-PKUOWdNCTmQ9JTKdvsmWYwNRb78dfkb4hKY7XqCFc5sPH2c079NTR9G6VeDEnno+BEMAowAvrQcd0fAjziUXIw==}
'@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@6.3.2':
resolution: {integrity: sha512-7WFEEkeEjg2foQleJOYl7e2ldi4ZiXp8XV2ibqyquFAA/4iaJgtdEKBrfEpPPVem/VkXS1OXqZsHl6V/MwQYeQ==}
'@maplibre/geojson-vt@7.0.1':
resolution: {integrity: sha512-xq3+TiG4hZtx9lHjq/oZginEBtJLJTJqRVmEIhPDSznlkl231z/p4foorEqASpD233EHO9+GVnnu6GNA4Pl+YQ==}
'@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.9.0':
resolution: {integrity: sha512-cQZK2lG3d6I5FjriPZCgJx/LiVMpWqoVibF+cgp2mkQ/P4BIGOsrA3WsvLw1wB28Q9JU9v2fapsQUJUbjjwa6g==}
'@maplibre/maplibre-gl-style-spec@26.11.0':
resolution: {integrity: sha512-MQMBqOkmVm7fLLun2l/bwOv9bURkvyEVISo/OYleb9/nsnfjQ6gs29isysARt5FK/k9RFM4SmH4eMTUQGlv0Pw==}
hasBin: true
'@maplibre/[email protected]':
@@ -5039,8 +5039,8 @@ packages:
resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}
engines: {node: '>=10'}
[email protected].8:
resolution: {integrity: sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==}
[email protected].9:
resolution: {integrity: sha512-JnOR0K4u67CWOiSS3vaduGlLUWS32lGiyglMIV6AyvK9DBRpS+QhR2ESKaUe2eWGRsdVmrxy77yaOk2hzDa4Bg==}
hasBin: true
peerDependencies:
eslint: '>=7.0.0'
@@ -5669,8 +5669,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-UmdmHUmp5CIKKjSoE10la5yfU+AYJAaiYLsodbjL4lji83JNvgOQUjGaGhGrpFCb0Uh7sl7qfP1IyILa8Z40ug==}
[email protected].0:
resolution: {integrity: sha512-zFzW80iYSSJm4V185g3ItJQ96lBZ2RDO8O8qmRiPAAVKYXJeHfDQN2ITdtLlV+CjSi9Lo7zVW9xGt9CPCx7J6A==}
[email protected].1:
resolution: {integrity: sha512-GvlBHj5Blu0ro39QT/QEbX3I23GAYvDh9/B+l33NnXjmYe/UoqFgZjNZoqPa6QdWwAliP/i27y5JeKjFkqlbRA==}
[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.19.0:
resolution: {integrity: sha512-3bOrnfddggUYudLGJFsYFvqulUyvSxy4iQzd/uURI7ZhgYEZifdSrECujRSghaCpc+v/ZsFI0Y6ZsGSilEtE+w==}
maplibre-gl@6.20.0:
resolution: {integrity: sha512-7manvqXeNoN0mKRzenYDopkb3VW9j7iag45RvopkOVFZ7c+La7CBWtK8eBS5bKrI6NyxqAIxPxIG1PMcotcY1w==}
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.1.2:
resolution: {integrity: sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==}
pbf@5.2.0:
resolution: {integrity: sha512-R6YptaRZl0t9SVO6MllszYq1IkaOQawzprndmvQxEoFrtvX7fT+oNIPoVD152NOllmLWEC3ThxzUTqBX12q5FQ==}
hasBin: true
[email protected]:
@@ -6994,9 +6994,6 @@ 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'}
@@ -9816,7 +9813,7 @@ snapshots:
'@floating-ui/[email protected]': {}
'@formatjs/[email protected]0': {}
'@formatjs/[email protected]2': {}
'@formatjs/[email protected]':
dependencies:
@@ -9829,7 +9826,7 @@ snapshots:
dependencies:
tslib: 2.9.1
'@formatjs/[email protected].7': {}
'@formatjs/[email protected].8': {}
'@formatjs/[email protected]':
dependencies:
@@ -9848,56 +9845,55 @@ snapshots:
'@formatjs/[email protected]': {}
'@formatjs/intl-datetimeformat@8.0.3':
'@formatjs/intl-datetimeformat@8.2.2':
dependencies:
'@formatjs/bigdecimal': 0.2.10
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/[email protected].3':
'@formatjs/[email protected].5':
dependencies:
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/[email protected].0':
'@formatjs/[email protected].2':
dependencies:
'@formatjs/bigdecimal': 0.2.10
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/bigdecimal': 0.2.12
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/[email protected].0': {}
'@formatjs/[email protected].2': {}
'@formatjs/[email protected].0':
'@formatjs/[email protected].2':
dependencies:
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/[email protected].0':
'@formatjs/[email protected].2':
dependencies:
'@formatjs/intl-getcanonicallocales': 3.4.0
'@formatjs/intl-supportedvaluesof': 3.1.0
'@formatjs/intl-getcanonicallocales': 3.4.2
'@formatjs/intl-supportedvaluesof': 3.1.2
'@formatjs/[email protected].1':
'@formatjs/[email protected].3':
dependencies:
'@formatjs/fast-memoize': 3.1.7
'@formatjs/fast-memoize': 3.1.8
'@formatjs/[email protected]':
dependencies:
tslib: 2.9.1
'@formatjs/[email protected].0':
'@formatjs/[email protected].2':
dependencies:
'@formatjs/bigdecimal': 0.2.10
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/bigdecimal': 0.2.12
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/[email protected].0':
'@formatjs/[email protected].2':
dependencies:
'@formatjs/bigdecimal': 0.2.10
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/bigdecimal': 0.2.12
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/[email protected].3':
'@formatjs/[email protected].5':
dependencies:
'@formatjs/intl-localematcher': 0.10.1
'@formatjs/intl-localematcher': 0.10.3
'@formatjs/[email protected].0':
'@formatjs/[email protected].2':
dependencies:
'@formatjs/fast-memoize': 3.1.7
'@formatjs/fast-memoize': 3.1.8
'@formatjs/[email protected]([email protected])':
dependencies:
@@ -10229,19 +10225,19 @@ snapshots:
dependencies:
'@mapbox/point-geometry': 1.1.0
'@types/geojson': 7946.0.16
pbf: 5.1.2
pbf: 5.2.0
'@maplibre/geojson-vt@6.3.2':
'@maplibre/geojson-vt@7.0.1':
dependencies:
kdbush: 4.1.0
'@maplibre/[email protected](@types/[email protected])([email protected])(maplibre-gl@6.19.0)':
'@maplibre/[email protected](@types/[email protected])([email protected])(maplibre-gl@6.20.0)':
dependencies:
'@types/leaflet': 1.9.23
leaflet: 1.9.4
maplibre-gl: 6.19.0
maplibre-gl: 6.20.0
'@maplibre/maplibre-gl-style-spec@26.9.0':
'@maplibre/maplibre-gl-style-spec@26.11.0':
dependencies:
'@mapbox/jsonlint-lines-primitives': 2.0.3
'@mapbox/unitbezier': 1.0.0
@@ -10258,7 +10254,7 @@ snapshots:
dependencies:
'@mapbox/point-geometry': 1.1.0
'@types/geojson': 7946.0.16
pbf: 5.1.2
pbf: 5.2.0
'@marijn/[email protected]': {}
@@ -11759,11 +11755,11 @@ snapshots:
'@unrs/[email protected]':
optional: true
'@versatiles/[email protected](maplibre-gl@6.19.0)':
'@versatiles/[email protected](maplibre-gl@6.20.0)':
dependencies:
'@maplibre/maplibre-gl-style-spec': 26.9.0
'@maplibre/maplibre-gl-style-spec': 26.11.0
optionalDependencies:
maplibre-gl: 6.19.0
maplibre-gl: 6.20.0
'@vibrant/[email protected]': {}
@@ -12933,7 +12929,7 @@ snapshots:
[email protected]: {}
[email protected].8([email protected]([email protected])):
[email protected].9([email protected]([email protected])):
dependencies:
eslint: 10.15.0([email protected])
@@ -13679,9 +13675,9 @@ snapshots:
'@formatjs/icu-messageformat-parser': 2.11.2
tslib: 2.9.1
[email protected].0:
[email protected].1:
dependencies:
'@formatjs/fast-memoize': 3.1.7
'@formatjs/fast-memoize': 3.1.8
'@formatjs/icu-messageformat-parser': 3.5.23
[email protected]: {}
@@ -14232,14 +14228,14 @@ snapshots:
[email protected]: {}
maplibre-gl@6.19.0:
maplibre-gl@6.20.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': 6.3.2
'@maplibre/maplibre-gl-style-spec': 26.9.0
'@maplibre/geojson-vt': 7.0.1
'@maplibre/maplibre-gl-style-spec': 26.11.0
'@maplibre/mlt': 1.3.0
'@maplibre/vt-pbf': 4.3.3
'@types/geojson': 7946.0.16
@@ -14248,7 +14244,7 @@ snapshots:
gl-matrix: 3.4.4
kdbush: 4.1.0
murmurhash-js: 1.0.0
pbf: 5.1.2
pbf: 5.2.0
potpack: 2.1.0
quickselect: 3.0.0
tinyqueue: 3.0.0
@@ -14826,9 +14822,9 @@ snapshots:
[email protected]: {}
pbf@5.1.2:
pbf@5.2.0:
dependencies:
resolve-protobuf-schema: 2.1.0
protocol-buffers-schema: 3.6.1
[email protected]: {}
@@ -15058,10 +15054,6 @@ snapshots:
[email protected]: {}
[email protected]:
dependencies:
protocol-buffers-schema: 3.6.1
[email protected]:
dependencies:
es-errors: 1.3.0
@@ -0,0 +1,74 @@
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
import type {
ConditionContext,
VisibilityCondition,
} from "../../panels/lovelace/common/validate-condition";
import { addEntityToCondition } from "../../panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../types";
import type { ConditionEvaluation } from "../controllers/condition-evaluator-controller";
import { ConditionEvaluatorController } from "../controllers/condition-evaluator-controller";
import { dropInvalidConditions } from "./sanitize";
export interface VisibilitySubscription {
/** Pass each new hass object so client-side conditions check again. */
update(hass: HomeAssistant): void;
/** Close the subscriptions. `onChange` is not called again. */
unsubscribe(): void;
}
/**
* Live visibility of a list of dashboard visibility conditions, for code
* without a Lit host, such as custom cards and plugins. Conditions core
* evaluates are subscribed to; the rest are checked locally. Reports
* `unknown` until core replies.
*/
export const subscribeVisibility = (
hass: HomeAssistant,
conditions: VisibilityCondition[],
onChange: (result: ConditionEvaluation, error?: string) => void,
context: ConditionContext = {}
): VisibilitySubscription => {
// The controller only needs a host to register with and to re-render.
const host: ReactiveControllerHost = {
addController: () => undefined,
removeController: () => undefined,
requestUpdate: () => undefined,
updateComplete: Promise.resolve(true),
};
let active = true;
const controller = new ConditionEvaluatorController(host, {
resubscribeDelay: 0,
onResult: (result, error) => {
if (active) {
onChange(result, error);
}
},
});
const sanitized = dropInvalidConditions(conditions);
const { entity_id: entityId } = context;
// Core-evaluated conditions never see the context, so fold its entity in
// first, as the dashboard mixin does.
const validConditions = entityId
? sanitized.map((condition) => addEntityToCondition(condition, entityId))
: sanitized;
const getContext = () => context;
controller.hostConnected();
controller.observe(validConditions, hass, getContext);
return {
update: (newHass) => {
if (active) {
controller.observe(validConditions, newHass, getContext);
}
},
unsubscribe: () => {
active = false;
controller.hostDisconnected();
},
};
};
@@ -0,0 +1,33 @@
import { mdiVideoOffOutline } from "@mdi/js";
import { css, html, LitElement } from "lit";
import { customElement } from "lit/decorators";
import "../ha-svg-icon";
/**
* @element ha-camera-placeholder
*
* @summary Shows instead of a camera's picture when there is none, like
* while the camera is unavailable.
*/
@customElement("ha-camera-placeholder")
export class HaCameraPlaceholder extends LitElement {
protected render() {
return html`<ha-svg-icon .path=${mdiVideoOffOutline}></ha-svg-icon>`;
}
static styles = css`
:host {
display: flex;
align-items: center;
justify-content: center;
color: var(--secondary-text-color);
--mdc-icon-size: 40px;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-camera-placeholder": HaCameraPlaceholder;
}
}
+66 -12
View File
@@ -22,12 +22,16 @@ import type { LocalizeFunc } from "../../common/translations/localize";
import { nextRender } from "../../common/util/render-status";
import type { CameraCapabilities, CameraEntity } from "../../data/camera";
import type { CameraStreamStatus } from "../../data/camera-streams";
import { showCameraStreamInfoDialog } from "../../dialogs/camera/show-dialog-camera-stream-info";
import {
showCameraStreamInfoDialog,
type CameraStreamInfo,
} from "../../dialogs/camera/show-dialog-camera-stream-info";
import "../ha-camera-stream";
import type { HaCameraStream } from "../ha-camera-stream";
import "../ha-icon-button";
import "../ha-spinner";
import "../ha-svg-icon";
import "./ha-camera-placeholder";
import "./ha-camera-stream-badge";
import {
fitPicture,
@@ -107,6 +111,8 @@ export class HaCameraPlayer extends LitElement {
@state() private _capabilities?: CameraCapabilities;
private _streamInfoCallbacks = new Set<(info: CameraStreamInfo) => void>();
@state() private _video?: HTMLVideoElement;
@state() private _muted = false;
@@ -212,6 +218,7 @@ export class HaCameraPlayer extends LitElement {
);
clearTimeout(this._controlsTimeout);
clearTimeout(this._wheelHintTimeout);
this._streamInfoCallbacks.clear();
this._unbindVideo(this._video);
this._video = undefined;
this._pointers.clear();
@@ -251,6 +258,10 @@ export class HaCameraPlayer extends LitElement {
this._unbindVideo(changedProps.get("_video") as HTMLVideoElement);
this._bindVideo(this._video);
}
if (changedProps.has("_status") || changedProps.has("_capabilities")) {
const info = this._streamInfo();
this._streamInfoCallbacks.forEach((callback) => callback(info));
}
}
protected render() {
@@ -262,11 +273,12 @@ export class HaCameraPlayer extends LitElement {
// controls and zoom of this one can't reach, so it shows just the stream
const inApp = Boolean(status.inApp);
const zoomed = !inApp && isZoomed(this._zoom);
// Stays while the connection changes, so the user sees what happens
// Stays while not live, so the user sees what happens
const badgeVisible =
this._controlsVisible ||
status.connecting ||
status.upgrading !== undefined;
Boolean(status.unavailable) ||
Boolean(status.disconnected);
return html`
<div
@@ -319,6 +331,11 @@ export class HaCameraPlayer extends LitElement {
@camera-capabilities-changed=${this._capabilitiesChanged}
@camera-poster-size-changed=${this._posterSizeChanged}
></ha-camera-stream>
${
status.unavailable
? html`<ha-camera-placeholder></ha-camera-placeholder>`
: nothing
}
</div>
${inApp ? nothing : this._renderControls(status, zoomed, badgeVisible)}
</div>
@@ -332,7 +349,10 @@ export class HaCameraPlayer extends LitElement {
) {
return html`
${
this._paused && !status.connecting
this._paused &&
!status.connecting &&
!status.unavailable &&
!status.disconnected
? html`<ha-icon-button
class="control pinned play"
.label=${this._localize("ui.components.camera-player.play")}
@@ -543,15 +563,21 @@ export class HaCameraPlayer extends LitElement {
) {
const oldStatus = this._status;
this._status = ev.detail;
if (ev.detail.inApp) {
if (ev.detail.inApp || ev.detail.unavailable) {
this._zoom = ZOOM_PAN_IDENTITY;
}
if (
oldStatus.connecting !== ev.detail.connecting ||
oldStatus.unavailable !== ev.detail.unavailable ||
oldStatus.disconnected !== ev.detail.disconnected
) {
// Shows the new state for a moment
this._showControls();
}
if (
oldStatus.connecting !== ev.detail.connecting ||
oldStatus.type !== ev.detail.type
) {
// Shows the new connection for a moment
this._showControls();
this._updateVideo();
}
}
@@ -586,10 +612,26 @@ export class HaCameraPlayer extends LitElement {
this._posterSize = ev.detail.size;
}
private _showStreamInfo() {
showCameraStreamInfoDialog(this, {
private _streamInfo(): CameraStreamInfo {
return {
status: this._status,
supportedTypes: this._capabilities?.frontend_stream_types,
};
}
private _subscribeStreamInfo = (
callback: (info: CameraStreamInfo) => void
) => {
this._streamInfoCallbacks.add(callback);
callback(this._streamInfo());
return () => {
this._streamInfoCallbacks.delete(callback);
};
};
private _showStreamInfo() {
showCameraStreamInfoDialog(this, {
subscribe: this._subscribeStreamInfo,
});
}
@@ -820,12 +862,17 @@ export class HaCameraPlayer extends LitElement {
this._zoom = refitZoomPan(this._zoom, oldViewport, viewport);
};
// The app's own player and a camera without picture can't be zoomed
private _canZoom(): boolean {
return !this._status.inApp && !this._status.unavailable;
}
private _resetZoom() {
this._zoom = ZOOM_PAN_IDENTITY;
}
private _wheel(ev: WheelEvent) {
if (!this._viewport || this._status.inApp) {
if (!this._viewport || !this._canZoom()) {
return;
}
// A pinch on a touchpad scrolls with ctrl held
@@ -869,7 +916,7 @@ export class HaCameraPlayer extends LitElement {
}
private _doubleClick(ev: MouseEvent) {
if (!this._viewport || this._status.inApp) {
if (!this._viewport || !this._canZoom()) {
return;
}
if (isZoomed(this._zoom)) {
@@ -912,7 +959,8 @@ export class HaCameraPlayer extends LitElement {
this._showControls();
}
const pointer = this._pointers.get(ev.pointerId);
if (!pointer || !this._viewport) {
// Taps still toggle the controls when the picture can't be zoomed
if (!pointer || !this._viewport || !this._canZoom()) {
return;
}
const { rect, viewport } = this._measureViewport();
@@ -1106,6 +1154,12 @@ export class HaCameraPlayer extends LitElement {
transition: transform var(--ha-animation-duration-fast) ease-out;
}
ha-camera-placeholder {
position: absolute;
inset: 0;
color: rgba(255, 255, 255, 0.5);
}
.viewport.gesture ha-camera-stream {
transition: none;
will-change: transform;
+24 -51
View File
@@ -6,7 +6,6 @@ import type {
CameraStreamStatus,
CameraStreamType,
} from "../../data/camera-streams";
import "../ha-spinner";
/** Names of the protocols, the same in every language. */
export const CAMERA_STREAM_TYPE_NAMES: Record<CameraStreamType, string> = {
@@ -16,8 +15,10 @@ export const CAMERA_STREAM_TYPE_NAMES: Record<CameraStreamType, string> = {
};
/**
* Shows over a camera stream how it is connected. A faster stream that still
* connects in the background is shown next to the current one.
* @element ha-camera-stream-badge
*
* @summary Shows over a camera stream whether it is live. Selecting it
* shows how it is connected.
*/
@customElement("ha-camera-stream-badge")
export class HaCameraStreamBadge extends LitElement {
@@ -32,51 +33,27 @@ export class HaCameraStreamBadge extends LitElement {
if (!status) {
return nothing;
}
const connecting = status.connecting || !status.type;
const label = connecting
? this._localize("ui.components.camera-player.connecting")
: CAMERA_STREAM_TYPE_NAMES[status.type!];
const connection = status.disconnected
? "disconnected"
: status.unavailable
? "unavailable"
: status.connecting || !status.type
? "connecting"
: "live";
return html`
<button
type="button"
aria-label=${this._ariaLabel(status)}
class=${connecting ? "connecting" : "live"}
>
<button type="button" class=${connection} aria-describedby="details">
<span class="dot"></span>
<span class="label">${label}</span>
${
status.upgrading
? html`<span class="upgrading" aria-hidden="true">
<ha-spinner></ha-spinner>
${CAMERA_STREAM_TYPE_NAMES[status.upgrading]}
</span>`
: nothing
}
<span class="label"
>${this._localize(`ui.components.camera-player.${connection}`)}</span
>
</button>
<span id="details" hidden
>${this._localize("ui.components.camera-player.show_details")}</span
>
`;
}
private _ariaLabel(status: CameraStreamStatus): string {
if (status.connecting || !status.type) {
return this._localize(
"ui.components.camera-player.stream_info_connecting"
);
}
if (status.upgrading) {
return this._localize(
"ui.components.camera-player.stream_info_upgrading",
{
type: CAMERA_STREAM_TYPE_NAMES[status.type],
upgrading: CAMERA_STREAM_TYPE_NAMES[status.upgrading],
}
);
}
return this._localize("ui.components.camera-player.stream_info", {
type: CAMERA_STREAM_TYPE_NAMES[status.type],
});
}
static styles = css`
:host {
display: inline-flex;
@@ -120,16 +97,12 @@ export class HaCameraStreamBadge extends LitElement {
animation: pulse 1.2s ease-in-out infinite;
}
.upgrading {
display: inline-flex;
align-items: center;
gap: var(--ha-space-1);
padding-inline-start: var(--ha-space-1);
border-inline-start: 1px solid rgba(255, 255, 255, 0.3);
opacity: 0.7;
--ha-spinner-indicator-color: var(--ha-color-white);
--ha-spinner-size: 10px;
--ha-spinner-divider-color: rgba(255, 255, 255, 0.3);
.unavailable .dot {
background-color: rgba(255, 255, 255, 0.5);
}
.disconnected .dot {
background-color: var(--ha-color-red-60);
}
@keyframes pulse {
+116 -17
View File
@@ -34,6 +34,8 @@ import {
connectionContext,
formattersContext,
} from "../data/context";
import { UNAVAILABLE } from "../data/entity/entity";
import "./camera/ha-camera-placeholder";
import "./ha-hls-player";
import type { HaHLSPlayer } from "./ha-hls-player";
import "./ha-mjpeg-player";
@@ -111,6 +113,13 @@ export class HaCameraStream extends LitElement {
// The app plays the HLS stream in its own player, over the page
@state() private _hlsInApp = false;
// WebRTC is the only stream and failed, its player shows why
@state() private _webRtcFailed = false;
// The MJPEG image failed, it is tried again with the next access token or
// once Home Assistant reconnects
@state() private _mjpegImageFailed = false;
@query("ha-web-rtc-player") private _webRtcPlayer?: HaWebRtcPlayer;
@query("ha-mjpeg-player") private _mjpegPlayer?: HaMjpegPlayer;
@@ -153,9 +162,32 @@ export class HaCameraStream extends LitElement {
this._config.config.state === STATE_RUNNING &&
oldConfig.config?.state !== STATE_RUNNING;
if (entityChanged || backendStarted) {
this._getCapabilities();
this._getPosterUrl();
const oldStateObj = changedProps.get("stateObj") as
CameraEntity | undefined;
const becameAvailable =
!entityChanged &&
this.stateObj !== undefined &&
oldStateObj?.state === UNAVAILABLE &&
!this._unavailable;
if (entityChanged || backendStarted || becameAvailable) {
if (this._unavailable) {
// Core often doesn't know the camera then, as its integration
// didn't load. Its capabilities are fetched once it is back.
this._clearCapabilities();
} else {
this._getCapabilities();
this._getPosterUrl();
}
}
if (
oldStateObj &&
oldStateObj.attributes.access_token !==
this.stateObj?.attributes.access_token
) {
// A new token gives a new MJPEG address, worth another try
this._mjpegImageFailed = false;
}
const oldConnection = changedProps.get("_connection") as
@@ -170,6 +202,10 @@ export class HaCameraStream extends LitElement {
}
}
private get _unavailable(): boolean {
return this.stateObj?.state === UNAVAILABLE;
}
/** The microphone track sent to the camera, only on WebRTC streams. */
public get microphoneTrack(): MediaStreamTrack | undefined {
return this._webRtcPlayer?.microphoneTrack;
@@ -238,29 +274,63 @@ export class HaCameraStream extends LitElement {
this._visibleStreamType = visibleStreamType;
fireEvent(this, "stream-type-changed", { type: visibleStreamType });
}
const status: CameraStreamStatus = {
...computeCameraStreamStatus(
streams,
// Nothing plays while Home Assistant is disconnected
this._connection.connected ? this._loadedStreams : new Set(),
this._hlsStreams,
this._webRtcStreams
),
inApp: visibleStreamType === STREAM_TYPE_HLS && this._hlsInApp,
};
const status = this._computeStatus(streams, visibleStreamType);
if (
!this._status ||
status.type !== this._status.type ||
status.connecting !== this._status.connecting ||
status.upgrading !== this._status.upgrading ||
status.hasAudio !== this._status.hasAudio ||
status.inApp !== this._status.inApp
status.inApp !== this._status.inApp ||
status.unavailable !== this._status.unavailable ||
status.disconnected !== this._status.disconnected
) {
this._status = status;
fireEvent(this, "camera-stream-status-changed", status);
}
}
private _computeStatus(
streams: CameraStream[],
visibleStreamType?: CameraStreamType
): CameraStreamStatus {
// A playing WebRTC stream can come straight from the camera or an
// external go2rtc, it then keeps playing without Home Assistant
const playsWithoutHomeAssistant =
visibleStreamType === STREAM_TYPE_WEB_RTC &&
this._loadedStreams.has(STREAM_TYPE_WEB_RTC);
const inApp = visibleStreamType === STREAM_TYPE_HLS && this._hlsInApp;
if (!this._connection.connected && !playsWithoutHomeAssistant) {
// Kept so the player still shows its placeholder instead of nothing
return {
connecting: false,
hasAudio: false,
inApp,
disconnected: "home_assistant",
unavailable: this._unavailable,
};
}
if (this._unavailable) {
return { connecting: false, hasAudio: false, unavailable: true };
}
if (this._webRtcFailed) {
return {
connecting: false,
hasAudio: false,
disconnected: "stream_failed",
};
}
return {
...computeCameraStreamStatus(
streams,
this._loadedStreams,
this._hlsStreams,
this._webRtcStreams
),
inApp,
};
}
protected render() {
if (!this.stateObj) {
return nothing;
@@ -297,6 +367,11 @@ export class HaCameraStream extends LitElement {
@load=${this._handleMjpegLoad}
></ha-mjpeg-player>`;
}
if (this._mjpegImageFailed) {
return html`<ha-camera-placeholder
style=${styleMap({ aspectRatio: this.aspectRatio ?? 16 / 9 })}
></ha-camera-placeholder>`;
}
return html`<img
.src=${streamUrl}
style=${styleMap({
@@ -305,6 +380,7 @@ export class HaCameraStream extends LitElement {
})}
alt=${`Preview of the ${this._formatters?.formatEntityName(this.stateObj) ?? ""} camera.`}
@load=${this._handleImageLoad}
@error=${this._handleImageError}
/>`;
}
@@ -346,6 +422,9 @@ export class HaCameraStream extends LitElement {
}
private _currentStreams() {
if (this._unavailable) {
return [];
}
return this._streams(
this._capabilities?.frontend_stream_types,
this._hlsStreams,
@@ -353,10 +432,15 @@ export class HaCameraStream extends LitElement {
);
}
private async _getCapabilities() {
/** Returns the request number, so an older request can be dropped. */
private _clearCapabilities() {
this._capabilities = undefined;
this._resetStreams();
const request = ++this._capabilitiesRequest;
return ++this._capabilitiesRequest;
}
private async _getCapabilities() {
const request = this._clearCapabilities();
if (!supportsFeature(this.stateObj!, CameraEntityFeature.STREAM)) {
this._capabilities = {
frontend_stream_types: [],
@@ -379,11 +463,14 @@ export class HaCameraStream extends LitElement {
this._webRtcStreams = undefined;
this._loadedStreams = new Set();
this._hlsInApp = false;
this._webRtcFailed = false;
this._mjpegImageFailed = false;
this._mjpegPlayer?.restart();
}
private _restartMjpeg() {
this._setLoaded(MJPEG_STREAM, false);
this._mjpegImageFailed = false;
this._mjpegPlayer?.restart();
}
@@ -443,6 +530,11 @@ export class HaCameraStream extends LitElement {
fireEvent(this, "load");
}
private _handleImageError() {
this._mjpegImageFailed = true;
this._setLoaded(MJPEG_STREAM, false);
}
private _handleMjpegLoad() {
this._setLoaded(MJPEG_STREAM, true);
}
@@ -458,6 +550,7 @@ export class HaCameraStream extends LitElement {
}
private _handleWebRtcLoad() {
this._webRtcFailed = false;
this._setLoaded(STREAM_TYPE_WEB_RTC, true);
}
@@ -477,6 +570,7 @@ export class HaCameraStream extends LitElement {
) {
// Without another stream type, keep the player to show why it failed.
// Only a browser without WebRTC falls back to MJPEG.
this._webRtcFailed = true;
this._setLoaded(STREAM_TYPE_WEB_RTC, false);
return;
}
@@ -510,10 +604,15 @@ export class HaCameraStream extends LitElement {
display: block;
}
img {
img,
ha-camera-placeholder {
width: 100%;
}
ha-camera-placeholder {
background-color: var(--ha-color-fill-neutral-normal-resting);
}
ha-web-rtc-player {
width: 100%;
height: 100%;
+6 -1
View File
@@ -139,12 +139,17 @@ 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 = undefined;
this._lastChanging = this._steppedValue(activeValue);
fireEvent(this, `${this._activeSlider}-changing`, {
value: this._lastChanging,
});
}
if (!this._activeSlider) {
if (changedProps.has("value")) {
+9
View File
@@ -73,6 +73,15 @@ export class HaDropdown extends Dropdown {
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/naming-convention
private override async showMenu() {
// Flip away from the safe areas instead of opening into them, where the
// max-height below would squeeze the menu.
const styles = getComputedStyle(this);
// @ts-ignore flipPadding is typed as a number, floating-ui accepts sides
this.popup.flipPadding = {
top: parseFloat(styles.getPropertyValue("--safe-area-inset-top")) || 0,
bottom:
parseFloat(styles.getPropertyValue("--safe-area-inset-bottom")) || 0,
};
// @ts-ignore
await super.showMenu();
const triggerElement = this.getTrigger();
+30 -14
View File
@@ -42,6 +42,8 @@ export class HaMjpegPlayer extends LitElement {
private _drawInterval?: number;
private _copyingFrame = false;
/** The video for picture in picture, undefined when it can't be shown. */
public get videoElement(): HTMLVideoElement | undefined {
return this._canCopy ? this._videoEl : undefined;
@@ -66,12 +68,13 @@ export class HaMjpegPlayer extends LitElement {
}
try {
if (!this._stream) {
this._drawFrame();
// The canvas already has a frame from the copy test
this._copyFrame();
// Captures a frame whenever the canvas is drawn
this._stream = this._canvas!.captureStream();
video.srcObject = this._stream;
this._drawInterval = window.setInterval(
() => this._drawFrame(),
() => this._copyFrame(),
1000 / PICTURE_IN_PICTURE_FRAME_RATE
);
}
@@ -178,32 +181,45 @@ export class HaMjpegPlayer extends LitElement {
/** An image from another origin can't be copied out of a canvas. */
private _testCopy(): boolean {
const image = this._imageEl!;
try {
this._drawFrame();
this._canvas?.getContext("2d")?.getImageData(0, 0, 1, 1);
return Boolean(this._canvas);
this._drawFrame(image, image.naturalWidth, image.naturalHeight);
this._canvas!.getContext("2d")?.getImageData(0, 0, 1, 1);
return true;
} catch (_err: unknown) {
return false;
}
}
private _drawFrame() {
// Firefox only draws the first frame of an MJPEG image, a bitmap of it
// has the current one
private async _copyFrame() {
const image = this._imageEl;
if (!image?.naturalWidth) {
if (this._copyingFrame || !image?.naturalWidth) {
return;
}
this._copyingFrame = true;
try {
const bitmap = await createImageBitmap(image);
this._drawFrame(bitmap, bitmap.width, bitmap.height);
bitmap.close();
} catch (_err: unknown) {
// The stream is between frames or restarting, the next copy tries again
} finally {
this._copyingFrame = false;
}
}
private _drawFrame(frame: CanvasImageSource, width: number, height: number) {
if (!this._canvas) {
this._canvas = document.createElement("canvas");
}
const canvas = this._canvas;
if (
canvas.width !== image.naturalWidth ||
canvas.height !== image.naturalHeight
) {
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
canvas.getContext("2d")?.drawImage(image, 0, 0);
canvas.getContext("2d")?.drawImage(frame, 0, 0);
}
private _stopVideo = () => {
+47 -15
View File
@@ -23,6 +23,7 @@ import {
getPanelIcon,
getPanelIconPath,
getPanelTitle,
getSelectedPanelUrlPath,
} from "../data/panel";
import type { PersistentNotification } from "../data/persistent_notification";
import { subscribeNotifications } from "../data/persistent_notification";
@@ -231,12 +232,36 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
return nothing;
}
const selectedPanel = this.hass.panelUrl;
// prettier-ignore
return html`
${this._renderHeader()}
${this._renderAllPanels(selectedPanel)}`;
${this._renderAllPanels()}`;
}
private _computeSidebarPanels(): [PanelInfo[], PanelInfo[]] | undefined {
if (!this._panelOrder || !this._hiddenPanels) {
return undefined;
}
return computePanels(
this.hass.panels,
getDefaultPanelUrlPath(this.hass),
this._panelOrder,
this._hiddenPanels,
this.hass.locale
);
}
private _computeSelectedPanel(
sidebarPanels: [PanelInfo[], PanelInfo[]] | undefined,
route: Route | undefined
): string {
if (!route) {
return this.hass.panelUrl;
}
const urlPaths = (sidebarPanels ?? [[], []])
.flat()
.map((panel) => panel.url_path);
return getSelectedPanelUrlPath(urlPaths, route.path);
}
protected shouldUpdate(changedProps: PropertyValues): boolean {
@@ -254,7 +279,20 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
) {
return true;
}
if (!this.hass || !changedProps.has("hass")) {
if (!this.hass) {
return false;
}
if (changedProps.has("route")) {
const sidebarPanels = this._computeSidebarPanels();
const oldRoute = changedProps.get("route") as Route | undefined;
if (
this._computeSelectedPanel(sidebarPanels, oldRoute) !==
this._computeSelectedPanel(sidebarPanels, this.route)
) {
return true;
}
}
if (!changedProps.has("hass")) {
return false;
}
const oldHass = changedProps.get("hass") as HomeAssistant;
@@ -355,7 +393,9 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
</div>`;
}
private _renderAllPanels(selectedPanel: string) {
private _renderAllPanels() {
const sidebarPanels = this._computeSidebarPanels();
const selectedPanel = this._computeSelectedPanel(sidebarPanels, this.route);
const renderList = (content, cls: string, scrollable: boolean) =>
html`<ha-list-nav
class=${classMap({
@@ -365,7 +405,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
>${content}</ha-list-nav
>`;
if (!this._panelOrder || !this._hiddenPanels) {
if (!sidebarPanels) {
return html`<div class="panels-list">
<div class="wrapper">
${renderList(
@@ -390,15 +430,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
</div>`;
}
const defaultPanel = getDefaultPanelUrlPath(this.hass);
const [beforeSpacer, afterSpacer] = computePanels(
this.hass.panels,
defaultPanel,
this._panelOrder,
this._hiddenPanels,
this.hass.locale
);
const [beforeSpacer, afterSpacer] = sidebarPanels;
// prettier-ignore
return html`<div class="panels-list">
+1
View File
@@ -200,6 +200,7 @@ class HaEntityMarker extends LitElement {
}
.entity-picture {
background-size: cover;
background-position: center;
height: 100%;
width: 100%;
}
+6
View File
@@ -79,6 +79,8 @@ export const selectCameraStreams = ({
];
};
export type CameraStreamDisconnectReason = "home_assistant" | "stream_failed";
/** What the player tells the user about the connection of its stream. */
export interface CameraStreamStatus {
/** The stream that is shown, undefined until the camera's types are known */
@@ -91,6 +93,10 @@ export interface CameraStreamStatus {
hasAudio: boolean;
/** The app plays the shown stream in its own player, over the page */
inApp?: boolean;
/** The camera is unavailable, no stream is started */
unavailable?: boolean;
/** Home Assistant is disconnected, or the only stream failed */
disconnected?: CameraStreamDisconnectReason;
}
export const computeCameraStreamStatus = (
+15
View File
@@ -196,6 +196,21 @@ export const getPanelIconPath = (panel: PanelInfo): string | undefined => {
export const FIXED_PANELS = [PROFILE_PANEL, "config", NOT_FOUND_PANEL];
// A panel's url_path can span several segments (e.g. "config/logs"), so the
// most specific url_path matching the path wins over its first segment.
export const getSelectedPanelUrlPath = (
urlPaths: string[],
path: string
): string =>
urlPaths.reduce(
(selected, urlPath) =>
urlPath.length > selected.length &&
(path === `/${urlPath}` || path.startsWith(`/${urlPath}/`))
? urlPath
: selected,
path.split("/")[1] ?? ""
);
export interface PanelMutableParams {
title?: string | null;
icon?: string | null;
@@ -28,7 +28,10 @@ import { fetchCloudStatus } from "../../data/cloud";
import { apiContext, configContext } from "../../data/context";
import { haStyleDialog, haStyleDialogFixedTop } from "../../resources/styles";
import { DialogMixin } from "../dialog-mixin";
import type { CameraStreamInfoDialogParams } from "./show-dialog-camera-stream-info";
import type {
CameraStreamInfo,
CameraStreamInfoDialogParams,
} from "./show-dialog-camera-stream-info";
// Ordered from the fastest to the most compatible
const STREAM_TYPES: { type: CameraStreamType; icon: string }[] = [
@@ -53,6 +56,23 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
@state() private _cloudIceServers = false;
@state() private _info?: CameraStreamInfo;
private _unsubscribe?: () => void;
public connectedCallback() {
super.connectedCallback();
this._unsubscribe = this.params?.subscribe((info) => {
this._info = info;
});
}
public disconnectedCallback() {
this._unsubscribe?.();
this._unsubscribe = undefined;
super.disconnectedCallback();
}
protected firstUpdated() {
this._fetchCloudIceServers();
}
@@ -74,10 +94,10 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
}
protected render() {
if (!this.params) {
if (!this._info) {
return nothing;
}
const { status, supportedTypes } = this.params;
const { status, supportedTypes } = this._info;
// Without a video stream, still images are all the camera has
const stillImagesOnly = supportedTypes?.length === 0;
// MJPEG is only the fallback, only worth explaining while it shows
@@ -106,6 +126,22 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
: "ui.dialogs.camera_stream_info.intro"
)}
</p>
${
status.disconnected
? html`<ha-alert alert-type="error">
${this._localize(
`ui.dialogs.camera_stream_info.disconnected.${status.disconnected}`
)}
</ha-alert>`
: nothing
}
${
status.unavailable
? html`<ha-alert alert-type="warning">
${this._localize("ui.dialogs.camera_stream_info.unavailable")}
</ha-alert>`
: nothing
}
${
mjpegInUse && !stillImagesOnly
? html`<ha-alert alert-type="info">
@@ -145,7 +181,7 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
type: CameraStreamType;
icon: string;
}) {
const { status } = this.params!;
const { status } = this._info!;
const current = !status.connecting && status.type === type;
const upgrading = status.upgrading === type;
return html`
@@ -1,12 +1,17 @@
import { fireEvent } from "../../common/dom/fire_event";
import type { CameraStreamStatus, StreamType } from "../../data/camera-streams";
export interface CameraStreamInfoDialogParams {
export interface CameraStreamInfo {
status: CameraStreamStatus;
/** The stream types the camera supports, undefined while unknown */
supportedTypes?: StreamType[];
}
export interface CameraStreamInfoDialogParams {
/** Calls back with the current info right away and on every change */
subscribe: (callback: (info: CameraStreamInfo) => void) => () => void;
}
export const showCameraStreamInfoDialog = (
element: HTMLElement,
params: CameraStreamInfoDialogParams
@@ -324,6 +324,10 @@ class MoreInfoCamera extends LitElement {
ev: HASSDomEvent<HASSDomEvents["stream-type-changed"]>
) {
this._streamType = ev.detail.type;
// A removed WebRTC player can't tell that its microphone stopped
if (ev.detail.type !== STREAM_TYPE_WEB_RTC && !this._useAppMicrophone) {
this._microphoneState = "off";
}
}
private _capabilitiesChanged(
+6
View File
@@ -2,4 +2,10 @@ import "@webcomponents/scoped-custom-element-registry/scoped-custom-element-regi
import "../resources/scoped-registry-ready";
import "../layouts/home-assistant";
// Custom cards and plugins can reach the helpers on any page, not only once a
// dashboard has loaded.
Object.assign(window, {
loadCardHelpers: () => import("../panels/lovelace/custom-card-helpers"),
});
import("../resources/append-ha-style");
-2
View File
@@ -11,7 +11,6 @@ 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";
@@ -188,7 +187,6 @@ 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;
+14 -19
View File
@@ -1,21 +1,9 @@
import { supportsFeatureFromAttributes } from "../../common/entity/supports-feature";
import {
CLIMATE_HVAC_ACTION_TO_MODE,
ClimateEntityFeature,
} from "../../data/climate";
import { 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,
@@ -243,10 +231,13 @@ export class MockClimateEntity extends MockBaseEntity {
return "off";
}
// 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;
// Heat and cool get their action from the temperatures below
if (state === "dry") {
return "drying";
}
if (state === "fan_only") {
return "fan";
}
if (
@@ -276,13 +267,17 @@ 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 (lowTarget != null && lowTarget > current) {
if (state !== "cool" && lowTarget != null && lowTarget > current) {
return "heating";
}
if (highTarget != null && highTarget < current) {
if (state !== "heat" && highTarget != null && highTarget < current) {
return "cooling";
}
return "idle";
}
}
+16
View File
@@ -607,6 +607,22 @@ 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,6 +27,12 @@ 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,
@@ -53,6 +59,24 @@ 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,
@@ -221,6 +245,8 @@ 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 = {};
@@ -664,6 +690,51 @@ 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,8 +514,16 @@ class AddIntegrationDialog extends LitElement {
return [...integrations]
.filter((item) => !brand || item.domain === brand)
.sort(byName)
.flatMap((item) => this._brandRows(item))
.filter((row) => !brand || !row.is_header);
.flatMap((item) =>
this._brandRows(item)
.filter((row) => !row.is_header)
// The brand on the second line, so its entries read as a group
.map((row) =>
brand || !this._isBrand(item)
? row
: { ...row, description: item.name }
)
);
}
// A brand shows its integrations here, not itself, like the website
if (category) {
@@ -1207,17 +1215,11 @@ class AddIntegrationDialog extends LitElement {
})}
>
${
!this._stickyBrand
? nothing
: this._filter
? html`<ha-section-title class="sticky">
${this._stickyBrand}
</ha-section-title>`
: html`<ha-integration-list-title
class="sticky raised"
>
${this._stickyBrand}
</ha-integration-list-title>`
this._stickyBrand
? html`<ha-section-title class="sticky">
${this._stickyBrand}
</ha-section-title>`
: nothing
}
<ha-list-virtualized
.rows=${this._filter ? rows : this._withEndSpace(rows)}
@@ -1771,7 +1773,7 @@ class AddIntegrationDialog extends LitElement {
);
}
// The virtualizer positions rows, so CSS sticky can't hold the brand
// The virtualizer positions rows, so CSS sticky can't hold the section title
@eventOptions({ passive: true })
private _visibilityChanged(ev: HASSDomEvent<HaListVisibilityChangedDetail>) {
const rows = this._getRows();
@@ -1794,11 +1796,7 @@ class AddIntegrationDialog extends LitElement {
return html`<div style="height: var(--ha-space-2)"></div>`;
}
if (integration.is_header) {
return this._filter
? html`<ha-section-title>${integration.name}</ha-section-title>`
: html`<ha-integration-list-title>
${integration.name}
</ha-integration-list-title>`;
return html`<ha-section-title>${integration.name}</ha-section-title>`;
}
return html`
<ha-integration-list-item
@@ -26,6 +26,7 @@ import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import memoizeOne from "memoize-one";
import { navigate } from "../../../common/navigate";
import { formatListWithAnds } from "../../../common/string/format-list";
import { copyToClipboard } from "../../../common/util/copy-clipboard";
import "../../../components/ha-dropdown";
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
@@ -95,6 +96,9 @@ export class HaConfigEntryRow extends LitElement {
@property({ attribute: false }) public data!: ConfigEntryData;
/** The loaded integrations that lose this integration with this entry. */
@property({ attribute: false }) public dependents?: IntegrationManifest[];
@state() private _expanded = true;
@state() private _devicesExpanded = true;
@@ -812,14 +816,33 @@ export class HaConfigEntryRow extends LitElement {
const applicationCredentialsId =
await this._applicationCredentialForRemove(entryId);
const text = this.hass.localize(
"ui.panel.config.integrations.config_entry.delete_confirm_text"
);
const confirmed = await showConfirmationDialog(this, {
title: this.hass.localize(
"ui.panel.config.integrations.config_entry.delete_confirm_title",
{ title: this.data.entry.title }
),
text: this.hass.localize(
"ui.panel.config.integrations.config_entry.delete_confirm_text"
),
text: this.dependents?.length
? html`${text}<br /><br />${this.hass.localize(
"ui.panel.config.integrations.config_entry.delete_confirm_dependents",
{
count: this.dependents.length,
integrations: formatListWithAnds(
this.hass.locale,
this.dependents.map((manifest) =>
domainToName(this.hass.localize, manifest.domain, manifest)
)
),
name: domainToName(
this.hass.localize,
this.data.entry.domain,
this.manifest
),
}
)}`
: text,
confirmText: this.hass!.localize("ui.common.delete"),
dismissText: this.hass!.localize("ui.common.cancel"),
destructive: true,
@@ -21,7 +21,7 @@ import memoizeOne from "memoize-one";
import { ensureArray } from "../../../common/array/ensure-array";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import { QueryParamsController } from "../../../common/controllers/query-params-controller";
import { ContextSubscriptionController } from "../../../common/decorators/consume";
import { consume } from "../../../common/decorators/consume";
import type { HASSDomTargetEvent } from "../../../common/dom/fire_event";
import { computeDeviceNameDisplay } from "../../../common/entity/compute_device_name";
import {
@@ -176,9 +176,9 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
@state() private _manifest?: IntegrationManifest;
/** The manifests of all loaded integrations, to find the dependents. */
@state() private _loadedManifests?: DomainManifestLookup;
private _manifestsConsumer?: ContextSubscriptionController<DomainManifestLookup>;
@consume({ context: manifestsContext, subscribe: true })
@state()
private _loadedManifests?: DomainManifestLookup;
@state() private _extraConfigEntries?: ConfigEntry[];
@@ -432,17 +432,23 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
this.domain
);
const dependents = this._getDependents(
this.domain,
this._loadedManifests,
this.hass.localize,
this.hass.locale.language
);
// Without the dependents, a dependency looks like a YAML integration.
const dependents =
this._manifest && !this._manifest.config_flow
? this._getDependents(
this.domain,
this._loadedManifests,
this.hass.localize,
this.hass.locale.language
)
: [];
const showDependents = normalEntries.length === 0 && dependents.length > 0;
const dependencyOnly =
normalEntries.length === 0 &&
dependents.length > 0 &&
!this._manifest?.config_flow;
// Deleting the last entry in use leaves the dependents without it.
const entriesInUse = configEntries.filter(
(entry) => entry.source !== "ignore" && !entry.disabled_by
);
const lastEntryId =
entriesInUse.length === 1 ? entriesInUse[0].entry_id : undefined;
// Hold back the YAML texts and "Add entry" until the manifest and the
// dependents are known. Entries do not wait, so a failed request cannot
// hide them.
@@ -461,7 +467,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
const showAddEntry =
this._manifest?.integration_type !== "hardware" &&
!showDependents &&
!dependencyOnly &&
!dependentsLoading &&
!setUpInPanel &&
(!this._manifest?.single_config_entry ||
@@ -653,7 +659,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
}
${
normalEntries.length === 0 &&
!showDependents &&
!dependencyOnly &&
!dependentsLoading &&
!setUpInPanel &&
this._manifest &&
@@ -1010,6 +1016,11 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
.diagnosticHandler=${this._diagnosticHandler}
.entities=${this._entities}
.data=${data}
.dependents=${
data.entry.entry_id === lastEntryId
? dependents
: undefined
}
data-entry-id=${data.entry.entry_id}
></ha-config-entry-row>`
)}
@@ -1018,19 +1029,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
: nothing
}
${
showDependents
? html`<div class="section">
<h3 class="section-header">
${this.hass.localize(
"ui.panel.config.integrations.integration_page.used_by"
)}
</h3>
${this._renderDependents(dependents)}
</div>`
: nothing
}
${
showDependents ||
dependencyOnly ||
dependentsLoading ||
(setUpInPanel && normalEntries.length === 0)
? nothing
@@ -1077,6 +1076,11 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
.diagnosticHandler=${this._diagnosticHandler}
.entities=${this._entities}
.data=${data}
.dependents=${
data.entry.entry_id === lastEntryId
? dependents
: undefined
}
data-entry-id=${data.entry.entry_id}
></ha-config-entry-row>`
)}
@@ -1084,26 +1088,23 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
}
</div>`
}
${
dependents.length
? html`<div class="section">
<h3 class="section-header">
${this.hass.localize(
"ui.panel.config.integrations.integration_page.used_by"
)}
</h3>
${this._renderDependents(dependents)}
</div>`
: nothing
}
</div>
</hass-subpage>
`;
}
// Only an integration without a config flow needs the loaded manifests, so
// other integration pages do not make the context fetch them.
private _watchLoadedManifests(): void {
if (this._manifestsConsumer) {
return;
}
this._manifestsConsumer = new ContextSubscriptionController(
this,
manifestsContext,
(manifests) => {
this._loadedManifests = manifests;
}
);
}
private _getDependents = memoizeOne(
(
domain: string,
@@ -1199,9 +1200,6 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
return;
}
this._manifest = await fetchIntegrationManifest(this.hass, this.domain);
if (!this._manifest.config_flow) {
this._watchLoadedManifests();
}
if (
this._manifest.integration_type &&
!["device", "hub", "service"].includes(this._manifest.integration_type)
+90 -63
View File
@@ -11,6 +11,7 @@ import type {
} from "../../../common/dom/fire_event";
import { computeDomain } from "../../../common/entity/compute_domain";
import parseAspectRatio from "../../../common/util/parse-aspect-ratio";
import "../../../components/camera/ha-camera-placeholder";
import "../../../components/ha-camera-stream";
import type { HaCameraStream } from "../../../components/ha-camera-stream";
import "../../../components/ha-spinner";
@@ -135,6 +136,12 @@ export class HuiImage extends LitElement {
if (this._shouldStartCameraUpdates(oldHass)) {
this._startIntersectionObserver();
} else if (
this._cameraBecameAvailable(oldHass) &&
this._imageVisible &&
this.cameraView !== "live"
) {
this._updateCameraImageSrc();
} else if (!this.hass!.connected) {
this._stopUpdateCameraInterval();
this._stopIntersectionObserver();
@@ -264,6 +271,13 @@ export class HuiImage extends LitElement {
// Snapshots load only once the card is on screen; skip the spinner until then.
const showSpinner = !this.cameraImage || this._imageVisible;
const cameraUnavailable = this._cameraUnavailable();
const placeholderHeight = !useRatio
? this._lastImageHeight
? `${this._lastImageHeight}px`
: "100%"
: undefined;
return html`
<div
style=${styleMap({
@@ -288,71 +302,66 @@ export class HuiImage extends LitElement {
})}"
>
${
this.cameraImage && this.cameraView === "live"
? html`
<ha-camera-stream
muted
.stateObj=${cameraObj}
.fitMode=${this.fitMode}
.aspectRatio=${
this._ratio ? this._ratio.w / this._ratio.h : undefined
}
@load=${this._onVideoLoad}
></ha-camera-stream>
`
: imageSrc === undefined
? nothing
: html`
<img
id="image"
src=${this._reconnectImg ? nothing : live(imageSrc)}
alt=${this.entity || ""}
@error=${this._onImageError}
@load=${this._onImageLoad}
style=${styleMap({
display:
useRatio || this._loadState === LoadState.Loaded
? "block"
: "none",
})}
/>
cameraUnavailable
? nothing
: this.cameraImage && this.cameraView === "live"
? html`
<ha-camera-stream
muted
.stateObj=${cameraObj}
.fitMode=${this.fitMode}
.aspectRatio=${
this._ratio ? this._ratio.w / this._ratio.h : undefined
}
@load=${this._onVideoLoad}
></ha-camera-stream>
`
: imageSrc === undefined
? nothing
: html`
<img
id="image"
src=${this._reconnectImg ? nothing : live(imageSrc)}
alt=${this.entity || ""}
@error=${this._onImageError}
@load=${this._onImageLoad}
style=${styleMap({
display:
useRatio || this._loadState === LoadState.Loaded
? "block"
: "none",
})}
/>
`
}
${
this._loadState === LoadState.Error
? html`<div
id="brokenImage"
style=${styleMap({
height: !useRatio
? this._lastImageHeight
? `${this._lastImageHeight}px`
: "100%"
: undefined,
})}
></div>`
: this.cameraView !== "live" &&
(imageSrc === undefined ||
this._loadState === LoadState.Loading)
this.cameraImage &&
(cameraUnavailable || this._loadState === LoadState.Error)
? html`<ha-camera-placeholder
style=${styleMap({ height: placeholderHeight })}
></ha-camera-placeholder>`
: this._loadState === LoadState.Error
? html`<div
class="progress-container"
style=${styleMap({
height: !useRatio
? this._lastImageHeight
? `${this._lastImageHeight}px`
: "100%"
: undefined,
})}
>
${
showSpinner
? html`<ha-spinner
class="render-spinner"
size="small"
></ha-spinner>`
: nothing
}
</div>`
: ""
id="brokenImage"
style=${styleMap({ height: placeholderHeight })}
></div>`
: this.cameraView !== "live" &&
(imageSrc === undefined ||
this._loadState === LoadState.Loading)
? html`<div
class="progress-container"
style=${styleMap({ height: placeholderHeight })}
>
${
showSpinner
? html`<ha-spinner
class="render-spinner"
size="small"
></ha-spinner>`
: nothing
}
</div>`
: ""
}
</div>
`;
@@ -366,6 +375,18 @@ export class HuiImage extends LitElement {
);
}
private _cameraUnavailable(hass = this.hass): boolean {
return Boolean(
this.cameraImage && hass?.states[this.cameraImage]?.state === UNAVAILABLE
);
}
private _cameraBecameAvailable(oldHass?: HomeAssistant): boolean {
return Boolean(
oldHass && this._cameraUnavailable(oldHass) && !this._cameraUnavailable()
);
}
private _startIntersectionObserver(): void {
if (!this._intersectionObserver) {
this._intersectionObserver = new IntersectionObserver(
@@ -434,7 +455,8 @@ export class HuiImage extends LitElement {
}
private async _updateCameraImageSrc(): Promise<void> {
if (!this.hass || !this.cameraImage) {
// Its picture can't load, a placeholder shows instead
if (!this.hass || !this.cameraImage || this._cameraUnavailable()) {
return;
}
@@ -525,7 +547,8 @@ export class HuiImage extends LitElement {
}
.ratio img,
.ratio div {
.ratio div,
.ratio ha-camera-placeholder {
position: absolute;
top: 0;
left: 0;
@@ -537,6 +560,10 @@ export class HuiImage extends LitElement {
visibility: hidden;
}
ha-camera-placeholder {
background-color: var(--ha-color-fill-neutral-normal-resting);
}
#brokenImage {
background: grey url("/static/images/image-broken.svg") center/36px
no-repeat;
@@ -9,6 +9,8 @@ export {
showPromptDialog,
} from "../../dialogs/generic/show-dialog-box";
export { importMoreInfoControl } from "../../dialogs/more-info/state_more_info_control";
export { subscribeVisibility } from "../../common/condition/subscribe-visibility";
export { createBadgeElement } from "./create-element/create-badge-element";
export { createCardElement } from "./create-element/create-card-element";
export { createHeaderFooterElement } from "./create-element/create-header-footer-element";
@@ -1,6 +1,6 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { customElement, property, 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 {
public hass?: HomeAssistant;
@property({ attribute: false }) public hass?: HomeAssistant;
@state() private _config?: ButtonRowConfig;
@@ -3,6 +3,7 @@ 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";
@@ -52,6 +53,8 @@ export class HaStateControlClimateHumidity extends LitElement {
@state() private _targetHumidity?: number;
@state() private _changingHumidity?: number;
private _sizeController = createStateControlCircularSliderController(this);
private _pendingSync = new PendingValueSync();
@@ -61,7 +64,11 @@ 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();
@@ -71,6 +78,9 @@ export class HaStateControlClimateHumidity extends LitElement {
}
private _syncTargetHumidity() {
if (this.stateObj.attributes.humidity !== this._targetHumidity) {
this._changingHumidity = undefined;
}
this._targetHumidity = this.stateObj.attributes.humidity;
}
@@ -96,8 +106,11 @@ export class HaStateControlClimateHumidity extends LitElement {
private _valueChanging(ev: HASSDomEvent<HASSDomEvents["value-changing"]>) {
const { value } = ev.detail;
if (typeof value !== "number" || isNaN(value)) return;
this._targetHumidity = value;
if (typeof value !== "number" || isNaN(value)) {
this._changingHumidity = undefined;
return;
}
this._changingHumidity = value;
}
private _debouncedCallService = debounce(() => this._callService(), 1000);
@@ -212,6 +225,10 @@ 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
@@ -264,7 +281,8 @@ export class HaStateControlClimateHumidity extends LitElement {
>
</ha-control-circular-slider>
<div class="info">
${this._renderLabel()} ${this._renderTarget(targetHumidity)}
${this._renderLabel()}
${this._renderTarget(this._changingHumidity ?? targetHumidity)}
${this._renderCurrentHumidity(
this.stateObj.attributes.current_humidity
)}
@@ -4,6 +4,7 @@ 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";
@@ -81,6 +82,8 @@ 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);
@@ -92,7 +95,11 @@ 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();
@@ -102,11 +109,20 @@ export class HaStateControlClimateTemperature extends LitElement {
}
private _syncTargetTemperature() {
this._targetTemperature = {
const targetTemperature: Partial<Record<Target, number>> = {
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() {
@@ -127,27 +143,31 @@ 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", "");
const target = ev.type.replace("-changed", "") as Target;
this._targetTemperature = {
...this._targetTemperature,
[target]: value,
[target]: this._clampToRange(target, value),
};
this._selectTargetTemperature = target as Target;
this._selectTargetTemperature = target;
this._debouncedCallService.cancel();
this._callService(target);
}
private _valueChanging(ev: HASSDomEvent<HASSDomEvents["value-changing"]>) {
const { value } = ev.detail;
if (typeof value !== "number" || isNaN(value)) return;
if (typeof value !== "number" || isNaN(value)) {
this._changingTemperature = {};
return;
}
const target = ev.type.replace("-changing", "");
this._targetTemperature = {
...this._targetTemperature,
[target]: value,
};
this._changingTemperature = { [target]: value };
this._selectTargetTemperature = target as Target;
}
private get _displayedTemperature() {
return { ...this._targetTemperature, ...this._changingTemperature };
}
private _debouncedCallService = debounce(
(target: Target) => this._callService(target),
1000
@@ -180,21 +200,25 @@ 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]: temp,
[target]: this._clampToRange(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;
@@ -354,7 +378,7 @@ export class HaStateControlClimateTemperature extends LitElement {
}
if (this._supportsTargetTemperature && !this.showCurrentAsPrimary) {
return this._renderTarget(this._targetTemperature.value!, "big");
return this._renderTarget(this._displayedTemperature.value!, "big");
}
if (this._supportsTargetTemperatureRange && !this.showCurrentAsPrimary) {
@@ -374,7 +398,7 @@ export class HaStateControlClimateTemperature extends LitElement {
"target_temp_low"
)}
</span>
${this._renderTarget(this._targetTemperature.low!, "big")}
${this._renderTarget(this._displayedTemperature.low!, "big")}
</button>
<button
@click=${this._handleSelectTemp}
@@ -390,7 +414,7 @@ export class HaStateControlClimateTemperature extends LitElement {
"target_temp_high"
)}
</span>
${this._renderTarget(this._targetTemperature.high!, "big")}
${this._renderTarget(this._displayedTemperature.high!, "big")}
</button>
</div>
`;
@@ -427,7 +451,7 @@ export class HaStateControlClimateTemperature extends LitElement {
return html`
<p class="label secondary">
<ha-svg-icon .path=${mdiThermostat}></ha-svg-icon>
${this._renderTarget(this._targetTemperature.value!, "normal")}
${this._renderTarget(this._displayedTemperature.value!, "normal")}
</p>
`;
}
@@ -450,7 +474,7 @@ export class HaStateControlClimateTemperature extends LitElement {
"target_temp_low"
)}
</span>
${this._renderTarget(this._targetTemperature.low!, "normal", true)}
${this._renderTarget(this._displayedTemperature.low!, "normal", true)}
</button>
<span>·</span>
<button
@@ -467,7 +491,7 @@ export class HaStateControlClimateTemperature extends LitElement {
"target_temp_high"
)}
</span>
${this._renderTarget(this._targetTemperature.high!, "normal", true)}
${this._renderTarget(this._displayedTemperature.high!, "normal", true)}
</button>
</p>
`;
@@ -503,6 +527,10 @@ 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);
@@ -549,7 +577,7 @@ export class HaStateControlClimateTemperature extends LitElement {
.preventInteractionOnScroll=${this.preventInteractionOnScroll}
.inactive=${!active}
.mode=${sliderMode}
.value=${this._targetTemperature.value}
.value=${this._displayedTemperature.value}
.min=${this._min}
.max=${this._max}
.step=${this._step}
@@ -585,8 +613,8 @@ export class HaStateControlClimateTemperature extends LitElement {
.preventInteractionOnScroll=${this.preventInteractionOnScroll}
.inactive=${!active}
dual
.low=${this._targetTemperature.low}
.high=${this._targetTemperature.high}
.low=${this._displayedTemperature.low}
.high=${this._displayedTemperature.high}
.min=${this._min}
.max=${this._max}
.step=${this._step}
@@ -3,6 +3,7 @@ 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";
@@ -57,6 +58,8 @@ export class HaStateControlHumidifierHumidity extends LitElement {
@state() private _targetHumidity?: number;
@state() private _changingHumidity?: number;
private _sizeController = createStateControlCircularSliderController(this);
private _pendingSync = new PendingValueSync();
@@ -66,7 +69,11 @@ 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();
@@ -76,6 +83,9 @@ export class HaStateControlHumidifierHumidity extends LitElement {
}
private _syncTargetHumidity() {
if (this.stateObj.attributes.humidity !== this._targetHumidity) {
this._changingHumidity = undefined;
}
this._targetHumidity = this.stateObj.attributes.humidity;
}
@@ -101,8 +111,11 @@ export class HaStateControlHumidifierHumidity extends LitElement {
private _valueChanging(ev: HASSDomEvent<HASSDomEvents["value-changing"]>) {
const { value } = ev.detail;
if (typeof value !== "number" || isNaN(value)) return;
this._targetHumidity = value;
if (typeof value !== "number" || isNaN(value)) {
this._changingHumidity = undefined;
return;
}
this._changingHumidity = value;
}
private _debouncedCallService = debounce(() => this._callService(), 1000);
@@ -200,7 +213,10 @@ export class HaStateControlHumidifierHumidity extends LitElement {
}
if (this._targetHumidity != null && !this.showCurrentAsPrimary) {
return this._renderTarget(this._targetHumidity!, "big");
return this._renderTarget(
this._changingHumidity ?? this._targetHumidity,
"big"
);
}
if (this.stateObj.state !== UNAVAILABLE) {
@@ -234,7 +250,10 @@ export class HaStateControlHumidifierHumidity extends LitElement {
return html`
<p class="label">
<ha-svg-icon .path=${mdiThermostat}></ha-svg-icon>
${this._renderCurrent(this._targetHumidity, "normal")}
${this._renderCurrent(
this._changingHumidity ?? this._targetHumidity,
"normal"
)}
</p>
`;
}
@@ -299,6 +318,10 @@ 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,6 +3,7 @@ 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";
@@ -60,6 +61,8 @@ export class HaStateControlWaterHeaterTemperature extends LitElement {
@state() private _targetTemperature?: number;
@state() private _changingTemperature?: number;
private _sizeController = createStateControlCircularSliderController(this);
private _pendingSync = new PendingValueSync();
@@ -69,7 +72,11 @@ 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();
@@ -79,6 +86,9 @@ export class HaStateControlWaterHeaterTemperature extends LitElement {
}
private _syncTargetTemperature() {
if (this.stateObj.attributes.temperature !== this._targetTemperature) {
this._changingTemperature = undefined;
}
this._targetTemperature = this.stateObj.attributes.temperature;
}
@@ -107,8 +117,11 @@ export class HaStateControlWaterHeaterTemperature extends LitElement {
private _valueChanging(ev: HASSDomEvent<HASSDomEvents["value-changing"]>) {
const { value } = ev.detail;
if (typeof value !== "number" || isNaN(value)) return;
this._targetTemperature = value;
if (typeof value !== "number" || isNaN(value)) {
this._changingTemperature = undefined;
return;
}
this._changingTemperature = value;
}
private _debouncedCallService = debounce(() => this._callService(), 1000);
@@ -231,6 +244,10 @@ 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
@@ -271,7 +288,9 @@ export class HaStateControlWaterHeaterTemperature extends LitElement {
</ha-control-circular-slider>
<div class="info">
${this._renderLabel()}
${this._renderTargetTemperature(this._targetTemperature)}
${this._renderTargetTemperature(
this._changingTemperature ?? this._targetTemperature
)}
${this._renderCurrentTemperature(
this.stateObj.attributes.current_temperature
)}
+10 -3
View File
@@ -1394,9 +1394,10 @@
"reset_zoom": "Reset zoom",
"zoom_hint": "Use {modifier} + scroll to zoom",
"connecting": "Connecting",
"stream_info": "Streaming with {type}. Show connection details",
"stream_info_connecting": "Connecting to the camera. Show connection details",
"stream_info_upgrading": "Streaming with {type}, connecting with {upgrading} in the background. Show connection details"
"live": "Live",
"unavailable": "[%key:state::default::unavailable%]",
"disconnected": "Disconnected",
"show_details": "Show connection details"
},
"web-rtc-player": {
"not_supported": "WebRTC is not supported in this browser.",
@@ -2854,6 +2855,11 @@
"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})",
@@ -8260,6 +8266,7 @@
"delete": "Delete",
"delete_confirm_title": "Delete {title}?",
"delete_confirm_text": "Its devices and entities will be permanently deleted.",
"delete_confirm_dependents": "{integrations} {count, plural,\n one {depends}\n other {depend}\n} on {name} and may stop working.",
"enable_debug_logging": "Enable debug logging",
"reconfigure": "Reconfigure",
"reload": "Reload",
@@ -0,0 +1,109 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { subscribeVisibility } from "../../../src/common/condition/subscribe-visibility";
import type { VisibilityCondition } from "../../../src/panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../../src/types";
interface CapturedSubscription {
push: (message: { result?: boolean }) => void;
unsub: ReturnType<typeof vi.fn>;
condition: unknown;
}
let subs: CapturedSubscription[];
const tick = () =>
new Promise<void>((resolve) => {
setTimeout(resolve, 10);
});
const createHass = (userId = "user1"): HomeAssistant =>
({
connection: {
subscribeMessage: vi.fn(
(
onChange: CapturedSubscription["push"],
msg: { condition: unknown }
) => {
const unsub = vi.fn();
subs.push({ push: onChange, unsub, condition: msg.condition });
return Promise.resolve(unsub);
}
),
},
states: {},
user: { id: userId },
locale: { time_zone: "local" },
config: { time_zone: "America/New_York" },
}) as unknown as HomeAssistant;
describe("subscribeVisibility", () => {
beforeEach(() => {
subs = [];
});
it("checks client conditions again with each hass passed to update", async () => {
const onChange = vi.fn();
const conditions: VisibilityCondition[] = [
{ condition: "user", users: ["user1"] },
];
const subscription = subscribeVisibility(
createHass("user1"),
conditions,
onChange
);
await tick();
expect(onChange).toHaveBeenLastCalledWith("visible", undefined);
subscription.update(createHass("user2"));
expect(onChange).toHaveBeenLastCalledWith("hidden", undefined);
});
it("closes core subscriptions and stops reporting after unsubscribe", async () => {
const onChange = vi.fn();
const conditions: VisibilityCondition[] = [
{ condition: "state", entity: "light.kitchen", state: "on" },
];
const subscription = subscribeVisibility(
createHass(),
conditions,
onChange
);
await tick();
expect(subs).toHaveLength(1);
subs[0].push({ result: true });
expect(onChange).toHaveBeenLastCalledWith("visible", undefined);
onChange.mockClear();
subscription.unsubscribe();
await tick();
expect(subs[0].unsub).toHaveBeenCalled();
expect(onChange).not.toHaveBeenCalled();
});
it("sends the context entity to core for conditions without one", async () => {
const conditions: VisibilityCondition[] = [
{ condition: "state", state: "on" },
];
subscribeVisibility(createHass(), conditions, vi.fn(), {
entity_id: "light.kitchen",
});
await tick();
expect(subs).toHaveLength(1);
expect(subs[0].condition).toEqual({
condition: "state",
entity_id: "light.kitchen",
state: "on",
});
});
});
+44 -1
View File
@@ -1,5 +1,8 @@
import { describe, expect, it } from "vitest";
import { getConfigSubpageTitle } from "../../src/data/panel";
import {
getConfigSubpageTitle,
getSelectedPanelUrlPath,
} from "../../src/data/panel";
import type { PageNavigation } from "../../src/layouts/hass-tabs-subpage";
import type { HomeAssistant } from "../../src/types";
@@ -83,3 +86,43 @@ describe("getConfigSubpageTitle", () => {
).toBeUndefined();
});
});
describe("getSelectedPanelUrlPath", () => {
const urlPaths = ["lovelace", "history", "config/logs", "config/logs/raw"];
it("falls back to the first path segment", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/config/automation")).toBe(
"config"
);
expect(getSelectedPanelUrlPath(urlPaths, "/profile/general")).toBe(
"profile"
);
});
it("selects a panel whose url_path has several segments", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/config/logs")).toBe(
"config/logs"
);
expect(getSelectedPanelUrlPath(urlPaths, "/config/logs/details")).toBe(
"config/logs"
);
});
it("prefers the most specific url_path", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/config/logs/raw")).toBe(
"config/logs/raw"
);
});
it("only matches whole segments", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/config/logsfoo")).toBe("config");
});
it("keeps matching single segment panels on their subpaths", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/lovelace/0")).toBe("lovelace");
});
it("returns an empty url_path for the root path", () => {
expect(getSelectedPanelUrlPath(urlPaths, "/")).toBe("");
});
});
@@ -0,0 +1,63 @@
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);
}
);
});
@@ -0,0 +1,109 @@
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");
});
});