Compare commits

...
Author SHA1 Message Date
Petar Petrov b1cc32d50e Batch entity state updates per websocket frame
Pass batchUpdates to the entity states subscription, so all state
messages of one websocket frame build one states map and one hass
update. core.ts creates the collection, so it passes the option too.
Needs the batchUpdates option from
home-assistant/home-assistant-js-websocket#820.
2026-12-02 12:57:20 +02:00
Petar Petrov 73f8c04e7a Add fixed costs to the energy dashboard (#55955)
* Add fixed costs to the energy dashboard

* Keep fixed cost drafts per type and skip orphaned grid costs

* Show the grid total for fixed costs without grid energy
2026-12-02 12:31:15 +02:00
Lazizbek Ergashev 3fd97a5db0 Keep visibility when an or matches despite an error in another branch (#56336) 2026-12-02 11:01:23 +01:00
Thomas Freudenberg 3cc626b816 Localize date sensor states (#56237)
* Localize date sensor states using profile date format

* Handle invalid date-only values and timezone fallbacks

* Require complete calendar dates before localizing states

* Use consistent formatting for date-only states
2026-12-02 10:54:00 +01:00
Paul Bottein 712e65db1d Hide devices from the energy devices bar chart legend (#56287)
* Hide devices from the energy devices bar chart legend

* Resize the chart and keep legend focus when the axis legend changes

* Show the device tooltip when hovering the axis legend and keep focus for keyboard only
2026-12-02 10:48:19 +01:00
WendelinandClaude Opus 5.5 bfd20530d7 Fix plural forms being ignored in many languages (#56347)
* Keep the native Intl.PluralRules so plural forms work in every language

@formatjs/intl-pluralrules 7.1 and @formatjs/intl-numberformat 10.1 added a
should-polyfill check for formatting numeric strings with
trailingZeroDisplay: "stripToMinimum", which current browsers lack. Every
browser then replaced its native Intl.PluralRules with the polyfill, which
only carries English data, so languages like Russian and Polish lost their
"few" and "many" plural forms. Use our own checks without that feature, as
Home Assistant only passes numbers.

Fixes #56345

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018Kv7eFTWUj93p4Bx4NdNA9

* Trim the Intl polyfill check comments and test

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

* Remove the unused FormatJS should-polyfill paths from tsconfig

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

---------

Co-authored-by: Claude <[email protected]>
2026-12-02 09:11:56 +00:00
Eduardo Moreno be90211d76 Don't cache number formatters built before their locale data loaded (#56342)
* Don't cache number formatters built before their locale data loaded

* Clear the number formatter cache when locale data is added
2026-12-02 10:33:10 +02:00
Tom Mittelstädtand1358 19ffa27a7f Show the pointer cursor on clickable map markers (#56340)
* Show the pointer cursor on clickable map markers

MapLibre leaves markers at the map's grab cursor, so nothing tells a
clickable marker apart from the map behind it. Leaflet gave interactive
markers the pointer through .leaflet-interactive; the MapLibre engine now
does the same for interactive markers and cluster bubbles, and bubble
avatars get it from ha-map. A drag that starts on a marker still shows
grabbing, as on the rest of the map.

* Cover the pointer cursor on map markers in the engine tests

Two new tests check that only markers taking a click get the pointer, that removing a marker clears it, and that a closed bubble points while an open one leaves the cursor to its avatars. The draggable test now checks that a plain marker never gets the move cursor instead of expecting no cursor at all, since plain markers are interactive by default and show the pointer.

* Keep their own cursor on draggable markers while pressed

The grabbing rule for a press on a marker also matched draggable markers, so a zone center showed grabbing instead of move while being dragged, and so did its resize handle. The rule now leaves out .maplibregl-marker-draggable, which MapLibre sets on the markers it drags itself.

* Show the pointer cursor on clickable circle centers

The center of an editable circle only got a cursor when it was moveable, so a clickable center that does not move stayed at the map's grab. Leaflet gives it the pointer as an interactive marker; the MapLibre engine now does the same, and a moveable center keeps the move cursor. A test covers clickable, plain and moveable centers.

---------

Co-authored-by: 1358 <[email protected]>
2026-12-02 10:31:01 +02:00
Jan BouwhuisandClaude Opus 5.5 95eb9500e8 Add hover focus, click radius, legend sync and node position API to network graph (#56309)
* Add hover focus, click radius, legend sync and node position API to network graph

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

* Add label distance to network graph nodes

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

* Send only the node click for a link click near a network graph node

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

* Follow moving nodes in network graph position, first render and tooltip hide

- getNodePosition reads the drawn symbol, so it follows a node that animates
- fire network-graph-rendered once after setup, as the first frame is drawn before the listener is added
- cancel the deferred tooltip hide on the next pointer move, so it does not hide a later tooltip

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

* Drop selectable and label distance, stop network graph rendered event bubbling

The MQTT map no longer needs them: nodeClickRadius makes the small topic
nodes easy to click. The rendered event fires on every frame and is only
listened to on the graph element itself.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-02 10:00:09 +02:00
Eduardo Moreno 49f921bb8c Truncate long names in the picture entity card footer (#56344)
* Truncate long names in the picture entity card footer

* Clip the footer name horizontally so descenders aren't cut off
2026-12-02 08:57:04 +01:00
Petar Petrov a3b730d86a Stop the Home summary cards from filtering all entities on every state change (#56337)
The summary and updates cards now find their entities only when the
entity ids or registries change, and both copies of each card share
one result.
2026-12-02 08:53:22 +01:00
Eduardo Moreno 11e01b83f3 Fix durations losing a minute or second to floating point error (#56343) 2026-12-02 08:59:23 +02:00
289851ca65 Filter the Marketplace on integration connectivity (#56294)
* Filter the Marketplace on integration connectivity

Integrations can set how they connect, like Zigbee, Bluetooth or cloud.
The Marketplace now shows this connectivity:

- A connectivity filter pane in the repository table. It lists only the
  connectivity that the repositories of the tab have, with the names and
  icons that Home Assistant gives. A picked connectivity is kept in the
  URL and in My Home Assistant links, like the integration categories.
- A connectivity column in the table, hidden by default.
- Chips on the repository page that link to the other integrations with
  the same connectivity. The page loads the icons only for a repository
  that has a connectivity.

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

* Show connectivity in the Marketplace demo

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

---------

Co-authored-by: Paulus Schoutsen <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 23:16:17 -05:00
Petar Petrov ae75b0fbb3 Keep unchanged registry objects in the collection stores (#56331)
* Keep unchanged registry objects in the collection stores

After a refetch, hass.devices, hass.entities, hass.areas and hass.floors kept
their unchanged objects while the collection stores held the refetched ones,
so every device and entity entry existed twice. Reuse unchanged items in the
stores on every refetch so both share the same objects.

* Move the registry reuse into connection-mixin

core.ts creates the registry collections, so doing the reuse in their
fetch pulled deepEqual and Set polyfills into the core entry and broke
its size budget. connection-mixin now puts the unchanged previous items
back into the store's list before it builds hass.
2026-12-01 20:56:55 +01:00
Petar Petrov f821581318 Drop hass from the location selector (#56325)
* Drop hass from the location selector

Read localize, locale and config from contexts and pass the language to searchPlaces.

* Show a spinner until the location selector has the core config

The map has no marker and ignores clicks without it.
2026-12-01 20:19:31 +01:00
Petar Petrov d2ed5c57de Drop hass from ha-media-item-picker and ha-selector-media (#56326)
Read localize and the media player's browse support from contexts.
2026-12-01 20:18:00 +01:00
Petar Petrov 0c343898e6 Clear the lazy context value when its subscription ends (#56332)
* Clear the lazy context value when its subscription ends

The provider kept the last value, such as the full entity registry, after
the idle teardown. Clear it, as the comment there already described.

* Test that the lazy context value is cleared after the idle teardown
2026-12-01 19:58:12 +01:00
Petar Petrov 7a8696c237 Keep only callWS in the brands token refresh (#56330)
The 30 minute refresh interval kept the hass object it was given. After a
reconnect that was an old copy of every state. Pass callWS instead.
2026-12-01 19:56:55 +01:00
Petar Petrov f1cd21de5d Fix category picker reconnect and pass separate values to alarm helper (#56328)
Clear the category picker's list on disconnect so a reconnect with a new scope shows a loading state instead of the old scope's categories, and give setProtectedAlarmControlPanelMode separate callService, callWS and localize arguments.
2026-12-01 19:56:01 +01:00
Petar Petrov 570a781d60 Pass separate values to panel title helpers (#56327)
getPanelTitle and getPanelTitleFromUrlPath take localize and panels instead of a Pick of HomeAssistant.
2026-12-01 19:53:11 +01:00
Petar Petrov db9e222753 Stop entity rows from keeping old hass objects (#56335)
* Stop entity rows from keeping old hass objects

Rows only re-render when their own entity changes, so the hass bound to
hui-generic-entity-row kept the states map from that render alive. Rows
now pass stateObj, and the generic row and the entities header toggle
read the rest from contexts.

* Handle card actions in gallery demos

Entity rows now fire hass-action, which the standalone gallery demos did not handle, so row taps did nothing there.
2026-12-01 18:49:09 +01:00
renovate[bot] dd29acff7c Update dependency cally to v0.10.1 (#56338)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 19:08:34 +02:00
ljlongwingandClaude Opus 5.5 db8a8b5b41 Push the other setpoint when a temperature range target passes it (#56289)
* Push the other setpoint when a temperature range target passes it

Dragging or stepping the low target of a climate range up to the high
target stopped it there, and the same for high going down. Push the
other target along instead, as thermostats such as Nest do, so the
range can be moved in one gesture. The integration still decides the
minimum gap between the two.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LqKnSDvGqjpf7rg1pJrRJF

* Restore pushed handle on drag back and clamp to min/max

When dragging one handle of the dual circular slider past the other and
back in the same gesture, the pushed handle now returns to where it was
before the push started, so the handles match the displayed and
submitted targets. The dial's target temperature is clamped to the
entity's min/max again before the push is applied, since the slider can
round past the maximum.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LqKnSDvgqjpf7rg1pJrRJF

* Keep stepped slider values within min/max and update gallery

Rounding to the step happens after the value is bounded, so a max that
isn't a multiple of the step (max 35, step 2) left 36 as the slider's
internal value, making the next keyboard step start from 36. Clamp the
stepped value to min/max as well.

The circular slider gallery page now pushes the other handle the same
way, so its stored range stays in order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LqKnSDvgqjpf7rg1pJrRJF

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 17:32:15 +01:00
WendelinandClaude Opus 5.5 4fbaf8c0a8 Group discovered devices by integration in the add dialog (#56315)
* Group discovered devices by integration in the add dialog

An integration with more than one discovered device now shows one row
with a count, which opens a page with all its discovered devices.
Discovered flows also show the integration's name instead of its domain
when it has no translated title.

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

* Use nextRender to focus after the discovered group changes

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

* Remove an unneeded comment

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

* Remove the count badge from discovered groups

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 16:29:25 +01:00
Nacho García e8d660029d Add directions to the more info menu for entities with a location (#55858)
Entities with latitude and longitude attributes get a Directions item in
the more info menu. It opens the same platform navigation URL as the map
overview button.
2026-12-01 15:48:21 +01:00
Paul Bottein 67598310a6 Add a disabled state to the dashboard conditions editor (#56317) 2026-12-01 14:33:29 +00:00
Aidan Timson e6f71722b0 Add a ui_condition selector (#56285)
* Add a visibility conditions selector

* Load the dashboard translations in the visibility conditions selector

* Rename the selector to ui_condition and respect disabled
2026-12-01 14:33:29 +00:00
benep f22a17046c Add a gas devices detail graph card (#56292)
* Show gas devices in the devices detail graph

* Make the gas devices detail graph its own card type

* Use the unit-aware total in the devices detail graph tooltip

* Give the devices detail graph its own total_consumed key
2026-12-01 13:20:31 +00:00
renovate[bot]andAidan Timson 12cfde2aef Update dependency leaflet.markercluster to v2 (#56236)
* Update dependency leaflet.markercluster to v2

* Create marker clusters with the markercluster v2 class

* Fall back when getAnimations is missing on old browsers

* Turn off cluster animations without a native getAnimations

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Aidan Timson <[email protected]>
2026-12-01 14:18:21 +01:00
David Kennedy 1285f9c908 Mark "Add user" dialog fields for password managers (#56180) 2026-12-01 12:42:29 +00:00
renovate[bot]andAidan Timson cc650ec6ba Update dependency tar to v8 (#56303)
* Update dependency tar to v8

* Extract nightly translations with the tar v8 promise API

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Aidan Timson <[email protected]>
2026-12-01 12:41:50 +01:00
WendelinandClaude Opus 5.5 1a755e7f53 Make read-only code editors reachable with the keyboard (#56311)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 12:06:19 +01:00
Sergio Conde Gómez 7715ab71fd Flatten the map globe earlier to hide gaps in unbuffered ocean tiles (#56298)
* Flatten the map globe earlier to hide gaps in unbuffered ocean tiles

The ocean polygons in the OpenStreetMap vector tiles have no buffer, so
on a globe the neighbouring tiles can leave hairline gaps along their
borders. Flatten the globe into mercator between zoom 5 and 6, as
Mapbox does, instead of at MapLibre's default of zoom 12. Styles that
are not a globe are left as they are.

* Clarify the comment on the early globe flattening
2026-12-01 11:43:39 +01:00
renovate[bot] 5303f30323 Update dependency @rspack/dev-server to v2.2.3 (#56307)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 10:20:52 +00:00
renovate[bot] 35124e73cf Update dependency lint-staged to v17.6.3 (#56308)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 10:20:44 +00:00
Paul Bottein 7ded8288a2 Add capabilities to the entity selector filter (#56305)
* Add capabilities to the entity selector filter

* Test the capabilities entity filter
2026-12-01 11:03:06 +01:00
WendelinandClaude Opus 5.5 583900211b Keep the camera stream and zoom when going full screen (#56293)
* Keep the camera zoom when entering or leaving full screen

The player refits the zoom whenever its size changes, so it keeps the part
of the picture in the middle instead of resetting it.

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

* Keep the camera stream when entering full screen in the companion apps

The Android app hides the page for a moment while it enters full screen.
The WebRTC and HLS players stop the stream right away when the page gets
hidden in the companion apps, so entering full screen restarted it, which
can take a while or stall over remote connections, and the paused video
showed the play button.

Entering full screen with the player's button now lets the first hidden
page within a second through with a short delayed clean up, and the player
plays on if the app paused the video. Leaving full screen, locking the
phone or leaving the app still stop the streams right away.

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

* Resume the camera only once after entering full screen

So a pause in the iPhone's own full screen controls stays paused.

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

* Test the full screen entering window

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 11:43:48 +02:00
WendelinandClaude Opus 5.5 80451833b0 Always hide the camera player controls after a few seconds (#56291)
* Always hide the camera player controls after a few seconds

Hover only keeps the controls after mouse input, as a tapped button stays
hovered on touch screens. Focus only keeps them after keyboard input, as
focus moved by a script can look like keyboard focus. The hide timer also
starts again when the player is added back to the page.

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

* Capture the camera player's input listeners

The options on a listener object are ignored by addEventListener, so the
listeners didn't capture and missed key presses stopped by dialogs.

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

* Keep the camera player controls for keyboard focus on mouse moves

Moving the mouse made the player forget the keyboard input, so a control
focused with the keyboard could hide. A click still changes it.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 11:43:27 +02:00
WendelinandClaude Opus 5.5 7350465df1 Show the blueprint code in its own dialog on import (#56304)
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 11:43:24 +02:00
Nacho García 304020eb5b Add search to select selector dropdowns with many options (#55860)
* Add search to select selector dropdowns with many options

* Keep empty-value lists on the plain dropdown, ignore unchanged picks, test only the order helper

* Give the picker text IDs so numeric options keep their label and 0 can be picked

* Rank search matches by score, let the empty option be picked, trim comments

* Map picker IDs only in the searchable dropdown, without a colliding placeholder

Every option value gets an "option:" prefix as its picker ID, so the empty
value is selectable and no value can share another value's ID. The multiple
and custom_value pickers are back to their dev behaviour. A pick is looked up
in the current options, so an option removed or disabled while the list is
open is ignored.
2026-12-01 10:37:14 +01:00
WendelinandClaude Opus 5.5 57d73d236f Widen the dashboard editors in YAML mode (#56273)
* Widen the dashboard editors in YAML mode

Switching to the code editor now makes the card, badge, section and
view editors as wide as the screen allows, animated like the enlarge
button. The card and badge editors enlarge as if the button was
pressed, so Shrink undoes it, and switching back restores the width
from before. On desktop the code editor is also at least 500px high,
so a short config no longer gives a wide but flat dialog.

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

* Cap the view editor's code editor to the dialog height

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 09:55:01 +02:00
Rodrigo Roque 336259f6d2 Keep the weather temperature unit inside the card and more info dialog (#56146) 2026-12-01 07:24:45 +00:00
Lazizbek Ergashev 1882e154fe Don't report a dropped connection as a failed update (#56300) 2026-12-01 08:42:01 +02:00
renovate[bot] baa067caf0 Update pnpm to v12.24.0 (#56302)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 06:22:14 +00:00
renovate[bot] 07b5d9e98c Update babel monorepo to v8.1.4 (#56301)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 06:21:50 +00:00
Felipe Santos f2b2c92bdd Keep the whole dependents warning inside its plural (#56295) 2026-11-30 19:50:04 +01:00
renovate[bot] 33ef19dac1 Update dependency eslint to v10.16.0 (#56297)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-30 20:35:43 +02:00
Bram KragtenandClaude Opus 5.5 1e797c345c Fix the remote access card title and the webhooks help link (#56290)
Fix remote access card title and webhooks help link

The remote access card used "Remote connection" while its page, the
overview row and onboarding all say "Remote access". Use the page title
for the card and its switch, and drop the unused string.

The webhooks "Learn more" link pointed to nabucasa.com/config/webhooks
without a trailing slash, which returns a 404. Only the form with the
slash redirects to the support article, like the other Nabu Casa links.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 18:46:11 +01:00
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
Paul Bottein a2dd10adee Fill the mobile more info with the camera picture (#56199)
* Fill the mobile more info with the camera picture

* Use the dialog's own mode for the camera fill
2026-11-30 13:18:04 +01:00
Aidan Timson e3adc4adb6 Give the large date card a bigger default size (#56267) 2026-11-30 12:27:58 +01:00
3defae4364 Show wake word names in the voice setup wizard (#56035)
* Show wake word names in the voice setup wizard

The migration to ha-list-item-button left the wake word phrase in the
default slot, which ha-row-item does not render, so the "Change wake
word" step showed empty rows. Put the phrase in the headline slot.

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

* Remove wake word step test

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Paul Bottein <[email protected]>
2026-11-30 11:20:06 +00:00
262763a10e Align the database usage table with other tables on mobile (#56177)
* Align the database usage table with other tables on mobile

Show the table full width in the card, replace the column headers with a
"Sort by" chip on narrow screens, and show the sorted column's value next
to each entity there.

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

* Mock ha-assist-chip in storage section test

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Aidan Timson <[email protected]>
2026-11-30 12:23:55 +02:00
renovate[bot]andPetar Petrov db9a56cd4b Update dependency barcode-detector to v3.2.5 (#56210)
* Update dependency barcode-detector to v3.2.5

* Remove type-fest license override

zxing-wasm 3.1.8 no longer depends on type-fest, so no production
dependency ships it and the pinned override fails the build.

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Petar Petrov <[email protected]>
2026-11-30 11:09:54 +01:00
WendelinandClaude Opus 5.5 dc874ffdb5 Size the section editor to its preview (#56263)
* Size the section editor to its preview

Clicking the title of the section editor made it fill the screen, but
nothing showed that this was possible. On desktop the dialog now takes
the width the preview needs next to the editor: wider for a section
spanning several columns in the desktop preview, narrower in the mobile
preview. The width animates when switching the preview or changing the
section width.

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

* Treat a non-numeric section width as one column

A column span that isn't a whole number of at least one, like text in
YAML mode, made the desktop preview's dialog width invalid.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 10:04:33 +00:00
Paulus Schoutsen ef6a1222b2 Open restart confirmation directly after Marketplace integration updates (#56212)
* Open restart confirmation directly from Marketplace

* Call restart confirmation directly from Marketplace
2026-11-30 09:54:48 +01:00
renovate[bot]andPetar Petrov a25a643a31 Update dependency @vvo/tzdb to v6.208.0 (#56261)
* Update dependency @vvo/tzdb to v6.208.0

* Exclude @vvo/tzdb 6.208.0 from pnpm trust policy

6.208.0 lacks the trusted-publisher record that 6.205.0-6.207.0 carry,
but its provenance still points to vvo/tzdb's release workflow on main.

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Petar Petrov <[email protected]>
2026-11-30 09:33:10 +01:00
d7fbb1efac Use Marketplace icons for app install and uninstall (#56231)
The app info page now uses the same icons as the Marketplace:
mdiDownload for install and mdiDelete for uninstall. The previous
install icon filled its whole box and looked too large on the button.

Co-authored-by: Paulus Schoutsen <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 09:32:31 +01:00
Petar Petrov 4d643b7133 Open more-info from energy meter suggestion names (#56226)
* Open more-info from energy meter suggestion names

* Type the more-info handler's current target
2026-11-30 09:29:13 +01:00
Eduardo Moreno c196356d05 Fix thermostat and humidifier dial size when the entity appears after load (#56260)
In a sections view the grid sizes the card, so the host doesn't resize
when the entity appears and the warning is replaced by the control. The
ResizeController observed only the host, so its value stayed undefined
and the control got no max-width. Observe the .container element instead.
2026-11-30 09:44:25 +02:00
Jonathan DilksandClaude Opus 5.5 53d9395b44 Fix pause button size in narrow media control card (#56256)
A missing comma in the narrow-layout selector meant the pause and stop
buttons never got the larger play-button size, so the card changed
height when switching between play and pause.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-30 09:16:38 +02:00
darkrain-nl dc031d0566 Keep the startup progress in view while the list scrolls (#56213) 2026-11-30 09:03:18 +02:00
renovate[bot] 893daa8333 Update github/codeql-action action to v4.39.4 (#56258)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-30 08:31:41 +02:00
renovate[bot] bbc67bb9d6 Update actions/dependency-review-action action to v5.0.1 (#56257)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-30 08:31:30 +02:00
renovate[bot] 48b56c4653 Update dependency @codemirror/view to v6.44.2 (#56255)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-30 06:08:52 +00:00
renovate[bot] 9dd88a24ce Update dependency tar to v7.5.24 (#56253)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-29 20:49:13 +02:00
renovate[bot] 963711b8fd Update dependency cally to v0.10.0 (#56251)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-29 18:10:16 +00:00
renovate[bot] 55b43df5b5 Update dependency vite to v8.4.0 (#56250)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-29 17:25:02 +02:00
renovate[bot] 0481cfdde3 Update dependency @rslib/core to v1.1.0 (#56248)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-29 14:27:47 +02:00
renovate[bot] 2ce8646318 Update dependency @codemirror/view to v6.44.1 (#56247)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-29 11:02:38 +00:00
Lazizbek Ergashev 459a48b51f Keep picture glance icons visible when tap action is none (#56239) 2026-11-29 08:39:40 +02:00
renovate[bot] c148beafd3 Update dependency @versatiles/style to v9.1.3 (#56241)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-29 08:34:46 +02:00
renovate[bot] 696c3fb093 Update dependency @vvo/tzdb to v6.207.0 (#56242)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-29 08:34:36 +02:00
Paulus Schoutsen 12008d3a06 Distinguish Marketplace dialog alert icons (#56235)
Use icons specific to the required Home Assistant update, built-in integration replacement, and GitHub connection. These notices can appear alongside another alert with the same severity.
2026-11-28 20:33:48 +02:00
Paulus Schoutsen a2179425e0 Remove duplicate Marketplace repository icons (#56230)
* Remove duplicate Marketplace restart icon

The status already shows the restart icon beside its text. Use the button label alone to identify the action.

* Remove other repeated Marketplace repository icons

Use text-only labels for Install, Update, and the Community links. A package icon denotes an available repository and a separate download-count icon distinguishes the metric from the Install action in repository menus.
2026-11-28 20:32:44 +02:00
Lazizbek Ergashev 261debd0d9 Translate the voice satellite setup dialog title (#56233) 2026-11-28 20:31:10 +02:00
renovate[bot] 9a7d6c2892 Update dependency @types/node to v24.19.4 (#56223)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-28 17:38:22 +02:00
Norbert Rittel 90d9e3e87a Clarify configuration warning when recreating entity IDs (#56221)
Clarify configuration warning when recreating Entity IDs
2026-11-28 17:30:57 +02:00
renovate[bot] 1490f8ff12 Update dependency @lezer/common to v1.5.7 (#56220)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-28 17:28:05 +02:00
renovate[bot] 2cb6974ab7 Update dependency @types/leaflet to v1.9.23 (#56222)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-28 17:27:25 +02:00
renovate[bot] 53abe40f72 Update vitest monorepo to v5.1.2 (#56228)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-28 17:25:31 +02:00
renovate[bot] 0a63f12c50 Update dependency @html-eslint/eslint-plugin to v0.69.0 (#56229)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-28 17:24:22 +02:00
renovate[bot] 8f0a6539ac Update CodeMirror (#56219)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-28 15:53:06 +02:00
darkrain-nl 31678bba2d Keep the startup details dialog at a fixed height (#56209) 2026-11-27 19:46:01 +01:00
Lazizbek Ergashev 3a9f461e46 Show Home Assistant Link as the title of the signed out Link page (#56205) 2026-11-27 14:37:26 +02:00
renovate[bot] 6198a100f0 Update dependency @rspack/core to v2.3.4 (#56201)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-27 14:22:51 +02:00
Petar Petrov 6517d24017 Show the device tooltip when hovering a name in the energy devices chart (#56200) 2026-11-27 11:08:59 +01:00
Petar Petrov 1343ac5bc2 Add a Dismiss all button to energy meter suggestions (#56198) 2026-11-27 10:38:12 +01:00
github-actions[bot]andpiitaya 133dd06b07 Update sensor entity constants (#56195)
Co-authored-by: piitaya <[email protected]>
2026-11-27 08:56:20 +02:00
Lazizbek Ergashev bbc4d57fe8 Only add the entity name to energy devices when it tells them apart (#56192)
* Only add the entity name to energy devices when it tells them apart

* Keep entity names for same-named devices with several meters

* Keep entity names when a custom name shares the device label
2026-11-27 08:40:36 +02:00
Jan-Philipp BeneckeandCopilot Autofix powered by AI 0d5588ae56 Use ha-control-select-menu for the run picker on the assist debug page (#56190)
* Use ha-control-select-menu for the run picker on the assist debug page

* Update min-width calculation for toolbar select menu

Co-authored-by: Copilot Autofix powered by AI <[email protected]>

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-11-27 08:35:21 +02:00
renovate[bot] 67d858b828 Update dependency marked to v18.3.0 (#56194)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-27 08:32:20 +02:00
renovate[bot] 95e00f1e36 Update dependency @versatiles/style to v9.1.2 (#56193)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-27 08:32:12 +02:00
WendelinandClaude Opus 5.5 01f9c5eb5b Add a button to enlarge the card and badge editors (#56186)
Replace the hidden title click with a visible button next to Help,
shown on desktop only. The width animates after a click and is not
animated when the code editor switches to full screen.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 20:31:41 +02:00
renovate[bot] 40a28525fb Update dependency typescript-eslint to v8.74.0 (#56187)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-26 20:25:40 +02:00
f80deb0240 Timer progress bar tile card feature (#55994)
* Timer progress bar tile card feature

* Fix Copilot issues

Co-authored-by: Copilot Autofix powered by AI <[email protected]>

* Calculate remaining time only once

* Fix issues

* Switch willUpdate to update

* Update src/panels/lovelace/card-features/hui-timer-progress-card-feature.ts

Co-authored-by: Petar Petrov <[email protected]>

* Fix reduced motion

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-authored-by: Petar Petrov <[email protected]>
2026-11-26 19:59:29 +02:00
WendelinandClaude Opus 5.5 68313876d3 Only offer the tab's categories in the Marketplace filter (#56183)
The integration category filter offered every category on every tab, so
on the installed tab a category nothing installed is in emptied the
table. It now lists the categories of the tab's repositories, and a
category picked on another tab that this one doesn't list is left out
here but kept for that tab, like statuses.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 16:54:07 +01:00
Paul Bottein c3db90ae22 Swipe to open or close the tilt of tilt-only covers (#56182) 2026-11-26 16:52:38 +01:00
WendelinandClaude Opus 5.5 95e0988b93 Load Marketplace category icons only when they are shown (#56185)
The repository page loaded the integration category icons for every
repository, also for ones without integration categories. Load them once
a shown repository has categories, and only once per page.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 16:08:31 +01:00
WendelinandClaude Opus 5.5 00312420d8 Remove clicking the title to enlarge the more info dialog (#56176)
Clicking the title of the more info dialog made it fill the screen, but
nothing showed that this was possible. For a camera it only added black
bars, since its info view already fits the picture. Cameras also no
longer open at the large width: their info view and the image's size the
dialog from the picture, and their other views are as wide as those of
any other entity. A large width passed by the caller still works.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 15:24:20 +01:00
WendelinandClaude Opus 5.5 f2116b61fc Remove two marketplace tests that only cover helpers (#56184)
Follow-up to #55130 review: the empty integration_category link test only
covered the query param decoder, and the filtersOfTab category test only
covered a spread.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 14:19:49 +00:00
Bram KragtenandClaude Opus 5.5 2e872965f6 Draw the slats of tilt-only covers from their state (#56173)
* Draw the slats of tilt-only covers from their state

A tilt-only cover that only reports open or closed, without a tilt
position, was always drawn with half open slats. When the cover can't
move up or down, its state describes the slats, so draw them at the
closed tilt position when closed and at the open tilt position when
open. Covers that also move up and down keep the neutral slats, as
their state describes the position.

Add tilt-only blinds, open and closed, to the cover more-info gallery.

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

* Draw the slats from the state with the default tilt positions

Core only sends the open and closed tilt positions of covers that can
set their tilt position, so a tilt-only cover drawn from its state
always uses 0 and 100.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 15:19:19 +01:00
Paul Bottein cbf745f38a Fix rows value bubble cut off in the card size editor (#56181) 2026-11-26 15:02:14 +01:00
WendelinandClaude Opus 5.5 fe7cedd04b Make the image more info as wide as its picture fits (#56141)
* Make the image more info as wide as its picture fits

The more info of an image was always 1024px wide. Like the camera, the
dialog now takes the width the picture needs to be as high as there is
room for, between 580px and 1920px, but never wider than the picture
itself, so small images keep the standard width. Images no longer open
at the large width before their picture is loaded. The camera's aspect
ratio event becomes media-size-changed, with an optional natural width,
and the dialog forgets the size whenever the entity changes, also when
going to a related entity or back.

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

* Keep the image size for cached views and leave room for the safe area

A picture that finished loading while the info view was detached by
cache() couldn't send its size, and it doesn't load again when the view
is shown, so more-info-image sends the size again when it's reattached.
The picture's height now also leaves out the safe area, like the
dialog's height limit, and the image info's bottom padding that grows
with it.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 13:39:58 +02:00
Paul Bottein 2e9d8a1788 Fix integration names and toast overlap in startup details (#56147)
* Fix integration names and toast overlap in startup details

* Track startup details opened from the completion toast
2026-11-26 12:24:41 +01:00
Martin Salinas 332d612956 Give the tile icon's action its whole 48px area again (#56150)
* Give the tile icon's action its whole 48px area again

The tile container pads the icon by 6px so it is a 48px target, but the action handler was bound to the 36px circle inside it. A tap on that ring, around the circle or on a badge landed on the icon's host, which had no handler, and the container stopped it before the card's handler. Bind the action handler to the host instead.

* Let taps on the tile icon's badge reach the icon

With the action handler on the host, a tap on a badge in the default slot had the badge as its target, so a double tap across the badge and the rest of the icon fired two taps.

* Show the pointer cursor over the tile icon's whole area
2026-11-26 12:16:58 +01:00
WendelinandClaude Opus 5.5 11ef852384 Fix the Bluetooth adapter count on the dashboard (#56165)
* Fix the Bluetooth adapter count on the dashboard

The dashboard counted every bluetooth config entry that isn't disabled,
including ignored discoveries and entries without an adapter device, so
it could show more adapters than the adapters page lists. Move the
adapters page logic to a shared getBluetoothAdapters() helper and count
its enabled adapters on the dashboard. The count waits for the device
registry to load.

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

* Show skeletons while the Bluetooth adapters load

Don't report zero adapters and an offline network before the config
entries and the device registry have loaded. Add tests for the shared
adapter selection.

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

* Show an error with retry when the Bluetooth config entries fail to load

Otherwise the dashboard would keep showing its loading skeletons.

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

* Keep the Bluetooth adapters link named while it loads

A skeleton in the link made its accessible name only "Loading". Show
"Bluetooth adapters" until the count is known instead.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 11:23:45 +01:00
394d5999b8 Show Home Assistant Link label on WebRTC in camera stream info (#56153)
* Show Home Assistant Link label on WebRTC in camera stream info

The camera stream info dialog labels the WebRTC row with
"Enhanced by Home Assistant Link" when the cloud TURN servers are in
use. The dialog reads cloud/status and uses the same check as core:
logged in, active subscription, and cloud_ice_servers_enabled.

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

* Wrap the Home Assistant Link tag on narrow screens

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

---------

Co-authored-by: Paulus Schoutsen <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-26 11:22:32 +01:00
Petar Petrov 384fdfdbc9 Group intl-messageformat with formatjs packages in Renovate (#56161)
Group intl-messageformat with the formatjs packages in Renovate
2026-11-26 10:14:17 +00:00
Martin Salinas 0cccdc5972 Don't set the max value when a circular slider is removed during a drag (#56163)
Cancel a circular slider drag when the slider is removed from the page
2026-11-26 11:49:09 +02:00
Aidan Timson 771eaa70ff Add a skill for browser checks and pull request screenshots (#56142)
* Add a skill for browser checks and pull request screenshots

* Point the screenshot reminder to the browser checks skill

* Cover light and dark, long text and recorded demos in the browser checks skill

* Check RTL with an RTL profile language in the browser checks skill

* Keep a before capture for every change to an existing screen

* Have agents add pull request screenshots themselves when they can
2026-11-26 11:02:29 +02:00
darkrain-nl aff47efe5e 2026.12 beta - Fix add integration search focus (#56151)
* Focus autofocus elements slotted into an adaptive dialog

* Test focusing autofocus elements slotted into a dialog
2026-11-26 09:50:16 +01:00
Erwin Douna f13470719c Restore dismissed energy meter suggestions (#56156)
* Restore dismissed energy meter suggestions

* Use a toolbar menu for dismissed meter suggestions and fix save races
2026-11-26 08:50:27 +02:00
Martin Salinas 5f769d613c Show the entity's value in number controls after the device puts it back (#56148)
* Show the entity's value in number controls after the device puts it back

The numeric input card feature and the number entity row bound the state straight to the control's value. When the entity came back to the value it had, Lit skipped the unchanged binding and the control kept the requested value. Bind with live() so the control is compared with the entity's value on each render.

* Remove the number row tests

They only check that the template puts the entity's value back on the controls, which is a rendering test. The gallery reproduction in the PR covers the change.
2026-11-26 08:44:12 +02:00
renovate[bot] f214ef8667 Update dependency @versatiles/style to v9.1.1 (#56158)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-26 08:32:28 +02:00
renovate[bot] 528ebe6b27 Update dependency memoize-one to v7 (#56160)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-26 08:32:20 +02:00
Gerd Naschenweng 82e6f1106f Cap the bar width in the statistics graph (#56097) 2026-11-26 08:04:48 +02:00
Martin Salinas f02656da54 Keep the color wheel drawn when only the cold white value is set (#56149)
With cw set and ww undefined, the ww !== null check let undefined through to rgbww2rgb, which returned NaN and made addColorStop throw, leaving the wheel blank. Moving the cold white slider of an RGBWW light that is off or in another color mode did that.
2026-11-26 07:52:12 +02:00
Matthias de BaatandClaude Opus 5.5 25307e427d Show when backup retention is paused for a location (#56088)
Automatic backup retention no longer deletes backups from locations
that are turned off for automatic backups (home-assistant/core#192788).
Show "Retention paused" in the locations list and an info alert on the
location page for those locations.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-25 22:17:03 +01:00
Paul Bottein 207cbcc585 Show the connection error when logged out and the server is offline (#56139)
* Show the connection error when logged out and the server is offline

* Show the connection error when the server responds with a 5xx

* Time out the server check before the login redirect

* Give the server check 10 seconds
2026-11-25 19:44:23 +02:00
289 changed files with 9682 additions and 3186 deletions

No files matched your search

@@ -0,0 +1,43 @@
---
name: ha-frontend-browser-checks
description: Check a Home Assistant frontend change in a browser and show it in a pull request. Use when checking how a change looks or behaves at different screen sizes, in light and dark mode, right to left (RTL) or with long translations, or when taking before and after screenshots or recording a demo of a feature for a pull request.
---
# HA Frontend Browser Checks
Use this skill to check a visible change in a browser and to show it in a pull request. Any browser tool you already have works if it can open a page, set its size, run a script in it, take screenshots and record video. Load `ha-frontend-testing` for the dev servers, and `ha-frontend-loading` for loading states.
Screenshots and recordings help reviewers see what changed, but they don't make a large change easy to review. [Keep pull requests small](https://contributors.home-assistant.io/start/pull-requests/#keep-it-small), and make sure you have reviewed and understood the change and can explain it, as the [AI policy](https://contributors.home-assistant.io/start/ai-policy/) asks.
## Check Real Devices
Check the sizes the change affects rather than one fixed size, such as a phone, a tablet in both orientations, a laptop and a large desktop monitor. Include a small phone. Take each device's viewport in CSS pixels, its pixel ratio and touch support from the device presets your tools have, rather than from memory, and check the page really has that size once it's set.
## Check Light And Dark
When the change can look different in light and dark mode, such as a colour, border, background or image, check it in both. Switch the colour scheme in your browser tool, with the profile's theme following it, or pick light and dark in the profile. A fix for one mode only needs that mode.
## Check Right To Left (RTL)
Check layout, alignment, icons and anything with a direction in RTL. In the app, set your profile language to one written right to left, then set it back: many components take their direction from the language, so setting the page to RTL in your browser tool leaves them left to right. The gallery's RTL toggle checks styling only.
## Check Long Text
When a change adds or changes text, check it in a language with long words or long translations too, so labels, descriptions and buttons don't overflow or wrap badly. When the new string isn't translated yet, try a rough translation to check its length.
## Show It In The Pull Request
- When the change alters something that exists already, capture the same screen on `dev` and on your branch, in the same state, and put them side by side. Only a new screen, with nothing before it, needs just the after.
- Keep the size of every capture fixed, screenshots as well as videos. Set the page size before you capture and don't change it in between, and capture the same area each time, so the subject sits in the same place in before and after. For a card or other part of the page, work out a fixed area around it for each size you test, and use that same area on both branches.
- Say which device, size or mode each capture shows.
- Make the change easy to see: capture the part of the screen it affects rather than a whole page where it's a few pixels.
- Save captures outside the repository, so they can't be committed by accident.
- Keep personal details out: use demo data, such as the demo or the Demo integration, and mask anything else before you capture, such as names, addresses, IP and MAC addresses, hostnames, serial numbers and tokens. Check each capture before you attach it.
Record a video when it shows the change better than a still, such as an animation, a drag, a loading sequence (hold the loading state as "Checking It" in `ha-frontend-loading` shows) or a flow across several screens. Keep each video short and small: GitHub limits upload sizes, and reviewers have to watch it. You can record it yourself with the tools you have; it doesn't need a person.
- Use the recording tools at hand: your browser tool's recorder for a page, or a desktop screen recorder for a window, such as a phone emulator, so the device frame shows.
- Don't resize, zoom or take screenshots while recording, which redraw the page at another size and make the video jump.
- Check the whole recording before you attach it. For a short clip, look at a frame every second or half second, not only the first and last, since the page can jump to another size partway through. Record again if it does. Take stills from the same frames, so they match the video.
- Keep the window drawn on a screen. A hidden or minimised window records only a frame every few seconds.
- Label each video, such as **Before** and **After**, and say what it shows and how you set it up. Say what you didn't record and why.
+1 -1
View File
@@ -20,7 +20,7 @@ When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the body
- Do not omit, reorder, or rewrite template sections.
- Check the appropriate "Type of change" box based on the actual change.
- Do not check checklist items on behalf of the user.
- If the PR includes UI changes, remind the user to add screenshots or a short video.
- If the PR includes UI changes, add screenshots or a short video, taken as `ha-frontend-browser-checks` describes. Only ask the user to add them when you can't take them yourself.
- Explain what the change does for users, not only implementation details.
- Use Markdown.
+8 -8
View File
@@ -18,7 +18,7 @@ workflows:
- 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9'
'.github/workflows/codeql-analysis.yaml':
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
- 'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066'
- 'github/codeql-action@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea'
'.github/workflows/copilot-setup-steps.yml':
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
@@ -29,7 +29,7 @@ workflows:
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
'.github/workflows/dependency-review.yaml':
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
- 'actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294'
- 'actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec'
- 'actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'
'.github/workflows/design_deployment.yaml':
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
@@ -101,9 +101,9 @@ dependencies:
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294':
ref: 'v5.0.0'
commit: 'sha1-a1d282b36b6f3519aa1f3fc636f609c47dddb294'
'actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec':
ref: 'v5.0.1'
commit: 'sha1-bbc44d14a204704ccc493733616cd1e93a0321ec'
owner_id: 44036562
repo_id: 476372928
'actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333':
@@ -151,9 +151,9 @@ dependencies:
commit: 'sha1-89ae32b08ed1a541efecbab17912962a5e38981c'
owner_id: 7513068
repo_id: 113918130
'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066':
ref: 'v4.39.3'
commit: 'sha1-33d7b85da1a04171e211befe2c739303b9a4c066'
'github/codeql-action@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea':
ref: 'v4.39.4'
commit: 'sha1-1bd86f2fdb4b86187fa4059f16f31a3202acc9ea'
owner_id: 9919
repo_id: 259445878
'home-assistant/[email protected]':
+2 -2
View File
@@ -32,12 +32,12 @@ jobs:
persist-credentials: false
- name: Initialize CodeQL
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
uses: github/codeql-action/init@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4.39.4
with:
languages: javascript-typescript
build-mode: none
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
uses: github/codeql-action/analyze@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4.39.4
with:
category: "/language:javascript-typescript"
+1 -1
View File
@@ -27,7 +27,7 @@ jobs:
contents: read # To compare the dependency graph between base and head
steps:
- name: Dependency review
uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
uses: actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec # v5.0.1
with:
license-check: false # Covered by pnpm lint:licenses
fail-on-severity: high
+2 -1
View File
@@ -53,10 +53,11 @@ Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching
- `ha-frontend-ux-readiness`: UI/UX routing that complements frontend review for new user experiences.
- `ha-frontend-gallery`: gallery pages, demos, sidebar structure, content, and verification.
- `ha-frontend-demo`: standalone demo structure, configurations, navigation, shared stubs, and verification.
- `ha-frontend-browser-checks`: checking a change in a browser at real device sizes, in light and dark mode, right to left (RTL) and with long translations, and screenshots and recorded demos for pull requests.
## Pull Requests
When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the PR body. Preserve template sections, check only the appropriate type-of-change boxes, and do not check checklist items on behalf of the user. If the PR includes UI changes, remind the user to add screenshots or a short video.
When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the PR body. Preserve template sections, check only the appropriate type-of-change boxes, and do not check checklist items on behalf of the user. If the PR includes UI changes, add screenshots or a short video, taken as `ha-frontend-browser-checks` describes. Only ask the user to add them when you can't take them yourself.
## AI policy
@@ -198,10 +198,7 @@ async function fetchTranslations(currentArtifact: Artifact | null) {
console.log("Unpacking downloaded translations...");
const zip = await jszip.loadAsync(downloadResponse.data as ArrayBuffer);
await deleteCurrent;
const extractStream = zip.file(/.*/)[0].nodeStream().pipe(extract());
await new Promise((resolve, reject) => {
extractStream.on("close", resolve).on("error", reject);
});
await extract({ input: await zip.file(/.*/)[0].async("uint8array") });
// Record the artifact only after successful extraction, so a failed fetch
// is retried by the next build instead of being considered current.
-4
View File
@@ -69,10 +69,6 @@ async function copyMapPanel(staticDir) {
npmPath("leaflet/dist/leaflet.css"),
staticPath("images/leaflet/")
);
copyFileDir(
npmPath("leaflet.markercluster/dist/MarkerCluster.css"),
staticPath("images/leaflet/")
);
fs.copySync(
npmPath("leaflet/dist/images"),
staticPath("images/leaflet/images/")
+1 -7
View File
@@ -25,13 +25,7 @@ const NOTICE_FILES = [path.join(NODE_MODULES, "echarts/NOTICE")];
// that the new version's license still matches. The build will fail if
// the pinned version is no longer installed.
const LICENSE_OVERRIDES = [
{
// type-fest ships two license files (MIT for code, CC0 for types).
// We use the MIT license since that covers the bundled code.
packageName: "type-fest",
version: "5.10.0",
licenseFile: "license-mit",
},
// No entries currently needed.
];
// Locate the directory of an installed package matching an exact version.
-4
View File
@@ -508,12 +508,8 @@ const createRspackConfig = ({
"@formatjs/intl-locale/should-polyfill.js",
"@formatjs/intl-locale/polyfill-force":
"@formatjs/intl-locale/polyfill-force.js",
"@formatjs/intl-numberformat/should-polyfill":
"@formatjs/intl-numberformat/should-polyfill.js",
"@formatjs/intl-numberformat/polyfill-force":
"@formatjs/intl-numberformat/polyfill-force.js",
"@formatjs/intl-pluralrules/should-polyfill":
"@formatjs/intl-pluralrules/should-polyfill.js",
"@formatjs/intl-pluralrules/polyfill-force":
"@formatjs/intl-pluralrules/polyfill-force.js",
"@formatjs/intl-relativetimeformat/should-polyfill":
+2 -1
View File
@@ -73,7 +73,8 @@ class HcLovelace extends LitElement {
if (index !== undefined) {
const title = getPanelTitleFromUrlPath(
this.hass,
this.hass.localize,
this.hass.panels,
this.urlPath || "lovelace"
);
+2 -1
View File
@@ -355,7 +355,8 @@ export class HcMain extends HassElement {
private _handleNewLovelaceConfig(lovelaceConfig: LovelaceConfig) {
const title = getPanelTitleFromUrlPath(
this.hass!,
this.hass!.localize,
this.hass!.panels,
this._urlPath || "lovelace"
);
castContext.setApplicationState(title || "");
+1
View File
@@ -207,6 +207,7 @@ export class HaEmbedProvider extends LitElement {
}));
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
}));
this._applyColorScheme();
+3
View File
@@ -120,10 +120,12 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
stat_consumption: "sensor.gas_heat_pump",
},
],
fixed_costs: [],
};
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
}));
hass.mockWS("energy/validate", () => ({
@@ -131,6 +133,7 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
device_consumption: prefs.device_consumption.map(() => []),
device_consumption_water: prefs.device_consumption_water.map(() => []),
device_consumption_gas: prefs.device_consumption_gas.map(() => []),
fixed_costs: prefs.fixed_costs.map(() => []),
}));
hass.mockWS(
"energy/fossil_energy_consumption",
+10
View File
@@ -22,6 +22,14 @@ const baseRepository = {
status: "default" as const,
};
// The names of the connectivity of the demo repositories. Home Assistant
// translates them, the mocked hass has no backend translations.
export const marketplaceBackendTranslations = {
"component.homeassistant.integration_connectivity.mqtt.name": "MQTT",
"component.homeassistant.integration_connectivity.network.name":
"Local network",
};
const repositories: RepositoryBase[] = [
{
...baseRepository,
@@ -32,6 +40,7 @@ const repositories: RepositoryBase[] = [
description: "Watch camera streams with low latency through WebRTC.",
authors: ["@AlexxIT"],
domain: "webrtc",
connectivity: ["network"],
config_flow: true,
available_version: "v3.6.1",
downloads: 98000,
@@ -68,6 +77,7 @@ const repositories: RepositoryBase[] = [
description: "Use the cameras and events of a Frigate NVR.",
authors: ["@blakeblackshear", "@dermotduffy", "@NickM-27"],
domain: "frigate",
connectivity: ["network", "mqtt"],
config_flow: true,
available_version: "v5.9.0",
installed: true,
+6 -1
View File
@@ -1,6 +1,7 @@
import type { LocalizeFunc } from "../../../src/common/translations/localize";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
import { connectivityBackendTranslations } from "./connectivity/fixtures";
import { marketplaceBackendTranslations } from "./marketplace";
export const mockTranslations = (
hass: MockHomeAssistant,
@@ -20,7 +21,11 @@ export const mockTranslations = (
// this merges on top of them.
(localizePromise ?? Promise.resolve()).then(() =>
hass.addTranslations(
Object.assign({}, ...Object.values(connectivityBackendTranslations))
Object.assign(
{},
...Object.values(connectivityBackendTranslations),
marketplaceBackendTranslations
)
)
);
};
+12
View File
@@ -1,6 +1,8 @@
import type { PropertyValues } from "lit";
import { html, css, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import "../../../src/components/ha-switch";
import { handleAction } from "../../../src/panels/lovelace/common/handle-action";
import type { HomeAssistant } from "../../../src/types";
import "./demo-card";
import type { DemoCardConfig } from "./demo-card";
@@ -14,6 +16,16 @@ class DemoCards extends LitElement {
@state() private _showConfig = false;
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
// Handles card actions like the app's action mixin
this.addEventListener("hass-action", (ev) => {
ev.stopPropagation();
const node = (ev.composedPath()[0] as HTMLElement | undefined) ?? this;
handleAction(node, this.hass, ev.detail.config, ev.detail.action);
});
}
render() {
return html`
<ha-demo-options>
@@ -22,20 +22,27 @@ export class DemoHaCircularSlider extends LitElement {
@state()
private changingHigh?: number;
// A handle that passes the other one pushes it along, like the slider does
private _lowChanged(ev) {
this.low = ev.detail.value;
this.high = Math.max(this.high, this.low);
}
private _lowChanging(ev) {
this.changingLow = ev.detail.value;
const value = ev.detail.value;
this.changingLow = value;
this.changingHigh = value != null && value > this.high ? value : undefined;
}
private _highChanged(ev) {
this.high = ev.detail.value;
this.low = Math.min(this.low, this.high);
}
private _highChanging(ev) {
this.changingHigh = ev.detail.value;
const value = ev.detail.value;
this.changingHigh = value;
this.changingLow = value != null && value < this.low ? value : undefined;
}
private _currentChanged(ev) {
@@ -462,6 +462,14 @@ const SCHEMAS: {
},
},
},
select_search: {
name: "Select (more than 12 options)",
selector: {
select: {
options: Array.from({ length: 20 }, (_, i) => `Option ${i + 1}`),
},
},
},
select_disabled_list: {
name: "Select disabled option",
selector: {
@@ -632,6 +640,10 @@ const SCHEMAS: {
},
language: { name: "Language", selector: { language: {} } },
navigation: { name: "Navigation", selector: { navigation: {} } },
ui_condition: {
name: "Dashboard conditions",
selector: { ui_condition: {} },
},
numeric_threshold: {
name: "Numeric threshold",
selector: { numeric_threshold: {} },
@@ -22,6 +22,13 @@ const ENTITIES = [
friendly_name: "Bed Light",
},
},
{
entity_id: "light.living_room_ceiling_accent_lights",
state: "on",
attributes: {
friendly_name: "Living Room Ceiling Accent Lights",
},
},
{
entity_id: "person.paulus",
state: "home",
@@ -73,6 +80,14 @@ const CONFIGS = [
entity: "person.paulus",
},
},
{
heading: "Long name",
config: {
type: "picture-entity",
image: "/images/living_room.png",
entity: "light.living_room_ceiling_accent_lights",
},
},
{
heading: "Hidden name",
config: {
+26
View File
@@ -70,6 +70,32 @@ const ENTITIES = [
CoverEntityFeature.CLOSE_TILT,
},
},
{
entity_id: "cover.tilt_only_closed",
state: "closed",
attributes: {
friendly_name: "Tilt-only blind closed",
device_class: "blind",
assumed_state: true,
supported_features:
CoverEntityFeature.OPEN_TILT +
CoverEntityFeature.STOP_TILT +
CoverEntityFeature.CLOSE_TILT,
},
},
{
entity_id: "cover.tilt_only_open",
state: "open",
attributes: {
friendly_name: "Tilt-only blind open",
device_class: "blind",
assumed_state: true,
supported_features:
CoverEntityFeature.OPEN_TILT +
CoverEntityFeature.STOP_TILT +
CoverEntityFeature.CLOSE_TILT,
},
},
{
entity_id: "cover.tilt_slider_half",
state: "on",
+39 -40
View File
@@ -40,31 +40,31 @@
"license": "Apache-2.0",
"type": "module",
"dependencies": {
"@babel/runtime": "8.1.3",
"@babel/runtime": "8.1.4",
"@braintree/sanitize-url": "7.1.2",
"@codemirror/autocomplete": "6.20.4",
"@codemirror/commands": "6.11.1",
"@codemirror/commands": "6.11.2",
"@codemirror/lang-jinja": "6.0.1",
"@codemirror/lang-python": "6.2.1",
"@codemirror/lang-yaml": "6.1.3",
"@codemirror/language": "6.13.1",
"@codemirror/lint": "6.9.8",
"@codemirror/search": "6.7.2",
"@codemirror/search": "6.7.3",
"@codemirror/state": "6.7.6",
"@codemirror/view": "6.43.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.6",
"@lezer/common": "1.5.7",
"@lezer/highlight": "1.2.5",
"@lit-labs/motion": "1.1.0",
"@lit-labs/observers": "2.1.0",
@@ -79,12 +79,12 @@
"@swc/helpers": "0.5.24",
"@tsparticles/engine": "4.5.4",
"@tsparticles/preset-links": "4.5.4",
"@versatiles/style": "9.1.0",
"@versatiles/style": "9.1.3",
"@vibrant/color": "4.0.4",
"@vvo/tzdb": "6.204.0",
"@vvo/tzdb": "6.208.0",
"@webcomponents/scoped-custom-element-registry": "0.0.11",
"barcode-detector": "3.2.4",
"cally": "0.9.2",
"barcode-detector": "3.2.5",
"cally": "0.10.1",
"color-name": "2.1.1",
"comlink": "4.4.2",
"core-js": "3.51.0",
@@ -102,15 +102,15 @@
"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",
"leaflet.markercluster": "2.0.0",
"lit": "3.3.3",
"lit-html": "3.3.3",
"maplibre-gl": "6.19.0",
"marked": "18.2.1",
"memoize-one": "6.0.0",
"maplibre-gl": "6.20.0",
"marked": "18.3.0",
"memoize-one": "7.0.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
"object-hash": "3.0.0",
@@ -136,25 +136,25 @@
},
"devDependencies": {
"@ampproject/remapping": "2.3.0",
"@babel/core": "8.1.3",
"@babel/core": "8.1.4",
"@babel/helper-compilation-targets": "8.0.7",
"@babel/helper-define-polyfill-provider": "1.0.0",
"@babel/plugin-transform-class-properties": "8.0.1",
"@babel/plugin-transform-private-methods": "8.0.1",
"@babel/plugin-transform-runtime": "8.1.2",
"@babel/preset-env": "8.0.7",
"@babel/preset-env": "8.1.4",
"@bundle-stats/plugin-webpack-filter": "4.23.1",
"@eslint/js": "10.0.1",
"@gfx/zopfli": "1.0.15",
"@home-assistant/components": "workspace:*",
"@html-eslint/eslint-plugin": "0.68.0",
"@html-eslint/eslint-plugin": "0.69.0",
"@lokalise/node-api": "17.0.1",
"@octokit/auth-oauth-device": "8.0.5",
"@octokit/rest": "22.0.1",
"@playwright/test": "1.65.1",
"@rsdoctor/rspack-plugin": "1.6.5",
"@rspack/core": "2.3.3",
"@rspack/dev-server": "2.2.2",
"@rspack/core": "2.3.4",
"@rspack/dev-server": "2.2.3",
"@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "7.0.1",
"@types/chromecast-caf-sender": "1.0.11",
@@ -162,23 +162,22 @@
"@types/culori": "4.0.1",
"@types/geojson": "7946.0.16",
"@types/html-minifier-terser": "7.0.2",
"@types/leaflet": "1.9.22",
"@types/leaflet": "1.9.23",
"@types/leaflet.markercluster": "1.5.6",
"@types/lodash.merge": "4.6.9",
"@types/node": "24.19.2",
"@types/node": "24.19.4",
"@types/qrcode": "1.5.6",
"@types/sortablejs": "1.15.9",
"@types/tar": "7.0.87",
"@typescript/native": "npm:[email protected]",
"@vitest/coverage-v8": "5.1.1",
"@vitest/coverage-v8": "5.1.2",
"babel-loader": "10.1.1",
"babel-plugin-polyfill-corejs3": "1.0.0",
"browserslist": "4.29.6",
"browserslist-useragent-regexp": "4.1.4",
"core-js-compat": "3.51.0",
"del": "9.0.1",
"eslint": "10.15.0",
"eslint-config-prettier": "10.1.8",
"eslint": "10.16.0",
"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",
@@ -199,7 +198,7 @@
"jszip": "3.10.2",
"license-checker-rseidelsohn": "5.0.1",
"lightningcss": "1.33.0",
"lint-staged": "17.6.2",
"lint-staged": "17.6.3",
"lit-analyzer": "2.0.3",
"lodash.merge": "4.6.2",
"lodash.template": "4.18.1",
@@ -210,19 +209,19 @@
"rspack-manifest-plugin": "5.2.2",
"serve": "14.2.8",
"sinon": "22.1.0",
"tar": "7.5.23",
"tar": "8.0.2",
"terser-webpack-plugin": "5.6.1",
"ts-lit-plugin": "2.0.2",
"typescript": "6.0.3",
"typescript-eslint": "8.73.0",
"vite": "8.3.8",
"typescript-eslint": "8.74.0",
"vite": "8.4.0",
"vite-tsconfig-paths": "6.1.1",
"vitest": "5.1.1",
"vitest": "5.1.2",
"webpack-stats-plugin": "1.1.3",
"webpackbar": "7.0.0",
"workbox-build": "7.4.1"
},
"packageManager": "[email protected]3.0",
"packageManager": "[email protected]4.0",
"volta": {
"node": "24.22.3"
}
+1 -1
View File
@@ -53,7 +53,7 @@
},
"devDependencies": {
"@custom-elements-manifest/analyzer": "0.11.0",
"@rslib/core": "1.0.7",
"@rslib/core": "1.1.0",
"lit": "3.3.3",
"typescript": "6.0.3"
}
+1304 -1232
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -18,6 +18,8 @@ trustPolicyExclude:
- [email protected]
# Pre-release published without provenance, used by workbox-build
- "@trickfilm400/[email protected]"
# Published without the trusted-publisher record; provenance still from vvo/tzdb release.yml
- "@vvo/[email protected]"
# Dependency build scripts are denied unless listed here with true
allowBuilds:
+2 -2
View File
@@ -126,9 +126,9 @@
"matchPackageNames": ["echarts", "zrender"]
},
{
"description": "Group formatjs monorepo package",
"description": "Group formatjs monorepo packages",
"groupName": "formatjs",
"matchPackageNames": ["@formatjs/**"]
"matchPackageNames": ["@formatjs/**", "intl-messageformat"]
},
{
"description": "Group Playwright package and CI container updates",
@@ -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();
},
};
};
@@ -244,7 +244,7 @@ export class ConditionEvaluatorController implements ReactiveController {
return;
}
if (message.error !== undefined) {
this._serverResults[subtree.id] = false;
this._serverResults[subtree.id] = undefined;
this._subtreeErrors[subtree.id] =
typeof message.error === "string"
? message.error
@@ -265,7 +265,7 @@ export class ConditionEvaluatorController implements ReactiveController {
if (generation !== this._generation) {
return;
}
this._serverResults[subtree.id] = false;
this._serverResults[subtree.id] = undefined;
this._subtreeErrors[subtree.id] =
getWsErrorMessage(err) ?? hass.localize("ui.common.unknown_error");
this._recompute();
@@ -299,18 +299,19 @@ export class ConditionEvaluatorController implements ReactiveController {
}
};
// A failed subtree stays unknown, so it only hides the card when the
// result depends on it (a true `or` sibling still wins).
const value = this._split.evaluate(clientEvaluator, this._serverResults);
const error = firstDefined(this._subtreeErrors);
// Don't treat a server error as `false` that a client `not` would invert.
if (error !== undefined) {
if (value === undefined && error !== undefined) {
this._setResult("hidden", error);
return;
}
const value = this._split.evaluate(clientEvaluator, this._serverResults);
const result: ConditionEvaluation =
value === undefined ? "unknown" : value ? "visible" : "hidden";
this._setResult(result, firstDefined(this._subtreeTemplateErrors));
this._setResult(result, error ?? firstDefined(this._subtreeTemplateErrors));
}
private _setResult(
+13 -6
View File
@@ -209,6 +209,16 @@ const formatDurationMinuteMem = memoizeOne((locale: FrontendLocaleData) =>
})
);
// Splits a value into whole units and whole sub-units, e.g. 1.15 h into 1 h
// and 9 min. The value is converted to sub-units and rounded before flooring,
// as floating point math puts many of them just below a whole number:
// (1.15 - 1) * 60 is 8.999999999999995.
const splitDuration = (value: number, subUnits: number): [number, number] => {
const total = Math.floor(round(value * subUnits, 6));
const units = Math.floor(total / subUnits);
return [units, total - units * subUnits];
};
export const formatDuration = (
locale: FrontendLocaleData,
duration: string,
@@ -222,8 +232,7 @@ export const formatDuration = (
switch (unit) {
case "d": {
const days = Math.floor(value);
const hours = Math.floor((value - days) * 24);
const [days, hours] = splitDuration(value, 24);
const input = {
days,
hours,
@@ -231,8 +240,7 @@ export const formatDuration = (
return formatDurationDayMem(locale)(input);
}
case "h": {
const hours = Math.floor(value);
const minutes = Math.floor((value - hours) * 60);
const [hours, minutes] = splitDuration(value, 60);
const input = {
hours,
minutes,
@@ -240,8 +248,7 @@ export const formatDuration = (
return formatDurationHourMem(locale)(input);
}
case "min": {
const minutes = Math.floor(value);
const seconds = Math.floor((value - minutes) * 60);
const [minutes, seconds] = splitDuration(value, 60);
const input = {
minutes,
seconds,
+47
View File
@@ -0,0 +1,47 @@
/**
* How long after the full screen button the companion apps hide the page for
* the change, and after that how long they keep it hidden. A later hide ends
* streams as usual.
*/
export const FULLSCREEN_ENTER_TIME = 1000;
let enterStart = 0;
let enterId = 0;
// The last entering each stream let a hidden page through for
const claimedEnters = new WeakMap<object, number>();
/**
* Marks that the full screen button was pressed to enter full screen. The
* companion apps hide the page for a moment then, which shouldn't end a
* stream. Leaving full screen isn't marked, so locking the phone or leaving
* the app right after it always ends the streams.
*/
export const startEnteringFullscreen = () => {
enterId++;
enterStart = Date.now();
};
/** Ends it early, like when the browser denies full screen. */
export const cancelEnteringFullscreen = () => {
enterStart = 0;
};
export const isEnteringFullscreen = () =>
Date.now() - enterStart < FULLSCREEN_ENTER_TIME;
/**
* Whether the page is hidden by entering full screen, which hides it only
* once. Any later hiding is the user leaving, so each stream gets true only
* once per entering.
*/
export const claimFullscreenEnterHide = (stream: object): boolean => {
if (!isEnteringFullscreen() || claimedEnters.get(stream) === enterId) {
return false;
}
claimedEnters.set(stream, enterId);
// Counts from here, so the video still plays on when the page shows again
enterStart = Date.now();
return true;
};
-10
View File
@@ -31,8 +31,6 @@ export const setupLeafletMap = async (
const Leaflet = (await import("leaflet")).default as LeafletModuleType;
Leaflet.Icon.Default.imagePath = "/static/images/leaflet/images/";
await import("leaflet.markercluster");
const map = Leaflet.map(mapElement, {
minZoom: MAP_MIN_ZOOM,
maxZoom: MAP_MAX_ZOOM,
@@ -43,14 +41,6 @@ export const setupLeafletMap = async (
style.setAttribute("rel", "stylesheet");
mapElement.parentNode.appendChild(style);
const markerClusterStyle = document.createElement("link");
markerClusterStyle.setAttribute(
"href",
"/static/images/leaflet/MarkerCluster.css"
);
markerClusterStyle.setAttribute("rel", "stylesheet");
mapElement.parentNode.appendChild(markerClusterStyle);
if (initialView) {
map.setView(
[initialView.latitude, initialView.longitude],
+10 -6
View File
@@ -1,3 +1,4 @@
import { parseISO } from "date-fns";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
@@ -14,6 +15,7 @@ import {
getNumberFormatOptions,
isNumericFromAttributes,
} from "../number/format_number";
import { isDate } from "../string/is_date";
import { blankBeforeUnit } from "../translations/blank_before_unit";
import type { LocalizeFunc } from "../translations/localize";
import { computeDomain } from "./compute_domain";
@@ -196,7 +198,9 @@ const computeStateToPartsFromEntityAttributes = (
return [{ type: "value", value: value }];
}
if (DATE_TIME_DOMAINS.has(domain)) {
const isDateSensor = isSensorDomain && attributes.device_class === "date";
if (DATE_TIME_DOMAINS.has(domain) || isDateSensor) {
// If trying to display an explicit state, need to parse the explicit state to `Date` then format.
// Attributes aren't available, we have to use `state`.
@@ -217,15 +221,15 @@ const computeStateToPartsFromEntityAttributes = (
];
}
if (components.length === 1) {
if (state.includes("-")) {
// Date only.
if (isDate(state)) {
// Parse and format date-only values in UTC to preserve the calendar day.
return [
{
type: "value",
value: formatDate(
new Date(`${state}T00:00`),
{ ...locale, time_zone: TimeZone.local },
config
parseISO(`${state}T00:00:00Z`),
{ ...locale, time_zone: TimeZone.server },
{ ...config, time_zone: "UTC" }
),
},
];
+65
View File
@@ -1,8 +1,10 @@
import type { HassEntity } from "home-assistant-js-websocket";
import memoizeOne from "memoize-one";
import type { HomeAssistant } from "../../types";
import { ensureArray } from "../array/ensure-array";
import { computeDomain } from "./compute_domain";
import { getEntityContext } from "./context/get_entity_context";
import { getEntityIds } from "./get_entity_ids";
type EntityCategory = "none" | "config" | "diagnostic";
@@ -179,3 +181,66 @@ export const findFilteredEntities = (
);
return findEntities(Object.keys(sources.states), filterFuncs);
};
export type EntityFinder = (
states: HomeAssistant["states"],
entities: HomeAssistant["entities"],
devices: HomeAssistant["devices"],
areas: HomeAssistant["areas"],
floors: HomeAssistant["floors"]
) => string[];
/**
* Finds the same entities as `findFilteredEntities`, for repeated calls.
* Of a state, the filters only read its device class, so everything else is
* matched again only when the entity ids or the registries change.
*/
export const createEntityFinder = (filters: EntityFilter[]): EntityFinder => {
const registryFilters = filters.map(
({ device_class: _deviceClass, ...filter }) => filter
);
const deviceClasses = filters.map((filter) =>
filter.device_class ? new Set(ensureArray(filter.device_class)) : undefined
);
let candidatesKey: unknown[] = [];
let candidates: string[][] = [];
return memoizeOne<EntityFinder>(
(states, entities, devices, areas, floors) => {
const entityIds = getEntityIds(states);
const key = [entityIds, entities, devices, areas, floors];
if (key.some((value, i) => value !== candidatesKey[i])) {
candidatesKey = key;
candidates = registryFilters.map((filter) =>
entityIds.filter(
generateEntityFilter(
states,
entities,
devices,
areas,
floors,
filter
)
)
);
}
const seen = new Set<string>();
const results: string[] = [];
candidates.forEach((candidateIds, i) => {
const classes = deviceClasses[i];
for (const entityId of candidateIds) {
if (
!seen.has(entityId) &&
(!classes ||
classes.has(states[entityId].attributes.device_class || "none"))
) {
seen.add(entityId);
results.push(entityId);
}
}
});
return results;
}
);
};
+22
View File
@@ -0,0 +1,22 @@
import type { HomeAssistant } from "../../types";
let lastStates: HomeAssistant["states"] | undefined;
let lastEntityIds: string[] = [];
/**
* Returns the ids of `states`, as the same array for as long as they stay the
* same, so callers can memoize on it.
*/
export const getEntityIds = (states: HomeAssistant["states"]): string[] => {
if (states !== lastStates) {
lastStates = states;
const entityIds = Object.keys(states);
if (
entityIds.length !== lastEntityIds.length ||
entityIds.some((entityId, i) => entityId !== lastEntityIds[i])
) {
lastEntityIds = entityIds;
}
}
return lastEntityIds;
};
+46 -13
View File
@@ -1,9 +1,12 @@
/// <reference types="leaflet.markercluster" />
import type {
CircleMarker,
Control,
DivIcon,
Map,
MarkerCluster,
MarkerClusterGroup,
MarkerClusterGroupOptions,
Polyline,
} from "leaflet";
import type { LeafletModuleType } from "../../dom/setup-leaflet-map";
@@ -36,8 +39,18 @@ interface HandledMarker extends DecoratedMarker {
interface LeafletMarkerHandle extends MapMarkerHandle {
marker: HandledMarker;
title?: string;
}
// v2 option the 1.x types don't know yet
interface ClusterGroupOptions extends MarkerClusterGroupOptions {
clusterLabel?(cluster: MarkerCluster): string;
}
// Stands in for getAnimations on browsers without it (Chrome before 84),
// which markercluster calls whenever the map zooms
const noAnimations = (): Animation[] => [];
/** The Leaflet engine: raster viewing fallback without WebGL2, no editing */
export class LeafletMapEngine implements MapEngine {
/** For the ha-map jsdom tests only */
@@ -49,10 +62,14 @@ export class LeafletMapEngine implements MapEngine {
private _clusterable: HandledMarker[] = [];
private _MarkerClusterGroup?: typeof MarkerClusterGroup;
private _cluster?: MarkerClusterGroup;
private _clusterOptions: MapClusterOptions | null = null;
private _animateClusters = true;
private _scaleControl?: Control.Scale;
public async init(
@@ -66,22 +83,26 @@ export class LeafletMapEngine implements MapEngine {
// eslint-disable-next-line
const Leaflet = (await import("leaflet")).default as LeafletModuleType;
Leaflet.Icon.Default.imagePath = "/static/images/leaflet/images/";
await import("leaflet.markercluster");
// The package's own types are for Leaflet 2; on our Leaflet 1.9,
// @types/leaflet.markercluster describes it
this._MarkerClusterGroup = (await import("leaflet.markercluster"))
.MarkerClusterGroup as unknown as typeof MarkerClusterGroup;
// Without a native getAnimations, markercluster can't cancel the
// animations a zoom interrupts, so clusters don't animate there
this._animateClusters =
"getAnimations" in Element.prototype &&
Element.prototype.getAnimations !== noAnimations;
Element.prototype.getAnimations ??= noAnimations;
const map = Leaflet.map(container, {
minZoom: MAP_MIN_ZOOM,
maxZoom: MAP_MAX_ZOOM,
});
map.attributionControl.setPrefix("");
for (const href of [
"/static/images/leaflet/leaflet.css",
"/static/images/leaflet/MarkerCluster.css",
]) {
const style = document.createElement("link");
style.setAttribute("href", href);
style.setAttribute("rel", "stylesheet");
root.appendChild(style);
}
const style = document.createElement("link");
style.setAttribute("href", "/static/images/leaflet/leaflet.css");
style.setAttribute("rel", "stylesheet");
root.appendChild(style);
map.setView(options.center, options.zoom);
// The base layer adds itself; a vector layer may still fall back to raster
@@ -257,6 +278,7 @@ export class LeafletMapEngine implements MapEngine {
const handle: LeafletMarkerHandle = {
marker,
location,
title: options.title,
clusterData: options.clusterData,
remove: () => {
this._cluster?.removeLayer(marker);
@@ -345,18 +367,27 @@ export class LeafletMapEngine implements MapEngine {
this._cluster = undefined;
}
this._clusterOptions = options;
if (!this.leafletMap || !this.Leaflet) {
if (!this.leafletMap || !this.Leaflet || !this._MarkerClusterGroup) {
return;
}
if (!options) {
this._clusterable.forEach((marker) => marker.addTo(this.leafletMap!));
return;
}
// markercluster groups by proximity only; groupKey is not supported here
this._cluster = this.Leaflet.markerClusterGroup({
const clusterOptions: ClusterGroupOptions = {
showCoverageOnHover: false,
removeOutsideVisibleBounds: false,
animate: this._animateClusters,
maxClusterRadius: options.radius,
// The members' names, as the MapLibre engine labels its clusters
clusterLabel: (cluster) =>
(cluster.getAllChildMarkers() as HandledMarker[])
.map((marker) => marker.engineHandle?.title)
.filter(Boolean)
.join(", "),
iconCreateFunction: (cluster) => {
const build = () => {
const members = (cluster.getAllChildMarkers() as HandledMarker[]).map(
@@ -397,7 +428,9 @@ export class LeafletMapEngine implements MapEngine {
createShadow: () => null,
} as unknown as DivIcon;
},
});
};
this._cluster = new this._MarkerClusterGroup(clusterOptions);
this._cluster.addLayers(this._clusterable);
this.leafletMap!.addLayer(this._cluster!);
}
@@ -849,6 +849,9 @@ export class MapLibreMapEngine implements MapEngine {
if (!interactive) {
// Leaflet lets input through non-interactive markers; MapLibre does not
element.style.pointerEvents = "none";
} else {
// Leaflet points at what takes a click; MapLibre leaves the map's grab
element.style.cursor = "pointer";
}
setMarkerAccessibility(element, options.title, focusable);
element.style.zIndex = options.raised ? "1" : "";
@@ -1046,6 +1049,8 @@ export class MapLibreMapEngine implements MapEngine {
setMarkerAccessibility(centerEl, options.title, !!options.onClick);
if (options.moveable) {
centerEl.style.cursor = "move";
} else if (options.onClick) {
centerEl.style.cursor = "pointer";
}
this._placedElements.add(centerEl);
const centerMarker = new maplibre.Marker({
@@ -1650,6 +1655,7 @@ export class MapLibreMapEngine implements MapEngine {
this._hideEmerging(members);
};
setMarkerAccessibility(icon.element, this._groupTitle(group), true);
icon.element.style.cursor = "pointer";
icon.element.addEventListener("click", (ev) => {
ev.stopPropagation();
zoomToMembers();
+24 -1
View File
@@ -108,9 +108,32 @@ const addAtmosphere = (style: StyleSpecification): StyleSpecification => ({
sky: { ...style.sky, "atmosphere-blend": ATMOSPHERE_BLEND },
});
// MapLibre keeps the globe until it blends into mercator between zoom 11 and
// 12, but unbuffered ocean polygons leave hairline gaps between tiles on it
// from about zoom 6. Flatten it earlier, between zoom 5 and 6.
const GLOBE_FLATTEN_ZOOM = 5;
const flattenGlobeEarly = (style: StyleSpecification): StyleSpecification =>
style.projection?.type === "globe"
? {
...style,
projection: {
type: [
"interpolate",
["linear"],
["zoom"],
GLOBE_FLATTEN_ZOOM,
"vertical-perspective",
GLOBE_FLATTEN_ZOOM + 1,
"mercator",
],
},
}
: style;
/** Everything a freshly built style needs before it is handed to MapLibre */
export const finalizeMapStyle = (
name: string,
style: StyleSpecification
): StyleSpecification =>
addAtmosphere(addLatinLabels(useTileJson(name, style)));
flattenGlobeEarly(addAtmosphere(addLatinLabels(useTileJson(name, style))));
+10
View File
@@ -5,6 +5,7 @@ import type {
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
import type { FrontendLocaleData } from "../../data/translation";
import { NumberFormat } from "../../data/translation";
import { getLocaleDataVersion } from "../../resources/polyfills/locale-data-polyfill";
import { blankBeforeUnit } from "../translations/blank_before_unit";
/**
@@ -42,11 +43,20 @@ export const numberFormatToLocale = (
// (locale, options) combinations is small and bounded in practice, so cache the
// instances instead of rebuilding them on every call.
const numberFormatCache = new Map<string, Intl.NumberFormat>();
let numberFormatCacheVersion = getLocaleDataVersion();
const getNumberFormatter = (
locale: string | string[] | undefined,
options: Intl.NumberFormatOptions
): Intl.NumberFormat => {
// The Intl polyfill falls back to another locale while the data for the
// requested one is still loading, e.g. right after a language change.
// Start over when locale data is added, so the cache doesn't keep those.
const version = getLocaleDataVersion();
if (version !== numberFormatCacheVersion) {
numberFormatCache.clear();
numberFormatCacheVersion = version;
}
const key = JSON.stringify([locale, options]);
let formatter = numberFormatCache.get(key);
if (!formatter) {
+1 -1
View File
@@ -9,7 +9,7 @@ import {
// The filters of the Marketplace tables. Search, sorting and grouping are kept
// by the data table, see data-table-query-params.
export const marketplaceFilterQueryParamConfig = {
list: ["status", "type", "source", "integration_category"],
list: ["status", "type", "source", "integration_category", "connectivity"],
} as const satisfies QueryParamConfig;
export type MarketplaceFilterQueryParams = QueryParamValues<
@@ -37,3 +37,29 @@ export const preserveUnchangedRecord = <T>(
}
return changed ? next : previous;
};
/**
* List variant of {@link preserveUnchangedRecord}: replaces each item in `next`
* with the equal `previous` item that has the same key, in place.
*/
export const preserveUnchangedItems = <T>(
previous: readonly T[] | undefined,
next: T[],
getKey: (item: T) => string,
equal: (a: T, b: T) => boolean
): T[] => {
if (!previous?.length) {
return next;
}
const previousByKey = new Map<string, T>();
for (const item of previous) {
previousByKey.set(getKey(item), item);
}
for (let i = 0; i < next.length; i++) {
const previousItem = previousByKey.get(getKey(next[i]));
if (previousItem !== undefined && equal(previousItem, next[i])) {
next[i] = previousItem;
}
}
return next;
};
@@ -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;
}
}
+178 -28
View File
@@ -17,17 +17,27 @@ import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import { storage } from "../../common/decorators/storage";
import { deepActiveElement } from "../../common/dom/deep-active-element";
import { fireEvent, type HASSDomEvent } from "../../common/dom/fire_event";
import {
cancelEnteringFullscreen,
isEnteringFullscreen,
startEnteringFullscreen,
} from "../../common/dom/entering-fullscreen";
import { ctrlOrCmdLabel } from "../../common/keyboard/ctrl-or-cmd";
import type { LocalizeFunc } from "../../common/translations/localize";
import { nextRender } from "../../common/util/render-status";
import type { CameraCapabilities, CameraEntity } from "../../data/camera";
import type { CameraStreamStatus } from "../../data/camera-streams";
import { showCameraStreamInfoDialog } from "../../dialogs/camera/show-dialog-camera-stream-info";
import { isExternal } from "../../data/external";
import {
showCameraStreamInfoDialog,
type CameraStreamInfo,
} from "../../dialogs/camera/show-dialog-camera-stream-info";
import "../ha-camera-stream";
import type { HaCameraStream } from "../ha-camera-stream";
import "../ha-icon-button";
import "../ha-spinner";
import "../ha-svg-icon";
import "./ha-camera-placeholder";
import "./ha-camera-stream-badge";
import {
fitPicture,
@@ -97,6 +107,9 @@ export class HaCameraPlayer extends LitElement {
@property({ type: Boolean, attribute: "keep-awake" })
public keepAwake = false;
/** Fills the height it is given, with the picture in the middle. */
@property({ type: Boolean, reflect: true }) public fill = false;
@state() private _status: CameraStreamStatus = {
connecting: true,
hasAudio: false,
@@ -104,6 +117,8 @@ export class HaCameraPlayer extends LitElement {
@state() private _capabilities?: CameraCapabilities;
private _streamInfoCallbacks = new Set<(info: CameraStreamInfo) => void>();
@state() private _video?: HTMLVideoElement;
@state() private _muted = false;
@@ -133,6 +148,10 @@ export class HaCameraPlayer extends LitElement {
// full screen player
@state() private _paused = false;
// Playing when its button entered full screen, so a pause meanwhile is the
// companion app's
private _playingBeforeFullscreen = false;
@query("ha-camera-stream") private _stream?: HaCameraStream;
@query(".player") private _player?: HTMLElement;
@@ -159,6 +178,16 @@ export class HaCameraPlayer extends LitElement {
private _controlsTimeout?: number;
// A pointer type or "keyboard", as hover sticks after a tap on touch
// screens and focus moved by a script can look like keyboard focus
private _lastInput?: string;
// Captured, as dialogs stop the propagation of their key presses
private _inputChanged = (ev: KeyboardEvent | PointerEvent) => {
this._lastInput =
ev.type === "keydown" ? "keyboard" : (ev as PointerEvent).pointerType;
};
private _wheelHintTimeout?: number;
private _videoRequest = 0;
@@ -186,7 +215,7 @@ export class HaCameraPlayer extends LitElement {
public connectedCallback() {
super.connectedCallback();
document.addEventListener("visibilitychange", this._requestWakeLock);
document.addEventListener("visibilitychange", this._visibilityChanged);
// The first update requests it, once keep-awake is set
if (this.hasUpdated) {
this._requestWakeLock();
@@ -196,19 +225,28 @@ export class HaCameraPlayer extends LitElement {
"webkitfullscreenchange",
this._fullscreenChanged
);
const inputOptions = { capture: true, passive: true };
document.addEventListener("keydown", this._inputChanged, inputOptions);
document.addEventListener("pointerdown", this._inputChanged, inputOptions);
if (this._controlsVisible) {
this._scheduleHideControls();
}
}
public disconnectedCallback() {
super.disconnectedCallback();
document.removeEventListener("visibilitychange", this._requestWakeLock);
document.removeEventListener("visibilitychange", this._visibilityChanged);
this._releaseWakeLock();
document.removeEventListener("fullscreenchange", this._fullscreenChanged);
document.removeEventListener(
"webkitfullscreenchange",
this._fullscreenChanged
);
document.removeEventListener("keydown", this._inputChanged, true);
document.removeEventListener("pointerdown", this._inputChanged, true);
clearTimeout(this._controlsTimeout);
clearTimeout(this._wheelHintTimeout);
this._streamInfoCallbacks.clear();
this._unbindVideo(this._video);
this._video = undefined;
this._pointers.clear();
@@ -235,7 +273,7 @@ export class HaCameraPlayer extends LitElement {
const aspectRatio = this._aspectRatio();
if (aspectRatio !== this._firedAspectRatio) {
this._firedAspectRatio = aspectRatio;
fireEvent(this, "camera-aspect-ratio-changed", { aspectRatio });
fireEvent(this, "media-size-changed", { aspectRatio });
}
if (changedProps.has("keepAwake")) {
if (this.keepAwake) {
@@ -248,6 +286,10 @@ export class HaCameraPlayer extends LitElement {
this._unbindVideo(changedProps.get("_video") as HTMLVideoElement);
this._bindVideo(this._video);
}
if (changedProps.has("_status") || changedProps.has("_capabilities")) {
const info = this._streamInfo();
this._streamInfoCallbacks.forEach((callback) => callback(info));
}
}
protected render() {
@@ -259,11 +301,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
@@ -284,9 +327,10 @@ export class HaCameraPlayer extends LitElement {
gesture: this._gesture,
})}
style=${styleMap({
aspectRatio: this._fullscreen
? undefined
: String(this._aspectRatio()),
aspectRatio:
this._fullscreen || this.fill
? undefined
: String(this._aspectRatio()),
})}
@pointerdown=${this._pointerDown}
@pointerup=${this._pointerUp}
@@ -303,6 +347,9 @@ export class HaCameraPlayer extends LitElement {
mjpeg-video
measure-poster
style=${styleMap({
"--picture-aspect-ratio": this.fill
? String(this._aspectRatio())
: undefined,
transform: zoomed
? `translate(${this._zoom.x}px, ${this._zoom.y}px) scale(${this._zoom.scale})`
: undefined,
@@ -312,6 +359,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>
@@ -325,7 +377,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")}
@@ -458,6 +513,11 @@ export class HaCameraPlayer extends LitElement {
</div>`;
}
private _visibilityChanged = () => {
this._requestWakeLock();
this._resumeAfterEnteringFullscreen();
};
/**
* Browsers release the lock when the page is hidden, so it is requested
* again whenever the page shows.
@@ -506,9 +566,10 @@ export class HaCameraPlayer extends LitElement {
this._controlsTimeout = window.setTimeout(() => {
this._controlsTimeout = undefined;
if (
this._overlay?.querySelector(
".control:hover, ha-camera-stream-badge:hover"
) ||
(this._lastInput === "mouse" &&
this._overlay?.querySelector(
".control:hover, ha-camera-stream-badge:hover"
)) ||
this._hasKeyboardFocus()
) {
this._scheduleHideControls();
@@ -520,6 +581,7 @@ export class HaCameraPlayer extends LitElement {
private _hasKeyboardFocus(): boolean {
return Boolean(
this._lastInput === "keyboard" &&
this.shadowRoot &&
deepActiveElement(this.shadowRoot)?.matches(":focus-visible")
);
@@ -536,15 +598,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();
}
}
@@ -579,10 +647,26 @@ export class HaCameraPlayer extends LitElement {
this._posterSize = ev.detail.size;
}
private _showStreamInfo() {
showCameraStreamInfoDialog(this, {
private _streamInfo(): CameraStreamInfo {
return {
status: this._status,
supportedTypes: this._capabilities?.frontend_stream_types,
};
}
private _subscribeStreamInfo = (
callback: (info: CameraStreamInfo) => void
) => {
this._streamInfoCallbacks.add(callback);
callback(this._streamInfo());
return () => {
this._streamInfoCallbacks.delete(callback);
};
};
private _showStreamInfo() {
showCameraStreamInfoDialog(this, {
subscribe: this._subscribeStreamInfo,
});
}
@@ -671,6 +755,7 @@ export class HaCameraPlayer extends LitElement {
this._paused = Boolean(
video?.paused && (video.srcObject || video.currentSrc)
);
this._resumeAfterEnteringFullscreen();
};
private _toggleMute() {
@@ -722,16 +807,27 @@ export class HaCameraPlayer extends LitElement {
("webkitFullscreenElement" in document
? (document.webkitFullscreenElement as Element | null)
: null);
const fullscreen = Boolean(
this._fullscreen = Boolean(
this._player && fullscreenElement === this._player
);
if (fullscreen !== this._fullscreen) {
this._fullscreen = fullscreen;
// The size changes, so the zoomed in area would be off
this._zoom = ZOOM_PAN_IDENTITY;
}
this._resumeAfterEnteringFullscreen();
};
// The companion apps pause the video while entering full screen
private _resumeAfterEnteringFullscreen() {
if (
isExternal &&
this._playingBeforeFullscreen &&
this._paused &&
document.visibilityState === "visible" &&
isEnteringFullscreen()
) {
// Only once, so a pause in the iPhone's own full screen controls stays
this._playingBeforeFullscreen = false;
this._ensurePlaying();
}
}
private async _toggleFullscreen() {
const player = this._player;
if (!player) {
@@ -746,6 +842,10 @@ export class HaCameraPlayer extends LitElement {
}
return;
}
this._playingBeforeFullscreen = Boolean(
this._video && !this._video.paused
);
startEnteringFullscreen();
if (player.requestFullscreen) {
await player.requestFullscreen();
} else if ("webkitRequestFullscreen" in player) {
@@ -759,6 +859,7 @@ export class HaCameraPlayer extends LitElement {
}
} catch (_err: unknown) {
// Denied by the browser
cancelEnteringFullscreen();
}
}
@@ -813,12 +914,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
@@ -862,7 +968,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)) {
@@ -902,10 +1008,15 @@ export class HaCameraPlayer extends LitElement {
private _pointerMove(ev: PointerEvent) {
if (ev.pointerType === "mouse" && !this._pointers.size) {
// A click changes it, so the control focused with the keyboard stays
if (!this._hasKeyboardFocus()) {
this._lastInput = "mouse";
}
this._showControls();
}
const pointer = this._pointers.get(ev.pointerId);
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();
@@ -1030,6 +1141,38 @@ export class HaCameraPlayer extends LitElement {
cursor: none;
}
:host([fill]) {
position: relative;
flex: 1;
min-height: 0;
}
:host([fill]) .player {
position: absolute;
inset: 0;
}
:host([fill]) .viewport {
height: 100%;
max-height: none;
container-type: size;
--video-max-height: 100%;
}
/* As large as the picture fits in the middle, zoomed from the corner of
the viewport like a stream that fills it */
:host([fill]) ha-camera-stream {
--picture-width: min(100cqw, 100cqh * var(--picture-aspect-ratio));
--picture-height: min(100cqh, 100cqw / var(--picture-aspect-ratio));
position: absolute;
top: calc((100cqh - var(--picture-height)) / 2);
left: calc((100cqw - var(--picture-width)) / 2);
width: var(--picture-width);
height: var(--picture-height);
transform-origin: calc((var(--picture-width) - 100cqw) / 2)
calc((var(--picture-height) - 100cqh) / 2);
}
.viewport {
position: relative;
overflow: hidden;
@@ -1067,6 +1210,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;
@@ -1189,6 +1338,7 @@ declare global {
"ha-camera-player": HaCameraPlayer;
}
interface HASSDomEvents {
"camera-aspect-ratio-changed": { aspectRatio: number };
/** The natural width limits the picture's width when it is set */
"media-size-changed": { aspectRatio: number; naturalWidth?: number };
}
}
+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 {
+267 -93
View File
@@ -9,6 +9,7 @@ import {
import { differenceInMinutes } from "date-fns";
import type {
DataZoomComponentOption,
GridComponentOption,
MarkAreaComponentOption,
} from "echarts/components";
import type { EChartsType } from "echarts/core";
@@ -27,6 +28,7 @@ import {
eventOptions,
property,
query,
queryAll,
state,
} from "lit/decorators";
import { classMap } from "lit/directives/class-map";
@@ -150,6 +152,9 @@ const processSeriesTooltipFormatter = (s: HaECSeriesItem): RawSeriesOption => {
export type CustomLegendOption = ECOption["legend"] & {
type: "custom";
// "y-axis" lists the items beside the chart, each one next to its category,
// in place of the y-axis labels.
position?: "bottom" | "y-axis";
data?: {
id?: string;
secondaryIds?: string[]; // Other dataset IDs that should be controlled by this legend item.
@@ -248,6 +253,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
@query(".chart") private _chartContainer?: HTMLDivElement;
@queryAll(".chart-legend button[data-id]")
private _legendButtons!: NodeListOf<HTMLElement>;
@query(".sonification-output")
private _sonificationOutput?: HTMLDivElement;
@@ -319,6 +327,25 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
},
});
// The axis legend takes width from the chart without resizing the host
private _chartResizeController = new ResizeController(this, {
target: null,
callback: (entries) => {
const contentRect = entries[entries.length - 1]?.contentRect;
if (
this.chart &&
contentRect &&
(Math.round(contentRect.width) !== this.chart.getWidth() ||
Math.round(contentRect.height) !== this.chart.getHeight())
) {
this._shouldResizeChart = true;
this._resizeChartIfNeeded();
}
},
});
private _focusedLegendButton?: { id: string; toggle: boolean };
private _loading = false;
private _reducedMotion = false;
@@ -441,6 +468,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
if (!this.isConnected) {
return;
}
this._chartResizeController.observe(this._chartContainer!);
// The only measurement taken here: neither observer has reported yet, and a
// chart first rendered inside a hidden container has to defer its setup
// rather than build against a guessed width.
@@ -489,6 +517,16 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
}
public willUpdate(changedProps: PropertyValues): void {
const focused = this.shadowRoot?.activeElement as HTMLElement | null;
this._focusedLegendButton =
focused?.dataset.id &&
focused.closest(".chart-legend") &&
focused.matches(":focus-visible")
? {
id: focused.dataset.id,
toggle: focused.classList.contains("legend-toggle"),
}
: undefined;
if (!this.chart) {
return;
}
@@ -596,6 +634,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
this._resizeChartIfNeeded();
}
this._renderedLegendFit = this._legendFit.fit;
this._restoreLegendFocus();
if (changedProps.has("options") || changedProps.has("data")) {
// New values keep the widest widths, but other items are fitted afresh
const legendItemsKey = JSON.stringify(
@@ -610,11 +649,30 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
}
}
// The legend reuses its buttons when items move, which would leave focus on
// whichever item now sits where the focused one was
private _restoreLegendFocus() {
const focused = this._focusedLegendButton;
const active = this.shadowRoot?.activeElement as HTMLElement | null;
if (!focused || active?.dataset.id === focused.id) {
return;
}
const className = focused.toggle ? "legend-toggle" : "label";
Array.from(this._legendButtons)
.find(
(button) =>
button.dataset.id === focused.id &&
button.classList.contains(className)
)
?.focus();
}
protected render() {
const sonifiable =
!this._sonificationUnavailable &&
canSonifyChart(this.data, this._hiddenDatasets);
const showZoomSlider = this._showZoomSlider();
const axisLegend = this._hasAxisLegend();
return html`
<div
class="container ${classMap({ "has-height": !!this.height })}"
@@ -626,11 +684,14 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
})}
>
<div
class="chart-container"
class="chart-container ${classMap({
"has-axis-legend": axisLegend,
})}"
style=${styleMap({
height: this.height ? undefined : `${this._getDefaultHeight()}px`,
})}
>
${axisLegend ? this._renderAxisLegend() : nothing}
<div
class="chart ${classMap({
"touch-scrub": this._isTouchDevice && this._hasZoomableXAxis(),
@@ -656,7 +717,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
${showZoomSlider ? this._renderZoomSlider() : nothing}
</div>
<div class="sonification-output"></div>
${this._renderLegend()}
${axisLegend ? nothing : this._renderLegend()}
<div class="top-controls ${classMap({ small: this.smallControls })}">
<slot name="search"></slot>
<div
@@ -683,14 +744,22 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
`;
}
private _getLegendItems() {
if (!this.options?.legend || !this.data) {
private _getCustomLegend() {
if (!this.options?.legend) {
return undefined;
}
const legend = ensureArray(this.options.legend).find(
return ensureArray(this.options.legend).find(
(l) => l.show && l.type === "custom"
) as CustomLegendOption | undefined;
if (!legend) {
}
private _hasAxisLegend() {
return this._getCustomLegend()?.position === "y-axis";
}
private _getLegendItems() {
const legend = this._getCustomLegend();
if (!legend || !this.data) {
return undefined;
}
const datasets = ensureArray(this.data);
@@ -707,20 +776,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
if (!items) {
return nothing;
}
const datasets = ensureArray(this.data!);
// Index datasets by id and name so each legend item is an O(1) lookup
// instead of scanning every dataset twice. Charts can have many series.
const datasetById = new Map<unknown, (typeof datasets)[number]>();
const datasetByName = new Map<unknown, (typeof datasets)[number]>();
for (const dataset of datasets) {
if (dataset.id !== undefined && !datasetById.has(dataset.id)) {
datasetById.set(dataset.id, dataset);
}
if (dataset.name !== undefined && !datasetByName.has(dataset.name)) {
datasetByName.set(dataset.name, dataset);
}
}
const fit = this._legendFit.fit ?? items.length;
return html`<div
class=${classMap({
@@ -729,73 +784,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
})}
>
<ul ${this._legendFit.target()}>
${items.map((item, index) => {
let itemStyle: Record<string, any> = {};
let value = "";
let noLabelClick = false;
const name = typeof item === "string" ? item : (item.name ?? "");
let id: string;
if (typeof item === "string") {
id = item;
} else {
id = item.id ?? name;
value = item.value ?? "";
itemStyle = item.itemStyle ?? {};
noLabelClick = item.noLabelClick ?? false;
}
const labelClickable = this.clickLabelForMoreInfo && !noLabelClick;
const dataset = datasetById.get(id) ?? datasetByName.get(id);
itemStyle = {
color: dataset?.color as string,
...(dataset?.itemStyle as { borderColor?: string }),
...itemStyle,
};
const color = itemStyle?.color as string;
return html`<li
.id=${id}
@pointerdown=${this._legendPointerDown}
@pointerup=${this._legendPointerCancel}
@pointerleave=${this._legendPointerCancel}
@pointercancel=${this._legendPointerCancel}
@contextmenu=${this._legendContextMenu}
class=${classMap({
hidden: this._hiddenDatasets.has(id),
overflow: !this.expandLegend && index >= fit,
})}
>
<button
type="button"
class="legend-toggle"
data-id=${id}
aria-pressed=${!this._hiddenDatasets.has(id)}
.title=${this._i18n.localize(
"ui.components.history_charts.toggle_visibility"
)}
@click=${this._toggleDataset}
>
<ha-svg-icon
.path=${
this._hiddenDatasets.has(id)
? mdiCircleOutline
: mdiCheckCircle
}
style=${styleMap({
color: this._hiddenDatasets.has(id) ? undefined : color,
})}
></ha-svg-icon>
</button>
<button
type="button"
class=${classMap({ label: true, clickable: labelClickable })}
data-id=${id}
.title=${name}
@click=${this._labelClick}
>
${name}
</button>
${value ? html`<div class="value">${value}</div>` : nothing}
</li>`;
})}
${this._renderLegendItems(items, fit)}
${
items.length
? html`<li
@@ -829,6 +818,107 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
</div>`;
}
private _renderAxisLegend() {
const items = this._getLegendItems() ?? [];
const grid = ensureArray(this._getGridOption()!)[0];
return html`<div class="chart-legend axis-legend">
<ul
@pointerover=${this._axisLegendPointerOver}
@pointerleave=${this._axisLegendPointerLeave}
style=${styleMap({
paddingTop: `${grid.top}px`,
paddingBottom: `${grid.bottom}px`,
})}
>
${this._renderLegendItems(items, items.length)}
</ul>
</div>`;
}
private _renderLegendItems(
items: NonNullable<ReturnType<HaChartBase["_getLegendItems"]>>,
fit: number
) {
const datasets = ensureArray(this.data!);
// Index datasets by id and name so each legend item is an O(1) lookup
// instead of scanning every dataset twice. Charts can have many series.
const datasetById = new Map<unknown, (typeof datasets)[number]>();
const datasetByName = new Map<unknown, (typeof datasets)[number]>();
for (const dataset of datasets) {
if (dataset.id !== undefined && !datasetById.has(dataset.id)) {
datasetById.set(dataset.id, dataset);
}
if (dataset.name !== undefined && !datasetByName.has(dataset.name)) {
datasetByName.set(dataset.name, dataset);
}
}
return items.map((item, index) => {
let itemStyle: Record<string, any> = {};
let value = "";
let noLabelClick = false;
const name = typeof item === "string" ? item : (item.name ?? "");
let id: string;
if (typeof item === "string") {
id = item;
} else {
id = item.id ?? name;
value = item.value ?? "";
itemStyle = item.itemStyle ?? {};
noLabelClick = item.noLabelClick ?? false;
}
const labelClickable = this.clickLabelForMoreInfo && !noLabelClick;
const dataset = datasetById.get(id) ?? datasetByName.get(id);
itemStyle = {
color: dataset?.color as string,
...(dataset?.itemStyle as { borderColor?: string }),
...itemStyle,
};
const color = itemStyle?.color as string;
return html`<li
.id=${id}
@pointerdown=${this._legendPointerDown}
@pointerup=${this._legendPointerCancel}
@pointerleave=${this._legendPointerCancel}
@pointercancel=${this._legendPointerCancel}
@contextmenu=${this._legendContextMenu}
class=${classMap({
hidden: this._hiddenDatasets.has(id),
overflow: !this.expandLegend && index >= fit,
})}
>
<button
type="button"
class="legend-toggle"
data-id=${id}
aria-pressed=${!this._hiddenDatasets.has(id)}
.title=${this._i18n.localize(
"ui.components.history_charts.toggle_visibility"
)}
@click=${this._toggleDataset}
>
<ha-svg-icon
.path=${
this._hiddenDatasets.has(id) ? mdiCircleOutline : mdiCheckCircle
}
style=${styleMap({
color: this._hiddenDatasets.has(id) ? undefined : color,
})}
></ha-svg-icon>
</button>
<button
type="button"
class=${classMap({ label: true, clickable: labelClickable })}
data-id=${id}
.title=${name}
@click=${this._labelClick}
>
${name}
</button>
${value ? html`<div class="value">${value}</div>` : nothing}
</li>`;
});
}
// Chart2Music adds ~45 kB gzipped, so it is only fetched once someone actually
// moves keyboard focus into a chart.
private async _handleChartFocus() {
@@ -1309,14 +1399,28 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
private _getGridOption() {
const grid = this.options?.grid;
if (!grid || !this._zoomSliderRoom) {
const axisLegend = this._hasAxisLegend();
if (!axisLegend && (!grid || !this._zoomSliderRoom)) {
return grid;
}
const [first, ...rest] = ensureArray(grid);
return [
{ ...first, bottom: this._getGridBottom() + this._getZoomSliderSpace() },
...rest,
];
const [first, ...rest] = ensureArray(grid ?? {});
const result: GridComponentOption = { ...first };
if (axisLegend) {
// The legend rows are laid out from these, so labels must not move them
result.top = this._getGridTop();
result.bottom = this._getGridBottom();
result.containLabel = false;
result.outerBoundsMode = "none";
}
if (this._zoomSliderRoom) {
result.bottom = this._getGridBottom() + this._getZoomSliderSpace();
}
return [result, ...rest];
}
private _getGridTop() {
const top = this.options?.grid && ensureArray(this.options.grid)[0].top;
return typeof top === "number" ? top : 0;
}
private _getGridBottom() {
@@ -1389,6 +1493,22 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
} as XAXisOption;
});
}
let yAxis = this.options?.yAxis;
if (this._hasAxisLegend()) {
const [first, ...rest] = ensureArray(yAxis ?? {});
yAxis = [
{
...first,
type: "category",
inverse: true,
data: this._getLegendItems()?.map((item) =>
typeof item === "string" ? item : (item.id ?? item.name)
),
axisLabel: { ...first.axisLabel, show: false },
} as YAXisOption,
...rest,
];
}
let legend = this.options?.legend;
if (legend) {
legend = ensureArray(legend).map((l) =>
@@ -1418,6 +1538,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
grid: this._getGridOption(),
legend,
xAxis,
yAxis,
};
if (options.tooltip) {
@@ -1881,6 +2002,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
series.option.center = null;
series.option.zoom = 1;
});
fireEvent(this, "chart-zoom-reset");
}
private _getGraphRoams(): {
@@ -2018,6 +2140,24 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
}
};
private _axisLegendPointerOver(ev: PointerEvent) {
if (ev.pointerType !== "mouse" || !this.chart) {
return;
}
const id = (ev.target as HTMLElement).closest("li")?.id;
if (!id || this._hiddenDatasets.has(id)) {
this._hideTooltip();
return;
}
this.chart.dispatchAction({ type: "showTip", seriesIndex: 0, name: id });
}
private _axisLegendPointerLeave(ev: PointerEvent) {
if (ev.pointerType === "mouse") {
this._hideTooltip();
}
}
private _hideTooltip() {
this.chart?.dispatchAction({ type: "hideTip" });
this.chart?.dispatchAction({
@@ -2322,6 +2462,15 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
.has-height .chart-container {
flex: 1;
}
.chart-container.has-axis-legend {
display: flex;
/* The chart is not mirrored in RTL, so its legend stays on the left */
direction: ltr;
}
.has-axis-legend .chart {
flex: 1;
min-width: 0;
}
.chart {
height: 100%;
width: 100%;
@@ -2422,6 +2571,29 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
position: absolute;
visibility: hidden;
}
.chart-legend.axis-legend {
flex: none;
max-width: min(200px, 40%);
max-height: none;
padding: 0;
overflow: visible;
direction: var(--direction);
}
.chart-legend.axis-legend ul {
height: 100%;
box-sizing: border-box;
flex-direction: column;
flex-wrap: nowrap;
align-items: stretch;
gap: 0;
}
.chart-legend.axis-legend li,
.chart-legend.axis-legend li:has(.legend-toggle) {
flex: 1 1 0;
height: auto;
min-height: 0;
max-width: none;
}
.chart-legend .hidden {
color: var(--secondary-text-color);
}
@@ -2526,5 +2698,7 @@ declare global {
};
"chart-sankeyroam": { zoom: number };
"chart-setup": undefined;
// The user reset the zoom
"chart-zoom-reset": undefined;
}
}
+188 -6
View File
@@ -11,6 +11,8 @@ import type {
import { mdiFormatTextVariant, mdiGoogleCirclesGroup } from "@mdi/js";
import memoizeOne from "memoize-one";
import { consume } from "../../common/decorators/consume";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { fireEvent } from "../../common/dom/fire_event";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../common/translations/localize";
import { reducedMotionContext } from "../../data/context";
@@ -128,6 +130,25 @@ export class HaNetworkGraph extends LitElement {
*/
@property({ attribute: false }) public selectedNode?: string;
/**
* Highlight the neighbors of a node on hover and fade the rest.
*/
@property({ attribute: false }) public hoverFocus = true;
/**
* Distance in pixels from the center of a node within which a click next to
* it still clicks the node, so small nodes are easier to hit. 0 is off.
* Such a click fires a `chart-click` with only `dataType` and `data.id`.
*/
@property({ attribute: false }) public nodeClickRadius = 0;
/**
* Names of the legend categories that are switched off. Keep it up to date
* with `network-legend-changed`, or leave it out to let the legend keep its
* own selection.
*/
@property({ attribute: false }) public hiddenCategories?: string[];
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state() private _highlightedNodes?: Set<string>;
@@ -162,6 +183,8 @@ export class HaNetworkGraph extends LitElement {
private _followedChart?: EChartsType;
private _cancelSettledHide?: () => void;
@query("ha-chart-base") private _baseChart?: HaChartBase;
constructor() {
@@ -180,6 +203,10 @@ export class HaNetworkGraph extends LitElement {
this._physicsEnabled =
this.data.nodes.length <= PHYSICS_DISABLE_THRESHOLD;
}
// Before the first render, which counts the visible nodes
if (changedProperties.has("hiddenCategories") && this.hiddenCategories) {
this._hiddenCategories = this.hiddenCategories;
}
}
protected render() {
@@ -203,14 +230,19 @@ export class HaNetworkGraph extends LitElement {
isMobile,
hasHighlightedNodes,
this.selectedNode,
this.hoverFocus,
this._nodePositions,
this._pinnedNodes,
this._fewVisibleNodes()
)}
.options=${this._createOptions(this.data?.categories)}
.options=${this._createOptions(
this.data?.categories,
this.hiddenCategories
)}
height="100%"
.extraComponents=${[GraphChart]}
@chart-setup=${this._handleChartSetup}
@chart-click=${this._handleBaseChartClick}
>
<slot name="search" slot="search"></slot>
<slot name="button" slot="button"></slot>
@@ -234,7 +266,10 @@ export class HaNetworkGraph extends LitElement {
}
private _createOptions = memoizeOne(
(categories?: NetworkData["categories"]): HaECOption => ({
(
categories?: NetworkData["categories"],
hiddenCategories?: string[]
): HaECOption => ({
tooltip: {
trigger: "item",
confine: true,
@@ -246,6 +281,15 @@ export class HaNetworkGraph extends LitElement {
...category,
icon: category.symbol,
})),
// Every category, as a category left out keeps its last selection
...(hiddenCategories && {
selected: Object.fromEntries(
(categories ?? []).map((category) => [
category.name,
!hiddenCategories.includes(category.name),
])
),
}),
bottom: 8,
},
dataZoom: {
@@ -311,6 +355,7 @@ export class HaNetworkGraph extends LitElement {
isMobile: boolean,
hasHighlightedNodes?: boolean,
selectedNode?: string,
hoverFocus = true,
nodePositions: Record<string, { x: number; y: number }> = {},
pinnedNodes: string[] = [],
fewVisibleNodes = true
@@ -345,7 +390,11 @@ export class HaNetworkGraph extends LitElement {
},
},
emphasis: {
focus: hasHighlightedNodes ? "self" : isMobile ? "none" : "adjacency",
focus: hasHighlightedNodes
? "self"
: isMobile || !hoverFocus
? "none"
: "adjacency",
},
force: {
repulsion: [400, 600],
@@ -570,12 +619,23 @@ export class HaNetworkGraph extends LitElement {
}
}
// Fired for every drawn frame, so the page can place things next to nodes
// while the graph moves, and stays idle when it does not
private _handleRendered = () => {
fireEvent(this, "network-graph-rendered", undefined, {
bubbles: false,
composed: false,
});
};
private _handleChartSetup() {
const chart = this._baseChart?.chart;
chart?.getZr().on("click", this._handleEmptyClick);
chart?.on("mousedown", this._handleNodeMouseDown);
chart?.getZr().on("dragstart", this._handleDragStart);
chart?.getZr().on("drag", this._handleDrag);
chart?.getZr().on("dragend", this._handleDragEnd);
chart?.on("rendered", this._handleRendered);
for (const event of LEGEND_SELECT_EVENTS) {
chart?.on(event, this._handleLegendChange);
}
@@ -588,18 +648,22 @@ export class HaNetworkGraph extends LitElement {
// last render
this.requestUpdate();
this._updateFollowing();
// The base chart drew the first frame before the listener was added
this._handleRendered();
}
private _handleLegendChange = (params: unknown) => {
const { selected } = params as { selected: Record<string, boolean> };
const fewVisibleNodes = this._fewVisibleNodes();
this._setHiddenCategories(
(params as { selected: Record<string, boolean> }).selected
);
this._setHiddenCategories(selected);
if (this._fewVisibleNodes() !== fewVisibleNodes) {
// The new series option lays out again from where the nodes are now
this._saveNodePositions();
this.requestUpdate();
}
fireEvent(this, "network-legend-changed", {
hidden: this._hiddenCategories,
});
};
private _setHiddenCategories(selected: Record<string, boolean>) {
@@ -608,6 +672,65 @@ export class HaNetworkGraph extends LitElement {
);
}
// A click next to a small node hits nothing, or a link that runs to its
// center, so it clicks the nearest node within nodeClickRadius instead
private _handleEmptyClick = (ev: {
target?: unknown;
offsetX: number;
offsetY: number;
}) => {
if (!ev.target) {
this._clickNearestNode(ev.offsetX, ev.offsetY);
}
};
// The base chart forwards a click on a link, which is replaced by the node
// click, so the page gets one click
private _handleBaseChartClick = (
ev: HASSDomEvent<HASSDomEvents["chart-click"]>
) => {
const { dataType, event } = ev.detail;
if (
dataType === "edge" &&
event &&
this._clickNearestNode(event.offsetX, event.offsetY)
) {
ev.stopPropagation();
}
};
// Returns whether a node was clicked
private _clickNearestNode(offsetX: number, offsetY: number): boolean {
const chart = this._baseChart?.chart;
if (!this.nodeClickRadius || !chart || chart.isDisposed()) {
return false;
}
const series = this._getGraphSeries(chart);
let nearest: { id: string; distance: number } | undefined;
series?.getGraph().eachNode((node: any) => {
const layout: number[] | undefined = node.getLayout();
if (!layout) {
return;
}
const [x, y] = chart.convertToPixel({ seriesId: "network" }, layout);
const distance = Math.hypot(x - offsetX, y - offsetY);
if (
distance <= this.nodeClickRadius &&
(!nearest || distance < nearest.distance)
) {
nearest = { id: node.id, distance };
}
});
if (!nearest) {
return false;
}
fireEvent(this, "chart-click", {
dataType: "node",
data: { id: nearest.id },
} as unknown as HASSDomEvents["chart-click"]);
return true;
}
private _handleNodeMouseDown = (params: {
dataType?: string;
data?: unknown;
@@ -735,6 +858,62 @@ export class HaNetworkGraph extends LitElement {
}
};
/**
* The position of a node in pixels within the graph, or undefined when the
* node is not drawn.
*/
public getNodePosition(id: string): { x: number; y: number } | undefined {
const chart = this._baseChart?.chart;
if (!chart || chart.isDisposed()) {
return undefined;
}
const series = this._getGraphSeries(chart);
const node = series?.getGraph().getNodeById(id);
if (!node) {
return undefined;
}
// The layout already holds where a moving node ends up, the drawn symbol
// where it is now
const transform: number[] | null | undefined = series
.getData()
.getItemGraphicEl(node.dataIndex)
?.getComputedTransform();
if (transform) {
return { x: transform[4], y: transform[5] };
}
const position: number[] | undefined = node.getLayout();
if (!position) {
return undefined;
}
const [x, y] = chart.convertToPixel({ seriesId: "network" }, position);
return { x, y };
}
public hideTooltip(): void {
const chart = this._baseChart?.chart;
if (!chart || chart.isDisposed()) {
return;
}
chart.dispatchAction({ type: "hideTip" });
this._cancelSettledHide?.();
// A resize waits for running animations and shows the tooltip again, so
// it is hidden once more when the chart has settled. Without a resize it
// would hide the next tooltip, so moving the pointer cancels it.
const zr = chart.getZr();
const hideWhenSettled = () => {
this._cancelSettledHide?.();
chart.dispatchAction({ type: "hideTip" });
};
const cancel = () => {
chart.off("finished", hideWhenSettled);
zr.off("mousemove", cancel);
this._cancelSettledHide = undefined;
};
chart.on("finished", hideWhenSettled);
zr.on("mousemove", cancel);
this._cancelSettledHide = cancel;
}
private _centerOnSelectedNode = () => {
const chart = this._followedChart;
if (!chart) {
@@ -861,5 +1040,8 @@ declare global {
}
interface HASSDomEvents {
"node-selected": { id: string };
// The names of the legend categories that are switched off
"network-legend-changed": { hidden: string[] };
"network-graph-rendered": undefined;
}
}
@@ -328,6 +328,11 @@ export function generateStatisticsChartData(
: undefined,
color: chartType === "bar" ? backgroundColor : borderColor,
};
if (chartType === "bar") {
// echarts sizes bars from the smallest gap between points, so sparse
// data (one point, or points far apart) gets huge bars without a cap
(series as BarSeriesOption).barMaxWidth = 50;
}
if (chartStacked) {
series.stack = `band-stacked`;
series.stackStrategy = "samesign";
+8 -2
View File
@@ -1,5 +1,6 @@
import { mdiClose } from "@mdi/js";
import type { ContextType } from "@lit/context";
import { createContext, provide } from "@lit/context";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../common/decorators/consume";
@@ -11,7 +12,10 @@ import "./ha-icon-button";
import "./ha-dialog";
import type { DialogWidth } from "./ha-dialog";
type DialogSheetMode = "dialog" | "bottom-sheet";
export type DialogSheetMode = "dialog" | "bottom-sheet";
export const adaptiveDialogModeContext =
createContext<DialogSheetMode>("adaptiveDialogMode");
export const ADAPTIVE_DIALOG_MEDIA_QUERY =
"(max-width: 870px), (max-height: 500px)";
@@ -125,7 +129,9 @@ export class HaAdaptiveDialog extends LitElement {
@property({ type: Boolean, reflect: true, attribute: "flexcontent" })
public flexContent = false;
@state() public mode: DialogSheetMode = "dialog";
@provide({ context: adaptiveDialogModeContext })
@state()
public mode: DialogSheetMode = "dialog";
@state()
@consume({ context: internationalizationContext, subscribe: true })
+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%;
+20 -4
View File
@@ -327,7 +327,7 @@ export class HaCodeEditor extends ReactiveElement {
transactions.push({
effects: [
this._loadedCodeMirror!.readonlyCompartment!.reconfigure(
this._loadedCodeMirror!.EditorView!.editable.of(!this.readOnly)
this._readOnlyExtensions()
),
this._loadedCodeMirror!.yamlLintCompartment!.reconfigure(
this.lint && !this.readOnly
@@ -452,9 +452,7 @@ export class HaCodeEditor extends ReactiveElement {
this._loadedCodeMirror.haSyntaxHighlighting,
this._loadedCodeMirror.yamlScalarHighlighter,
this._loadedCodeMirror.yamlScalarHighlightStyle,
this._loadedCodeMirror.readonlyCompartment.of(
this._loadedCodeMirror.EditorView.editable.of(!this.readOnly)
),
this._loadedCodeMirror.readonlyCompartment.of(this._readOnlyExtensions()),
this._loadedCodeMirror.linewrapCompartment.of(
this.linewrap ? this._loadedCodeMirror.EditorView.lineWrapping : []
),
@@ -523,6 +521,20 @@ export class HaCodeEditor extends ReactiveElement {
}
}
private _readOnlyExtensions(): Extension {
const cm = this._loadedCodeMirror!;
if (!this.readOnly) {
return cm.EditorView.editable.of(true);
}
return [
cm.EditorView.editable.of(false),
// Keeps commands like Tab from changing the content once it has focus
cm.EditorState.readOnly.of(true),
// Focusable, so the content can be scrolled with the keyboard
cm.EditorView.contentAttributes.of({ tabindex: "0" }),
];
}
private _fullscreenLabel(): string {
if (this._isFullscreen) {
return (
@@ -1939,6 +1951,10 @@ export class HaCodeEditor extends ReactiveElement {
padding-top: var(--code-editor-toolbar-height);
}
:host(.fullscreen) {
--code-mirror-min-height: 100%;
}
:host(.fullscreen) .cm-editor {
height: 100% !important;
max-height: 100% !important;
+43 -20
View File
@@ -111,6 +111,11 @@ export class HaControlCircularSlider extends LitElement {
@state() public _lastSlider?: ActiveSlider;
// Position of the other handle before the active one started pushing it
private _lowBeforePush?: number;
private _highBeforePush?: number;
private _valueToPercentage(value: number) {
return (
(clamp(value, this.min, this.max) - this.min) / (this.max - this.min)
@@ -122,31 +127,31 @@ export class HaControlCircularSlider extends LitElement {
}
private _steppedValue(value: number) {
return Math.round(value / this.step) * this.step;
// Rounding to the step can overshoot min/max when they aren't multiples of it
return clamp(Math.round(value / this.step) * this.step, this.min, this.max);
}
private _boundedValue(value: number) {
const min =
this._activeSlider === "high"
? Math.min(this._localLow ?? this.max)
: this.min;
const max =
this._activeSlider === "low"
? Math.max(this._localHigh ?? this.min)
: this.max;
return Math.min(Math.max(value, min), max);
return Math.min(Math.max(value, this.min), this.max);
}
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) {
this._lowBeforePush = undefined;
this._highBeforePush = undefined;
if (changedProps.has("value")) {
this._localValue = this.value;
}
@@ -179,6 +184,10 @@ export class HaControlCircularSlider extends LitElement {
disconnectedCallback(): void {
super.disconnectedCallback();
this._destroyListeners();
if (this._activeSlider) {
this._cancelInteraction();
}
}
private _managers: HammerManager[] = [];
@@ -226,9 +235,19 @@ export class HaControlCircularSlider extends LitElement {
switch (this._activeSlider) {
case "high":
this._localHigh = value;
// Push the low handle along instead of stopping at it, and let it
// return to where it was if the drag comes back
if (this._localLow != null) {
this._lowBeforePush ??= this._localLow;
this._localLow = Math.min(this._lowBeforePush, value);
}
break;
case "low":
this._localLow = value;
if (this._localHigh != null) {
this._highBeforePush ??= this._localHigh;
this._localHigh = Math.max(this._highBeforePush, value);
}
break;
case "value":
this._localValue = value;
@@ -248,6 +267,18 @@ export class HaControlCircularSlider extends LitElement {
return undefined;
}
private _cancelInteraction() {
if (this._activeSlider) {
fireEvent(this, `${this._activeSlider}-changing`, {
value: undefined,
});
}
this._activeSlider = undefined;
this._localValue = this.value;
this._localLow = this.low;
this._localHigh = this.high;
}
private _setupListeners() {
if (this._interactions && this._managers.length === 0) {
this._interactions.forEach((interaction) => {
@@ -279,15 +310,7 @@ export class HaControlCircularSlider extends LitElement {
mc.add(new Tap({ event: "singletap" }));
const cancelInteraction = () => {
if (this._activeSlider) {
fireEvent(this, `${this._activeSlider}-changing`, {
value: undefined,
});
}
this._activeSlider = undefined;
this._localValue = this.value;
this._localLow = this.low;
this._localHigh = this.high;
this._cancelInteraction();
if (pressToActivate) {
panRecognizer.set({ enable: false });
}
+23 -3
View File
@@ -250,8 +250,8 @@ export class HaDialog extends ScrollableFadeMixin(LitElement) {
this._hassConfig?.auth.external &&
isIosApp(this._hassConfig.auth.external)
) {
const element = this.querySelector("[autofocus]");
if (element !== null) {
const element = this._autofocusElement();
if (element) {
if (!element.id) {
element.id = "ha-dialog-autofocus";
}
@@ -264,10 +264,30 @@ export class HaDialog extends ScrollableFadeMixin(LitElement) {
}
return;
}
(this.querySelector("[autofocus]") as HTMLElement | null)?.focus();
this._autofocusElement()?.focus();
});
};
// Wrappers like ha-adaptive-dialog pass their content in through slots
private _autofocusElement(): HTMLElement | null {
const element = this.querySelector<HTMLElement>("[autofocus]");
if (element) {
return element;
}
for (const slot of this.querySelectorAll("slot")) {
for (const assigned of slot.assignedElements({ flatten: true })) {
if (assigned.matches("[autofocus]")) {
return assigned as HTMLElement;
}
const nested = assigned.querySelector<HTMLElement>("[autofocus]");
if (nested) {
return nested;
}
}
}
return null;
}
private _handleAfterShow = (ev: Event) => {
if (ev.eventPhase !== Event.AT_TARGET) {
return;
+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();
@@ -83,6 +83,7 @@ const SELECTOR_FALLBACK_VALUES = {
ui_action: undefined,
ui_clock_date_format: undefined,
ui_color: undefined,
ui_condition: undefined,
ui_state_content: undefined,
ui_time_format: undefined,
unit_of_measurement: undefined,
@@ -118,6 +118,7 @@ const SELECTOR_INITIAL_VALUES = {
ui_action: undefined,
ui_clock_date_format: undefined,
ui_color: undefined,
ui_condition: () => [],
ui_state_content: undefined,
ui_time_format: undefined,
unit_of_measurement: undefined,
+1
View File
@@ -238,6 +238,7 @@ export class HaGridSizeEditor extends LitElement {
grid-template-rows: auto auto;
grid-template-columns: auto 1fr;
gap: var(--ha-space-2);
padding-left: var(--ha-space-4);
}
.precise {
grid-area: precise;
+12 -5
View File
@@ -9,6 +9,10 @@ import { consume } from "../common/decorators/consume";
import { isComponentLoaded } from "../common/config/is_component_loaded";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { fireEvent } from "../common/dom/fire_event";
import {
claimFullscreenEnterHide,
FULLSCREEN_ENTER_TIME,
} from "../common/dom/entering-fullscreen";
import type { LocalizeFunc } from "../common/translations/localize";
import { nextRender } from "../common/util/render-status";
import { fetchStreamUrl } from "../data/camera";
@@ -101,16 +105,19 @@ export class HaHLSPlayer extends LitElement {
return;
}
if (document.hidden) {
if (isExternal) {
if (isExternal && !claimFullscreenEnterHide(this)) {
// The companion apps pause JavaScript timers while in the background,
// so a delayed clean up would not run until the app is opened again
this._cleanUp();
return;
}
this._hiddenCleanupTimeout = window.setTimeout(() => {
this._hiddenCleanupTimeout = undefined;
this._cleanUp();
}, HIDDEN_CLEANUP_DELAY);
this._hiddenCleanupTimeout = window.setTimeout(
() => {
this._hiddenCleanupTimeout = undefined;
this._cleanUp();
},
isExternal ? FULLSCREEN_ENTER_TIME : HIDDEN_CLEANUP_DELAY
);
} else if (this._hiddenCleanupTimeout) {
// stream was not cleaned up yet, just cancel the cleanup
clearTimeout(this._hiddenCleanupTimeout);
+1 -1
View File
@@ -45,7 +45,7 @@ function adjustRgb(
if (wv != null) {
return rgbw2rgb([...rgb, wv] as [number, number, number, number]);
}
if (cw != null && ww !== null) {
if (cw != null && ww != null) {
return rgbww2rgb(
[...rgb, cw, ww] as [number, number, number, number, number],
minKelvin,
+47 -31
View File
@@ -1,17 +1,23 @@
import { mdiDelete, mdiPlayBox, mdiPlus } from "@mdi/js";
import type { HassEntities } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import memoizeOne from "memoize-one";
import { consume } from "../common/decorators/consume";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { transform } from "../common/decorators/transform";
import { fireEvent } from "../common/dom/fire_event";
import { supportsFeature } from "../common/entity/supports-feature";
import type { LocalizeFunc } from "../common/translations/localize";
import { statesContext } from "../data/context";
import type { MediaPickedEvent } from "../data/media-player";
import {
MediaClassBrowserSettings,
MediaPlayerEntityFeature,
} from "../data/media-player";
import type { MediaSelector, MediaSelectorValue } from "../data/selector";
import type { HomeAssistant } from "../types";
import "./ha-alert";
import "./ha-form/ha-form";
import type { SchemaUnion } from "./ha-form/types";
@@ -31,8 +37,6 @@ const EMPTY_FORM = {};
@customElement("ha-media-item-picker")
export class HaMediaItemPicker extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: MediaSelector;
@property({ attribute: false }) public value?: MediaSelectorValue;
@@ -51,6 +55,26 @@ export class HaMediaItemPicker extends LitElement {
filter_entity?: string | string[];
};
@state() @consumeLocalize() private _localize!: LocalizeFunc;
@state()
@consume({ context: statesContext, subscribe: true })
@transform<HassEntities | null, boolean>({
transformer: function (this: HaMediaItemPicker, states) {
const entityId = this._getActiveEntityId();
if (!entityId) {
return true;
}
const stateObj = states?.[entityId];
return (
!!stateObj &&
supportsFeature(stateObj, MediaPlayerEntityFeature.BROWSE_MEDIA)
);
},
watch: ["value", "context"],
})
private _supportsBrowse?: boolean;
private _contextEntities: string[] | undefined;
private get _hasAccept(): boolean {
@@ -68,13 +92,6 @@ export class HaMediaItemPicker extends LitElement {
protected render() {
const entityId = this._getActiveEntityId();
const stateObj = entityId ? this.hass.states[entityId] : undefined;
const supportsBrowse =
!entityId ||
(stateObj &&
supportsFeature(stateObj, MediaPlayerEntityFeature.BROWSE_MEDIA));
if (this.selector.media?.image_upload && !this.value) {
return html`${this.label ? html`<label>${this.label}</label>` : nothing}
<ha-picture-upload
@@ -98,7 +115,7 @@ export class HaMediaItemPicker extends LitElement {
.value=${entityId}
.label=${
this.label ||
this.hass.localize(
this._localize(
"ui.components.selectors.media.pick_media_player"
)
}
@@ -114,20 +131,19 @@ export class HaMediaItemPicker extends LitElement {
`
}
${
!supportsBrowse
this._supportsBrowse === false
? html`
${this.label ? html`<label>${this.label}</label>` : nothing}
<ha-alert>
${this.hass.localize(
${this._localize(
"ui.components.selectors.media.browse_not_supported"
)}
</ha-alert>
<ha-form
.hass=${this.hass}
.data=${this.value || EMPTY_FORM}
.schema=${MANUAL_SCHEMA}
.computeLabel=${this._computeLabelCallback}
.computeHelper=${this._computeHelperCallback}
.computeLabel=${this._computeLabel(this._localize)}
.computeHelper=${this._computeHelper(this._localize)}
></ha-form>
`
: html`${this.label ? html`<label>${this.label}</label>` : nothing}
@@ -137,9 +153,7 @@ export class HaMediaItemPicker extends LitElement {
role="button"
aria-label=${
!this.value?.media_content_id
? this.hass.localize(
"ui.components.selectors.media.pick_media"
)
? this._localize("ui.components.selectors.media.pick_media")
: this.value.metadata?.title || this.value.media_content_id
}
@click=${this._pickMedia}
@@ -196,7 +210,7 @@ export class HaMediaItemPicker extends LitElement {
<div class="title">
${
!this.value?.media_content_id
? this.hass.localize(
? this._localize(
"ui.components.selectors.media.pick_media"
)
: this.value.metadata?.title ||
@@ -209,7 +223,7 @@ export class HaMediaItemPicker extends LitElement {
: html`
<div class="delete">
<ha-icon-button
.label=${this.hass.localize("ui.common.delete")}
.label=${this._localize("ui.common.delete")}
.path=${mdiDelete}
@click=${this._clearValue}
></ha-icon-button>
@@ -227,7 +241,7 @@ export class HaMediaItemPicker extends LitElement {
variant="danger"
@click=${this._clearValue}
>
${this.hass.localize(
${this._localize(
"ui.components.picture-upload.clear_picture"
)}
</ha-button>
@@ -243,15 +257,17 @@ export class HaMediaItemPicker extends LitElement {
`;
}
private _computeLabelCallback = (
schema: SchemaUnion<typeof MANUAL_SCHEMA>
): string =>
this.hass.localize(`ui.components.selectors.media.${schema.name}`);
private _computeLabel = memoizeOne(
(localize: LocalizeFunc) =>
(schema: SchemaUnion<typeof MANUAL_SCHEMA>): string =>
localize(`ui.components.selectors.media.${schema.name}`)
);
private _computeHelperCallback = (
schema: SchemaUnion<typeof MANUAL_SCHEMA>
): string =>
this.hass.localize(`ui.components.selectors.media.${schema.name}_detail`);
private _computeHelper = memoizeOne(
(localize: LocalizeFunc) =>
(schema: SchemaUnion<typeof MANUAL_SCHEMA>): string =>
localize(`ui.components.selectors.media.${schema.name}_detail`)
);
private _entityChanged(ev: CustomEvent) {
ev.stopPropagation();
+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 = () => {
@@ -1,10 +1,14 @@
import { mdiMagnify, mdiMapSearchOutline } from "@mdi/js";
import type { HassConfig } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consume } from "../../common/decorators/consume";
import { transform } from "../../common/decorators/transform";
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
import { fireEvent } from "../../common/dom/fire_event";
import type { LocalizeFunc } from "../../common/translations/localize";
import { configContext, internationalizationContext } from "../../data/context";
import type {
LocationSelector,
LocationSelectorValue,
@@ -14,7 +18,10 @@ import {
formatOpenStreetMapPlace,
searchPlaces,
} from "../../data/openstreetmap";
import type { HomeAssistant } from "../../types";
import type {
HomeAssistantConfig,
HomeAssistantInternationalization,
} from "../../types";
import type { SchemaUnion } from "../ha-form/types";
import type { HaListItemButton } from "../item/ha-list-item-button";
import { searchResultsStatus } from "../list/search-results-status";
@@ -28,6 +35,7 @@ import "../ha-alert";
import "../ha-icon-button";
import "../item/ha-list-item-button";
import "../list/ha-list-base";
import "../animation/ha-fade-in";
import "../ha-spinner";
import "../ha-svg-icon";
import "../input/ha-input";
@@ -39,8 +47,6 @@ import {
@customElement("ha-selector-location")
export class HaLocationSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: LocationSelector;
@property({ type: Object }) public value?: LocationSelectorValue;
@@ -51,6 +57,17 @@ export class HaLocationSelector extends LitElement {
@property({ type: Boolean, reflect: true }) public disabled = false;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: HomeAssistantInternationalization;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, HassConfig | undefined>({
transformer: ({ config }) => config ?? undefined,
})
private _hassConfig?: HassConfig;
@state() private _working = false;
@state() private _places?: OpenStreetMapPlace[] | null;
@@ -106,10 +123,10 @@ export class HaLocationSelector extends LitElement {
);
protected willUpdate() {
if (!this.value) {
if (!this.value && this._hassConfig) {
this.value = {
latitude: this.hass.config.latitude,
longitude: this.hass.config.longitude,
latitude: this._hassConfig.latitude,
longitude: this._hassConfig.longitude,
radius: this.selector.location?.radius ? DEFAULT_RADIUS : undefined,
};
}
@@ -121,7 +138,7 @@ export class HaLocationSelector extends LitElement {
<div class="location-search" @keydown=${this._searchKeyDown}>
<ha-input
label=${this.hass.localize(
label=${this._i18n.localize(
"ui.components.selectors.location.address_label"
)}
.disabled=${this.disabled}
@@ -137,7 +154,7 @@ export class HaLocationSelector extends LitElement {
: html`<ha-icon-button
slot="end"
.path=${mdiMapSearchOutline}
.label=${this.hass.localize("ui.common.search")}
.label=${this._i18n.localize("ui.common.search")}
.disabled=${this.disabled}
@click=${this._searchButtonClicked}
></ha-icon-button>`
@@ -147,7 +164,7 @@ export class HaLocationSelector extends LitElement {
${
this._searchError
? html`<ha-alert alert-type="error">
${this.hass.localize(
${this._i18n.localize(
"ui.components.selectors.location.search_error"
)}
</ha-alert>`
@@ -165,7 +182,7 @@ export class HaLocationSelector extends LitElement {
Array.isArray(this._places) && this._places.length
? html`
<ha-list-base
aria-label=${this.hass.localize(
aria-label=${this._i18n.localize(
"ui.components.selectors.location.search_results_label"
)}
>
@@ -174,13 +191,13 @@ export class HaLocationSelector extends LitElement {
`
: this._places?.length === 0
? html`<p class="search-no-results">
${this.hass.localize("ui.components.combo-box.no_match")}
${this._i18n.localize("ui.components.combo-box.no_match")}
</p>`
: nothing
}
<p class="attribution">
${this.hass.localize(
${this._i18n.localize(
"ui.components.selectors.location.search_disclosure",
{
openstreetmap: html`<a
@@ -193,7 +210,7 @@ export class HaLocationSelector extends LitElement {
href="https://wiki.osmfoundation.org/wiki/Privacy_Policy"
target="_blank"
rel="noopener noreferrer"
>${this.hass.localize(
>${this._i18n.localize(
"ui.components.selectors.location.osm_privacy_policy"
)}</a
>`,
@@ -202,18 +219,27 @@ export class HaLocationSelector extends LitElement {
</p>
</div>
<ha-locations-editor
class="flex"
.helper=${this.helper}
.locations=${this._location(this.selector, this.value)}
@location-updated=${this._locationChanged}
@radius-updated=${this._radiusChanged}
pin-on-click
></ha-locations-editor>
${
this._hassConfig
? html`<ha-locations-editor
class="flex"
.helper=${this.helper}
.locations=${this._location(
this.selector,
this._hassConfig,
this.value
)}
@location-updated=${this._locationChanged}
@radius-updated=${this._radiusChanged}
pin-on-click
></ha-locations-editor>`
: html`<ha-fade-in .delay=${500}
><ha-spinner></ha-spinner
></ha-fade-in>`
}
<ha-form
.hass=${this.hass}
.schema=${this._schema(
this.hass.localize,
this._i18n.localize,
this.selector.location?.radius,
this.selector.location?.radius_readonly
)}
@@ -228,6 +254,7 @@ export class HaLocationSelector extends LitElement {
private _location = memoizeOne(
(
selector: LocationSelector,
hassConfig: HassConfig,
value?: LocationSelectorValue
): MarkerLocation[] => {
const computedStyles = getComputedStyle(this);
@@ -240,11 +267,11 @@ export class HaLocationSelector extends LitElement {
id: "location",
latitude:
!value || isNaN(value.latitude)
? this.hass.config.latitude
? hassConfig.latitude
: value.latitude,
longitude:
!value || isNaN(value.longitude)
? this.hass.config.longitude
? hassConfig.longitude
: value.longitude,
radius: selector.location?.radius
? value?.radius || DEFAULT_RADIUS
@@ -286,7 +313,7 @@ export class HaLocationSelector extends LitElement {
entry: SchemaUnion<ReturnType<typeof this._schema>>
): string => {
if (entry.name) {
return this.hass.localize(
return this._i18n.localize(
`ui.components.selectors.location.${entry.name}`
);
}
@@ -337,12 +364,17 @@ export class HaLocationSelector extends LitElement {
this._status = undefined;
try {
this._places = await searchPlaces(searchTerm, this.hass, true, 3);
this._places = await searchPlaces(
searchTerm,
this._i18n.locale.language,
true,
3
);
this._status = searchResultsStatus(
searchTerm,
this._places,
() => true,
this.hass.localize
this._i18n.localize
);
} catch (_err) {
this._places = undefined;
@@ -398,7 +430,7 @@ export class HaLocationSelector extends LitElement {
this._input?.focus({ preventScroll: true });
}
this._places = undefined;
this._status = this.hass.localize(
this._status = this._i18n.localize(
"ui.components.selectors.location.selected_location",
{ location: place.display_name }
);
@@ -1,15 +1,12 @@
import { html, LitElement, type TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
import type { MediaSelector, MediaSelectorValue } from "../../data/selector";
import type { HomeAssistant } from "../../types";
import "../ha-media-item-picker";
import { ensureArray } from "../../common/array/ensure-array";
import { fireEvent } from "../../common/dom/fire_event";
@customElement("ha-selector-media")
export class HaMediaSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: MediaSelector;
@property({ attribute: false }) public value?:
@@ -34,7 +31,6 @@ export class HaMediaSelector extends LitElement {
changeCallback?
): TemplateResult {
return html`<ha-media-item-picker
.hass=${this.hass}
.context=${this.context}
.selector=${this.selector}
.value=${value}
@@ -26,6 +26,20 @@ import "../ha-svg-icon";
import "../radio/ha-radio-group";
import "../radio/ha-radio-option";
const SEARCH_MIN_OPTIONS = 12;
const SEARCH_KEYS = [{ name: "primary", weight: 1 }];
// Every value gets the prefix, so "" has a non-empty ID and no value can
// collide with another value's ID.
const PICKER_ID_PREFIX = "option:";
export const toPickerId = (value: string | number) =>
`${PICKER_ID_PREFIX}${value}`;
export const findPickerOption = (options: SelectOption[], id?: string) =>
options.find((option) => toPickerId(option.value) === id);
@customElement("ha-selector-select")
export class HaSelectSelector extends LitElement {
@state()
@@ -256,6 +270,23 @@ export class HaSelectSelector extends LitElement {
`;
}
if (options.length > SEARCH_MIN_OPTIONS) {
return html`
<ha-generic-picker
no-sort
.label=${this.label}
.helper=${this.helper}
.disabled=${this.disabled}
.required=${this.required}
.getItems=${this._getSearchItems(options)}
.value=${this._pickerValue(options)}
.valueRenderer=${this._valueRenderer(options)}
.searchKeys=${SEARCH_KEYS}
@value-changed=${this._searchPickerChanged}
></ha-generic-picker>
`;
}
return html`
<ha-select
.label=${this.label ?? ""}
@@ -310,6 +341,37 @@ export class HaSelectSelector extends LitElement {
}
);
private _getSearchItems = memoizeOne(
(options: SelectOption[]) => () =>
options.map((option) => ({
id: toPickerId(option.value),
primary: option.label,
sorting_label: option.label,
disabled: option.disabled,
}))
);
private _pickerValue(options: SelectOption[]): string | undefined {
const value = this.value as string | number | undefined;
if (typeof value !== "string" && typeof value !== "number") {
return undefined;
}
if (value === "" && !options.some((option) => option.value === "")) {
return undefined;
}
return toPickerId(value);
}
private _valueRenderer = memoizeOne(
(options: SelectOption[]) => (id: string) =>
html`<span slot="headline"
>${
findPickerOption(options, id)?.label ??
id.slice(PICKER_ID_PREFIX.length)
}</span
>`
);
private get _mode(): "list" | "dropdown" | "box" {
return (
this.selector.select?.mode ||
@@ -384,6 +446,36 @@ export class HaSelectSelector extends LitElement {
});
}
private _searchPickerChanged(ev: CustomEvent): void {
ev.stopPropagation();
if (this.disabled) {
return;
}
const id: string | undefined = ev.detail.value;
if (id === undefined) {
if (this.value !== undefined) {
fireEvent(this, "value-changed", { value: undefined });
}
return;
}
// Look the pick up in the current options: the open list can be older.
const option = findPickerOption(this._getOptions(this.selector), id);
if (
!option ||
option.disabled ||
(this.value != null && String(option.value) === String(this.value))
) {
return;
}
fireEvent(this, "value-changed", { value: option.value });
}
private _comboBoxValueChanged(ev: CustomEvent): void {
ev.stopPropagation();
const newValue = ev.detail.value;
@@ -0,0 +1,52 @@
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import type { UiConditionSelector } from "../../data/selector";
import "../../panels/lovelace/editor/conditions/ha-card-conditions-editor";
import type { VisibilityCondition } from "../../panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../types";
@customElement("ha-selector-ui_condition")
export class HaUiConditionSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false })
public selector!: UiConditionSelector;
@property({ attribute: false }) public value?: VisibilityCondition[];
@property() public label?: string;
@property({ type: Boolean }) public disabled = false;
protected firstUpdated() {
// The editor's labels come from the dashboard translations, which only
// load with a dashboard; this selector can show anywhere.
this.hass.loadFragmentTranslation("lovelace");
}
protected render() {
return html`
${this.label ? html`<label>${this.label}</label>` : nothing}
<ha-card-conditions-editor
.hass=${this.hass}
.conditions=${this.value ?? []}
.disabled=${this.disabled}
></ha-card-conditions-editor>
`;
}
static styles = css`
label {
display: block;
margin-bottom: var(--ha-space-1);
font-weight: var(--ha-font-weight-medium);
color: var(--secondary-text-color);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-selector-ui_condition": HaUiConditionSelector;
}
}
@@ -69,6 +69,7 @@ const LOAD_ELEMENTS = {
ui_action: () => import("./ha-selector-ui-action"),
ui_clock_date_format: () => import("./ha-selector-ui-clock-date-format"),
ui_color: () => import("./ha-selector-ui-color"),
ui_condition: () => import("./ha-selector-ui-condition"),
ui_state_content: () => import("./ha-selector-ui-state-content"),
ui_time_format: () => import("./ha-selector-ui-time-format"),
unit_of_measurement: () => import("./ha-selector-unit-of-measurement"),
+48 -16
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">
@@ -442,7 +474,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
}
private _renderPanel(panel: PanelInfo, isSelected: boolean) {
const title = getPanelTitle(this.hass, panel);
const title = getPanelTitle(this.hass.localize, panel);
const urlPath = panel.url_path;
const icon = getPanelIcon(panel);
const iconPath = getPanelIconPath(panel);
+12 -5
View File
@@ -8,6 +8,10 @@ import { styleMap } from "lit/directives/style-map";
import { consume } from "../common/decorators/consume";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import { fireEvent } from "../common/dom/fire_event";
import {
claimFullscreenEnterHide,
FULLSCREEN_ENTER_TIME,
} from "../common/dom/entering-fullscreen";
import type { LocalizeFunc } from "../common/translations/localize";
import {
addWebRtcCandidate,
@@ -242,16 +246,19 @@ export class HaWebRtcPlayer extends LitElement {
return;
}
if (document.hidden) {
if (isExternal) {
if (isExternal && !claimFullscreenEnterHide(this)) {
// The companion apps pause JavaScript timers while in the background,
// so a delayed clean up would not run until the app is opened again
this._cleanUp();
return;
}
this._hiddenCleanupTimeout = window.setTimeout(() => {
this._hiddenCleanupTimeout = undefined;
this._cleanUp();
}, HIDDEN_CLEANUP_DELAY);
this._hiddenCleanupTimeout = window.setTimeout(
() => {
this._hiddenCleanupTimeout = undefined;
this._cleanUp();
},
isExternal ? FULLSCREEN_ENTER_TIME : HIDDEN_CLEANUP_DELAY
);
} else if (this._hiddenCleanupTimeout) {
// stream was not cleaned up yet, just cancel the cleanup
clearTimeout(this._hiddenCleanupTimeout);
+1
View File
@@ -200,6 +200,7 @@ class HaEntityMarker extends LitElement {
}
.entity-picture {
background-size: cover;
background-position: center;
height: 100%;
width: 100%;
}
+14
View File
@@ -1812,6 +1812,20 @@ export class HaMap extends ReactiveElement {
#map.clickable {
cursor: pointer;
}
/* Bubble avatars open their entity; the expanded bubble around them
takes no click of its own */
.maplibregl-marker ha-entity-marker {
cursor: pointer;
}
/* A drag that starts on a marker pans the map like anywhere else;
markers that drag themselves keep their own cursor */
.maplibregl-canvas-container.maplibregl-interactive:active
.maplibregl-marker:not(.maplibregl-marker-draggable),
.maplibregl-canvas-container.maplibregl-interactive:active
.maplibregl-marker:not(.maplibregl-marker-draggable)
ha-entity-marker {
cursor: grabbing !important;
}
.maplibregl-marker {
transition:
opacity var(--ha-animation-duration-fast),
+11 -3
View File
@@ -1,9 +1,9 @@
import type { TemplateResult } from "lit";
import type { PropertyValues, TemplateResult } from "lit";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { ifDefined } from "lit/directives/if-defined";
import type { ActionHandlerOptions } from "../../data/lovelace/action_handler";
import { actionHandler } from "../../panels/lovelace/common/directives/action-handler-directive";
import { actionHandlerBind } from "../../panels/lovelace/common/directives/action-handler-directive";
import "../ha-icon";
import "../ha-svg-icon";
@@ -56,6 +56,11 @@ export class HaTileIcon extends LitElement {
return nothing;
}
protected updated(changedProps: PropertyValues<this>): void {
super.updated(changedProps);
actionHandlerBind(this, this.actionHandlerOptions);
}
protected render(): TemplateResult {
const hasImage = Boolean(this.imageUrl);
@@ -67,7 +72,6 @@ export class HaTileIcon extends LitElement {
aria-label=${ifDefined(
this.interactive ? this.accessibleLabel : undefined
)}
.actionHandler=${actionHandler(this.actionHandlerOptions)}
>
<slot name="icon">${this._renderIcon()}</slot>
</div>
@@ -94,6 +98,7 @@ export class HaTileIcon extends LitElement {
:host([interactive]) {
-webkit-tap-highlight-color: transparent;
pointer-events: auto;
cursor: pointer;
}
:host([interactive]:active) {
transform: scale(1.2);
@@ -143,6 +148,9 @@ export class HaTileIcon extends LitElement {
transition: color 180ms ease-in-out;
pointer-events: none;
}
::slotted(:not([slot])) {
pointer-events: none;
}
.container img {
width: 100%;
height: 100%;
+8 -5
View File
@@ -11,6 +11,7 @@ import type {
HassEntityBase,
} from "home-assistant-js-websocket";
import { supportsFeature } from "../common/entity/supports-feature";
import type { LocalizeFunc } from "../common/translations/localize";
import { showEnterCodeDialog } from "../dialogs/enter-code/show-enter-code-dialog";
import type { HomeAssistant } from "../types";
import { getExtendedEntityRegistryEntry } from "./entity/entity_registry";
@@ -108,7 +109,9 @@ export const supportedAlarmModes = (stateObj: AlarmControlPanelEntity) =>
export const setProtectedAlarmControlPanelMode = async (
element: HTMLElement,
hass: Pick<HomeAssistant, "callService" | "localize" | "callWS">,
callService: HomeAssistant["callService"],
callWS: HomeAssistant["callWS"],
localize: LocalizeFunc,
stateObj: AlarmControlPanelEntity,
mode: AlarmMode
) => {
@@ -123,7 +126,7 @@ export const setProtectedAlarmControlPanelMode = async (
(mode === "disarmed" && stateObj.attributes.code_format)
) {
const entry = await getExtendedEntityRegistryEntry(
hass.callWS,
callWS,
stateObj.entity_id
).catch(() => undefined);
const defaultCode = entry?.options?.alarm_control_panel?.default_code;
@@ -133,10 +136,10 @@ export const setProtectedAlarmControlPanelMode = async (
const response = await showEnterCodeDialog(element, {
codeFormat: stateObj.attributes.code_format,
title: hass.localize(
title: localize(
`ui.card.alarm_control_panel.${disarm ? "disarm" : "arm"}`
),
submitText: hass.localize(
submitText: localize(
`ui.card.alarm_control_panel.${disarm ? "disarm" : "arm"}`
),
});
@@ -147,7 +150,7 @@ export const setProtectedAlarmControlPanelMode = async (
}
}
await hass.callService("alarm_control_panel", service, {
await callService("alarm_control_panel", service, {
entity_id: stateObj.entity_id,
code,
});
+51
View File
@@ -5,6 +5,9 @@ import {
} from "home-assistant-js-websocket";
import type { Store } from "home-assistant-js-websocket/dist/store";
import type { DataTableRowData } from "../components/data-table/ha-data-table";
import type { HomeAssistant } from "../types";
import type { ConfigEntry } from "./config_entries";
import type { DeviceRegistryEntry } from "./device/device_registry";
export interface BluetoothDeviceData extends DataTableRowData {
address: string;
@@ -74,6 +77,54 @@ export const isScannerStateMismatch = (state: BluetoothScannerState): boolean =>
state.requested_mode !== "auto" &&
state.current_mode !== state.requested_mode;
export interface BluetoothAdapterDevice {
device: DeviceRegistryEntry;
entry: ConfigEntry;
}
/**
* Splits the Bluetooth adapters into enabled and disabled ones. An adapter is
* a device with a Bluetooth connection that belongs to a `bluetooth` config
* entry. Config entries without such a device (for example ignored discoveries
* or removed proxies) are not adapters, unless they are disabled, so they can
* still be enabled again.
*/
export const getBluetoothAdapters = (
devices: HomeAssistant["devices"],
configEntries: ConfigEntry[]
) => {
const entryMap = new Map(configEntries.map((e) => [e.entry_id, e]));
const enabledDevices: BluetoothAdapterDevice[] = [];
const disabledDevices: BluetoothAdapterDevice[] = [];
const matchedEntryIds = new Set<string>();
for (const device of Object.values(devices)) {
const btConnection = device.connections.find((c) => c[0] === "bluetooth");
if (!btConnection) {
continue;
}
const entry = device.config_entries
.map((id) => entryMap.get(id))
.find((e) => e !== undefined);
if (!entry) {
continue;
}
matchedEntryIds.add(entry.entry_id);
if (entry.disabled_by !== null) {
disabledDevices.push({ device, entry });
} else {
enabledDevices.push({ device, entry });
}
}
const disabledEntriesWithoutDevice = configEntries.filter(
(e) => e.disabled_by !== null && !matchedEntryIds.has(e.entry_id)
);
return { enabledDevices, disabledDevices, disabledEntriesWithoutDevice };
};
export const subscribeBluetoothScannersDetailsUpdates = (
conn: Connection,
store: Store<BluetoothScannersDetails>
+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 = (
+20
View File
@@ -103,3 +103,23 @@ export const CLIMATE_HVAC_MODE_ICONS: Record<HvacMode, string> = {
export const climateHvacModeIcon = (mode: string) =>
CLIMATE_HVAC_MODE_ICONS[mode] || mdiThermostat;
export type ClimateTarget = "value" | "low" | "high";
/**
* The targets to change when one target is set. A low or high target that
* passes the other one pushes it along, so the range never ends up inverted.
*/
export const pushTargetTemperature = (
current: Partial<Record<ClimateTarget, number>>,
target: ClimateTarget,
value: number
): Partial<Record<ClimateTarget, number>> => {
if (target === "low" && current.high != null && value > current.high) {
return { low: value, high: value };
}
if (target === "high" && current.low != null && value < current.low) {
return { low: value, high: value };
}
return { [target]: value };
};
+6 -1
View File
@@ -158,7 +158,12 @@ export const computeNavigationPathInfo = (
const isDashboard = panel?.component_name === "lovelace";
const panelInfo: NavigationPathInfo = {
label: getPanelTitleFromUrlPath(options, panelUrlPath) || panelUrlPath,
label:
getPanelTitleFromUrlPath(
options.localize,
options.panels,
panelUrlPath
) || panelUrlPath,
icon: panelIcon || (isDashboard ? "mdi:view-dashboard" : undefined),
iconPath: panelIconPath || mdiLink,
};
+19 -5
View File
@@ -239,12 +239,29 @@ export interface CoverEntity extends HassEntityBase {
attributes: CoverEntityAttributes;
}
// For covers that report no value, the open or closed state tells where it is
const valueFromState = (stateObj: CoverEntity): number | undefined => {
if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
return undefined;
}
return stateObj.state === "closed" || stateObj.state === "opening" ? 0 : 100;
};
export const coverCurrentValue = (
stateObj: CoverEntity,
mode: CoverControlMode
): number | undefined => {
if (mode === "tilt") {
return stateObj.attributes.current_tilt_position ?? undefined;
const tilt = stateObj.attributes.current_tilt_position;
// The state only describes the slats when the cover can't move up or down
if (
tilt != null ||
coverSupportsTiltPosition(stateObj) ||
coverHasPositionControls(stateObj)
) {
return tilt ?? undefined;
}
return valueFromState(stateObj);
}
const position = stateObj.attributes.current_position;
if (
@@ -253,10 +270,7 @@ export const coverCurrentValue = (
) {
return position ?? undefined;
}
if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
return undefined;
}
return stateObj.state === "closed" || stateObj.state === "opening" ? 0 : 100;
return valueFromState(stateObj);
};
declare global {
+85 -3
View File
@@ -32,6 +32,7 @@ import type { EntityNameItem } from "../common/entity/entity_name_config";
import { formatNumberWithUnit } from "../common/number/format_number";
import { normalizeValueBySIPrefix } from "../common/number/normalize-by-si-prefix";
import { groupBy } from "../common/util/group-by";
import { generateUuidV4 } from "../common/util/uuid";
import type { HomeAssistant, HomeAssistantRegistries } from "../types";
import { fileDownload } from "../util/file_download";
import type {
@@ -343,6 +344,31 @@ export interface WaterSourceTypeEnergyPreference {
name?: string;
}
export type FixedCostType = "grid" | "gas" | "water";
export type FixedCostPeriod = "day" | "month" | "year";
export interface FixedCostEnergyPreference {
id: string;
type: FixedCostType;
name: string;
// Charged at the start of each period, exactly one of these is set
number_amount: number | null;
entity_amount: string | null;
period: FixedCostPeriod;
}
export const emptyFixedCostEnergyPreference = (
type: FixedCostType
): FixedCostEnergyPreference => ({
id: generateUuidV4(),
type,
name: "",
number_amount: null,
entity_amount: null,
period: "day",
});
export type EnergySource =
| SolarSourceTypeEnergyPreference
| HomeSourceTypeEnergyPreference
@@ -356,6 +382,7 @@ export interface EnergyPreferences {
device_consumption: DeviceConsumptionEnergyPreference[];
device_consumption_water: DeviceConsumptionEnergyPreference[];
device_consumption_gas: DeviceConsumptionEnergyPreference[];
fixed_costs: FixedCostEnergyPreference[];
}
export const EMPTY_PREFERENCES: EnergyPreferences = {
@@ -363,10 +390,13 @@ export const EMPTY_PREFERENCES: EnergyPreferences = {
device_consumption: [],
device_consumption_water: [],
device_consumption_gas: [],
fixed_costs: [],
};
export interface EnergyInfo {
cost_sensors: Record<string, string>;
// Fixed cost id to the entity ID of its cost sensor
fixed_cost_sensors: Record<string, string>;
solar_forecast_domains: string[];
}
@@ -381,6 +411,7 @@ export interface EnergyPreferencesValidation {
device_consumption: EnergyValidationIssue[][];
device_consumption_water: EnergyValidationIssue[][];
device_consumption_gas: EnergyValidationIssue[][];
fixed_costs: EnergyValidationIssue[][];
}
export const getEnergyInfo = (callWS: HomeAssistant["callWS"]) =>
@@ -443,6 +474,30 @@ export interface EnergySourceByType {
export const energySourcesByType = (prefs: EnergyPreferences) =>
groupBy(prefs.energy_sources, (item) => item.type) as EnergySourceByType;
export type FixedCostsByType = Partial<
Record<FixedCostType, FixedCostEnergyPreference[]>
>;
export const fixedCostsByType = (prefs: EnergyPreferences) =>
groupBy(prefs.fixed_costs, (item) => item.type) as FixedCostsByType;
/** Sum of the fixed costs, or undefined without cost data. */
export const calculateFixedCostTotal = (
fixedCosts: FixedCostEnergyPreference[],
info: EnergyInfo,
stats: Statistics
): number | undefined => {
let total: number | undefined;
for (const fixedCost of fixedCosts) {
const statId = info.fixed_cost_sensors[fixedCost.id];
const cost = statId ? calculateStatisticSumGrowth(stats[statId]) : null;
if (cost !== null) {
total = (total ?? 0) + cost;
}
}
return total;
};
/** Import cost minus export compensation, or undefined without cost data. */
export const calculateGridNetCost = (
sources: GridSourceTypeEnergyPreference[],
@@ -567,7 +622,9 @@ export const computeEnergyStatisticArea = (
* device in the same list, which happens when one device has several meters of
* the same type. Those are named with the entity name as well, so they stay
* apart in the charts. Lists hold one type of device, so an energy meter and a
* water meter of one device never collide.
* water meter of one device never collide. Separate devices that only share
* a name keep their label when their entity names match too, since adding
* those would not tell them apart, unless a custom name takes the same label.
*/
export const computeAmbiguousEnergyDevices = (
states: HomeAssistant["states"],
@@ -606,8 +663,14 @@ export const computeAmbiguousEnergyDevices = (
const ambiguous = new Set<string>();
for (const statisticIds of statisticIdsByLabel.values()) {
if (statisticIds.size > 1) {
for (const statisticId of statisticIds) {
if (!named.has(statisticId)) {
const unnamed = [...statisticIds].filter((id) => !named.has(id));
const entityLabels = new Set(
unnamed.map((statisticId) =>
formatEntityName(states[statisticId], ENERGY_DEVICE_ENTITY_NAME)
)
);
if (unnamed.length < statisticIds.size || entityLabels.size > 1) {
for (const statisticId of unnamed) {
ambiguous.add(statisticId);
}
}
@@ -750,6 +813,15 @@ export const getReferencedStatisticIds = (
...prefs.device_consumption_gas.map((d) => d.stat_consumption)
);
}
for (const fixedCost of prefs.fixed_costs) {
if (includeTypes && !includeTypes.includes(fixedCost.type)) {
continue;
}
const costStatId = info.fixed_cost_sensors[fixedCost.id];
if (costStatId) {
statIDs.push(costStatId);
}
}
return statIDs;
};
@@ -2583,6 +2655,9 @@ export const formatFlowRateShort = (
export type WaterGasResource = "water" | "gas";
/** The device categories the device graphs can show. */
export type DeviceConsumptionResource = "electricity" | "gas";
export const getWaterGasDevicesKey = (resource: WaterGasResource) =>
`device_consumption_${resource}` as const;
@@ -2930,6 +3005,13 @@ export const downloadEnergyData = (
printCategory("device_consumption_gas", gasDevices, state.gasUnit);
}
energyData.prefs.fixed_costs.forEach((fixedCost) => {
const costId = state.info.fixed_cost_sensors[fixedCost.id];
if (costId) {
processStat(costId, `${fixedCost.type}_fixed_cost`, currency);
}
});
const { summedData } = getSummedData(state);
const { consumption } = computeConsumptionData(summedData, undefined);
+10 -4
View File
@@ -153,17 +153,23 @@ export const computeEnergySuggestions = (
};
/**
* The dismissed statistics with the new one added, dropping statistics that
* The dismissed statistics with the new ones added, dropping statistics that
* no longer exist.
*/
export const updateDismissedSuggestions = (
dismissed: string[],
statisticId: string,
statisticIds: string[],
statistics: StatisticsMetaData[]
): string[] => {
const existing = new Set(statistics.map((meta) => meta.statistic_id));
return [
...dismissed.filter((id) => id !== statisticId && existing.has(id)),
statisticId,
...dismissed.filter((id) => !statisticIds.includes(id) && existing.has(id)),
...statisticIds,
];
};
/** The dismissed statistics without the restored one. */
export const restoreDismissedSuggestion = (
dismissed: string[],
statisticId: string
): string[] => dismissed.filter((id) => id !== statisticId);
+4
View File
@@ -77,6 +77,10 @@ export const filterGroupsWithListedMembers = (
): string[] => {
const listed = new Set(entityIds);
const hasListedDescendant = (groupId: string): boolean => {
const groupObj = states[groupId];
if (!groupObj || !computeGroupMemberIds(groupObj)) {
return false;
}
const seen = new Set([groupId]);
const queue = [groupId];
while (queue.length) {
+30 -2
View File
@@ -250,13 +250,16 @@ export type IconCategory =
| "services"
| "triggers"
| "conditions"
| "integration_category";
| "integration_category"
| "integration_connectivity";
export type IntegrationCategoryIcons = Record<
string,
{ default: string; subcategory?: Record<string, { default: string }> }
>;
export type IntegrationConnectivityIcons = Record<string, { default: string }>;
interface CategoryType {
entity: PlatformIcons;
entity_component: ComponentIcons;
@@ -264,6 +267,7 @@ interface CategoryType {
triggers: TriggerIcons;
conditions: ConditionIcons;
integration_category: IntegrationCategoryIcons;
integration_connectivity: IntegrationConnectivityIcons;
}
export const getHassIcons = async <T extends IconCategory>(
@@ -334,7 +338,10 @@ export const getComponentIcons = async (
export const getCategoryIcons = async <
T extends Exclude<
IconCategory,
"entity" | "entity_component" | "integration_category"
| "entity"
| "entity_component"
| "integration_category"
| "integration_connectivity"
>,
>(
connection: Connection,
@@ -775,3 +782,24 @@ export const getIntegrationCategoryIcons = async (
return undefined;
}
};
let integrationConnectivityIcons:
ReturnType<typeof getHassIcons<"integration_connectivity">> | undefined;
export const getIntegrationConnectivityIcons = async (
connection: Connection
): Promise<IntegrationConnectivityIcons | undefined> => {
// Cache the request itself, so callers while it loads share it
integrationConnectivityIcons ??= getHassIcons(
connection,
"integration_connectivity",
"homeassistant"
);
try {
const result = await integrationConnectivityIcons;
return result.resources.homeassistant;
} catch (_err) {
integrationConnectivityIcons = undefined;
return undefined;
}
};
+15
View File
@@ -0,0 +1,15 @@
import type { LocalizeFunc } from "../common/translations/localize";
import type { IntegrationConnectivityIcons } from "./icons";
// The name of a connectivity, like `zigbee`. Empty for one this Home Assistant
// doesn't know.
export const integrationConnectivityName = (
localize: LocalizeFunc,
slug: string
): string =>
localize(`component.homeassistant.integration_connectivity.${slug}.name`);
export const integrationConnectivityIcon = (
icons: IntegrationConnectivityIcons | undefined,
slug: string
): string | undefined => icons?.[slug]?.default;
+3
View File
@@ -10,6 +10,9 @@ export interface RepositoryBase {
can_install: boolean;
category: RepositoryType;
config_flow: boolean;
// How an integration connects, like `zigbee` or `cloud`. Empty for other
// repositories and for integrations that don't set it.
connectivity?: string[];
custom: boolean;
description: string;
domain: string | null;
+2 -2
View File
@@ -62,14 +62,14 @@ export const formatOpenStreetMapPlace = (
export const searchPlaces = (
address: string,
hass: HomeAssistant,
language: string,
addressdetails?: boolean,
limit?: number
): Promise<OpenStreetMapPlace[]> => {
const params = new URLSearchParams({
q: address,
format: "jsonv2",
"accept-language": hass.locale.language,
"accept-language": language,
email: "[email protected]",
});
if (limit) {
+27 -8
View File
@@ -8,9 +8,12 @@ import {
mdiMap,
mdiPlayBoxMultiple,
} from "@mdi/js";
import type { LocalizeKeys } from "../common/translations/localize";
import type {
LocalizeFunc,
LocalizeKeys,
} from "../common/translations/localize";
import type { PageNavigation } from "../layouts/hass-tabs-subpage";
import type { HomeAssistant, PanelInfo } from "../types";
import type { HomeAssistant, PanelInfo, Panels } from "../types";
import { MARKETPLACE_NAME } from "../common/translations/name-placeholders";
export const APP_PANEL = "app";
@@ -66,7 +69,7 @@ export const getPanelNameTranslationKey = (panel: PanelInfo) => {
};
export const getPanelTitle = (
hass: Pick<HomeAssistant, "localize">,
localize: LocalizeFunc,
panel: PanelInfo
): string | undefined => {
if (panel.url_path === "marketplace") {
@@ -75,18 +78,19 @@ export const getPanelTitle = (
const translationKey = getPanelNameTranslationKey(panel);
return hass.localize(translationKey) || panel.title || undefined;
return localize(translationKey) || panel.title || undefined;
};
export const getPanelTitleFromUrlPath = (
hass: Pick<HomeAssistant, "localize" | "panels">,
localize: LocalizeFunc,
panels: Panels,
urlPath: string
): string | undefined => {
if (!hass.panels) {
if (!panels) {
return undefined;
}
const panel = Object.values(hass.panels).find(
const panel = Object.values(panels).find(
(p: PanelInfo): boolean => p.url_path === urlPath
);
@@ -94,7 +98,7 @@ export const getPanelTitleFromUrlPath = (
return undefined;
}
return getPanelTitle(hass, panel);
return getPanelTitle(localize, panel);
};
/**
@@ -196,6 +200,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;
+1 -1
View File
@@ -57,7 +57,7 @@ const generateNavigationPanelCommands = (
.map(([_panelKey, panel]) => {
const icon = getPanelIcon(panel) || "mdi:view-dashboard";
const primary = getPanelTitle({ localize }, panel) || panel.url_path;
const primary = getPanelTitle(localize, panel) || panel.url_path;
const panelApp = apps?.find(({ slug }) => slug === panel.url_path);
+33
View File
@@ -89,6 +89,7 @@ export type Selector =
| UiActionSelector
| UiClockDateFormatSelector
| UiColorSelector
| UiConditionSelector
| UiStateContentSelector
| UiTimeFormatSelector
| UnitOfMeasurementSelector
@@ -203,6 +204,11 @@ export interface ConditionSelector {
} | null;
}
/** Dashboard conditions, edited like a card's visibility tab. */
export interface UiConditionSelector {
ui_condition: {} | null;
}
export interface ConversationAgentSelector {
conversation_agent: { language?: string } | null;
}
@@ -307,6 +313,7 @@ export interface EntitySelectorFilter {
device_class?: string | readonly string[];
supported_features?: number | [number];
unit_of_measurement?: string | readonly string[];
capabilities?: Record<string, readonly (string | readonly string[])[]>;
}
interface EntitySelectorEntityFilter extends EntitySelectorFilter {
@@ -1112,6 +1119,26 @@ export const filterSelectorDevices = (
return true;
};
const matchesCapabilities = (
entity: HassEntity,
capabilities: NonNullable<EntitySelectorFilter["capabilities"]>
): boolean => {
for (const [capability, alternatives] of Object.entries(capabilities)) {
const value = entity.attributes[capability];
if (value == null) {
return false;
}
const entityValues: unknown[] = Array.isArray(value) ? value : [value];
const matches = alternatives.some((required) =>
ensureArray(required).every((item) => entityValues.includes(item))
);
if (!matches) {
return false;
}
}
return true;
};
export const filterSelectorEntities = (
filterEntity: EntitySelectorEntityFilter,
entity: HassEntity,
@@ -1125,6 +1152,7 @@ export const filterSelectorEntities = (
device_class: filterDeviceClass,
supported_features: filterSupportedFeature,
unit_of_measurement: filterUnitOfMeasurement,
capabilities: filterCapabilities,
integration: filterIntegration,
device: filterDevice,
} = filterEntity;
@@ -1173,6 +1201,10 @@ export const filterSelectorEntities = (
}
}
if (filterCapabilities && !matchesCapabilities(entity, filterCapabilities)) {
return false;
}
if (filterDevice) {
if (!entityRegistry || !devices) {
return false;
@@ -1279,6 +1311,7 @@ export const computeCreateDomains = (
!entityFilter.integration &&
!entityFilter.device_class &&
!entityFilter.supported_features &&
!entityFilter.capabilities &&
!entityFilter.device &&
entityFilter.domain
? ensureArray(entityFilter.domain).filter((domain) =>
+2
View File
@@ -223,6 +223,7 @@ export const SENSOR_DEVICE_CLASS_UNITS: Record<string, (string | null)[]> = {
voltage: ["kV", "MV", "mV", "V", "μV"],
volume: ["CCF", "fl. oz.", "ft³", "gal", "L", "MCF", "mL", "m³"],
volume_flow_rate: [
"ft³/h",
"ft³/min",
"gal/d",
"gal/h",
@@ -399,6 +400,7 @@ export const SENSOR_DEVICE_CLASS_CONVERTIBLE_UNITS: Record<
voltage: ["kV", "MV", "mV", "V", "μV"],
volume: ["CCF", "fl. oz.", "ft³", "gal", "L", "MCF", "mL", "m³"],
volume_flow_rate: [
"ft³/h",
"ft³/min",
"gal/d",
"gal/h",
+2 -1
View File
@@ -77,7 +77,8 @@ export type TranslationCategory =
| "services"
| "triggers"
| "conditions"
| "integration_category";
| "integration_category"
| "integration_connectivity";
export const subscribeTranslationPreferences = (
hass: HomeAssistant,
+11
View File
@@ -4,9 +4,11 @@ import type {
HassEntityBase,
HassEvent,
} from "home-assistant-js-websocket";
import memoizeOne from "memoize-one";
import { BINARY_STATE_OFF, BINARY_STATE_ON } from "../common/const";
import { computeDomain } from "../common/entity/compute_domain";
import { computeStateDomain } from "../common/entity/compute_state_domain";
import { getEntityIds } from "../common/entity/get_entity_ids";
import { supportsFeature } from "../common/entity/supports-feature";
import { formatNumber } from "../common/number/format_number";
import { caseInsensitiveStringCompare } from "../common/string/compare";
@@ -152,6 +154,15 @@ export const filterUpdateEntities = (
);
});
const findUpdateEntityIds = memoizeOne((entityIds: string[]) =>
entityIds.filter((entityId) => computeDomain(entityId) === "update")
);
export const countInstallableUpdates = (states: HassEntities): number =>
findUpdateEntityIds(getEntityIds(states)).filter((entityId) =>
updateCanInstall(states[entityId] as UpdateEntity)
).length;
export const filterUpdateEntitiesParameterized = (
entities: HassEntities,
formatEntityName: HomeAssistant["formatEntityName"],
@@ -3,8 +3,11 @@ import {
mdiImageMultipleOutline,
mdiLightningBolt,
} from "@mdi/js";
import type { ContextType } from "@lit/context";
import { css, html, LitElement, nothing } from "lit";
import { customElement, state } from "lit/decorators";
import { isComponentLoaded } from "../../common/config/is_component_loaded";
import { consume } from "../../common/decorators/consume";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../common/translations/localize";
import { CAMERA_STREAM_TYPE_NAMES } from "../../components/camera/ha-camera-stream-badge";
@@ -21,9 +24,14 @@ import {
type CameraStreamType,
type StreamType,
} from "../../data/camera-streams";
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 }[] = [
@@ -40,11 +48,56 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
@consumeLocalize()
private _localize!: LocalizeFunc;
@consume({ context: apiContext })
private _api!: ContextType<typeof apiContext>;
@consume({ context: configContext })
private _hassConfig!: ContextType<typeof configContext>;
@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();
}
// The same check that core uses to add the cloud TURN servers
private async _fetchCloudIceServers() {
if (!isComponentLoaded(this._hassConfig.config, "cloud")) {
return;
}
try {
const status = await fetchCloudStatus(this._api.callWS);
this._cloudIceServers =
status.logged_in &&
status.active_subscription &&
status.prefs.cloud_ice_servers_enabled;
} catch (_err) {
// Without the cloud status the label stays hidden
}
}
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
@@ -73,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">
@@ -112,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`
@@ -124,6 +193,18 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
wrap-supporting-text
>
<ha-svg-icon slot="start" .path=${icon}></ha-svg-icon>
${
type === STREAM_TYPE_WEB_RTC && this._cloudIceServers
? html`<span slot="headline" class="headline">
${CAMERA_STREAM_TYPE_NAMES[type]}
<span class="tag cloud"
>${this._localize(
"ui.dialogs.camera_stream_info.enhanced_by_cloud"
)}</span
>
</span>`
: nothing
}
${
current
? html`<span slot="end" class="tag current"
@@ -188,6 +269,20 @@ class DialogCameraStreamInfo extends DialogMixin<CameraStreamInfoDialogParams>(
color: var(--secondary-text-color);
}
.headline {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--ha-space-2);
/* The row keeps the headline on one line, but a long tag must wrap */
white-space: normal;
}
.tag.cloud {
background-color: var(--ha-color-fill-primary-quiet-resting);
color: var(--ha-color-on-primary-quiet);
}
.tag.current {
background-color: var(--ha-color-fill-success-quiet-resting);
color: var(--ha-color-on-success-quiet);
@@ -1,12 +1,17 @@
import { fireEvent } from "../../common/dom/fire_event";
import type { CameraStreamStatus, StreamType } from "../../data/camera-streams";
export interface CameraStreamInfoDialogParams {
export interface CameraStreamInfo {
status: CameraStreamStatus;
/** The stream types the camera supports, undefined while unknown */
supportedTypes?: StreamType[];
}
export interface CameraStreamInfoDialogParams {
/** Calls back with the current info right away and on every change */
subscribe: (callback: (info: CameraStreamInfo) => void) => () => void;
}
export const showCameraStreamInfoDialog = (
element: HTMLElement,
params: CameraStreamInfoDialogParams
+1 -1
View File
@@ -46,7 +46,7 @@ export const DOMAINS_WITH_NEW_MORE_INFO = [
"media_player",
];
/** Domains with full height more info dialog */
export const DOMAINS_FULL_HEIGHT_MORE_INFO = ["update"];
export const DOMAINS_FULL_HEIGHT_MORE_INFO = ["camera", "update"];
/** Domains with separate more info dialog. */
export const DOMAINS_WITH_MORE_INFO = [
@@ -31,11 +31,9 @@ class MoreInfoAlarmControlPanel extends LitElement {
private async _disarm() {
setProtectedAlarmControlPanelMode(
this,
{
callService: this._api.callService,
callWS: this._api.callWS,
localize: this._localize,
},
this._api.callService,
this._api.callWS,
this._localize,
this.stateObj!,
"disarmed"
);
@@ -9,6 +9,10 @@ import { consumeLocalize } from "../../../common/decorators/consume-context-entr
import type { HASSDomEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import type { LocalizeFunc } from "../../../common/translations/localize";
import {
adaptiveDialogModeContext,
type DialogSheetMode,
} from "../../../components/ha-adaptive-dialog";
import "../../../components/ha-button";
import "../../../components/camera/ha-camera-player";
import type { HaCameraPlayer } from "../../../components/camera/ha-camera-player";
@@ -50,6 +54,10 @@ class MoreInfoCamera extends LitElement {
@state() private _attached = false;
@state()
@consume({ context: adaptiveDialogModeContext, subscribe: true })
private _dialogMode?: DialogSheetMode;
@state() private _microphoneState: WebRtcMicrophoneState = "off";
@state() private _streamType?: CameraStreamType;
@@ -133,6 +141,7 @@ class MoreInfoCamera extends LitElement {
.stateObj=${this.stateObj}
allow-exoplayer
keep-awake
?fill=${this._dialogMode === "bottom-sheet"}
@microphone-changed=${this._microphoneChanged}
@stream-type-changed=${this._streamTypeChanged}
@camera-capabilities-changed=${this._capabilitiesChanged}
@@ -315,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(
@@ -334,7 +347,9 @@ class MoreInfoCamera extends LitElement {
static styles = css`
:host {
display: block;
display: flex;
flex-direction: column;
flex: 1;
}
.buttons {
@@ -22,7 +22,6 @@ import {
coverHasPositionControls,
coverHasTiltControls,
coverModeAttribute,
coverSupportsPosition,
coverSupportsSetValue,
defaultCoverMode,
} from "../../../data/cover";
@@ -164,7 +163,7 @@ class MoreInfoCover extends LitElement {
if (!request || this._drag) {
return undefined;
}
if (request.mode === "position" && !coverSupportsPosition(this.stateObj!)) {
if (!coverSupportsSetValue(this.stateObj!, request.mode)) {
return this._hint(request.value ? "requested_open" : "requested_closed");
}
return this._hint("requested", {
@@ -2,6 +2,8 @@ import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { consume } from "../../../common/decorators/consume";
import { transform } from "../../../common/decorators/transform";
import type { HASSDomCurrentTargetEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
import { connectionContext, formattersContext } from "../../../data/context";
import type { ImageEntity } from "../../../data/image";
import { computeImageUrl } from "../../../data/image";
@@ -28,6 +30,17 @@ class MoreInfoImage extends LitElement {
@property({ attribute: false }) public stateObj?: ImageEntity;
private _size?: HASSDomEvents["media-size-changed"];
public connectedCallback() {
super.connectedCallback();
// A cached view that was detached while the picture loaded couldn't send
// its size, and the picture doesn't load again when it's shown
if (this._size) {
fireEvent(this, "media-size-changed", this._size);
}
}
protected render() {
if (!this._connection || !this.stateObj) {
return nothing;
@@ -39,16 +52,28 @@ class MoreInfoImage extends LitElement {
return html`<img
alt=${this._formatEntityName?.(this.stateObj) || this.stateObj.entity_id}
src=${this._connection.hassUrl(imageUrl)}
@load=${this._imageLoaded}
/> `;
}
private _imageLoaded(ev: HASSDomCurrentTargetEvent<HTMLImageElement>) {
const { naturalWidth, naturalHeight } = ev.currentTarget;
if (!naturalWidth || !naturalHeight) {
return;
}
this._size = { aspectRatio: naturalWidth / naturalHeight, naturalWidth };
fireEvent(this, "media-size-changed", this._size);
}
static styles = css`
:host {
display: block;
text-align: center;
}
img {
display: block;
margin: 0 auto;
max-width: 100%;
max-height: var(--more-info-media-max-height, none);
}
`;
}
@@ -1,5 +1,6 @@
import type { ContextType } from "@lit/context";
import type { HassConfig, UnsubscribeFunc } from "home-assistant-js-websocket";
import { ERR_CONNECTION_LOST } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
@@ -456,6 +457,11 @@ class MoreInfoUpdate extends LitElement {
false
);
} catch (err: any) {
// The update keeps running when the connection drops during a long install.
if (err?.error?.code === ERR_CONNECTION_LOST) {
return;
}
const message = await this._localizeInstallError(err);
if (this._isShown()) {
@@ -620,15 +620,14 @@ class MoreInfoWeather extends LitElement {
}
.temp-attribute .temp {
position: relative;
margin-right: var(--ha-space-6);
direction: ltr;
}
.temp-attribute .temp span {
position: absolute;
position: relative;
font-size: var(--ha-font-size-2xl);
top: 1px;
vertical-align: top;
}
.state,
+104 -49
View File
@@ -7,6 +7,7 @@ import {
mdiCogOutline,
mdiContentDuplicate,
mdiDevices,
mdiDirections,
mdiDotsVertical,
mdiDownload,
mdiInformationOutline,
@@ -37,6 +38,8 @@ import {
computeEntityNameParts,
type EntityNameType,
} from "../../common/entity/compute_entity_name_display";
import { getEntityLocation } from "../../common/entity/get_entity_location";
import { navigationUrl } from "../../common/map/navigation-url";
import {
getHistoryState,
navigate,
@@ -149,10 +152,12 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
@property({ type: Boolean, reflect: true }) public large = false;
@state() private _fill = false;
// The dialog grows with the camera's or image's picture, as high as there
// is room for
@state() private _mediaAspectRatio?: number;
// The dialog grows with the camera's picture, as high as there is room for
@state() private _cameraAspectRatio?: number;
// An image is not shown larger than it is
@state() private _mediaNaturalWidth?: number;
// Height of the controls the camera's info shows below the picture
@state() private _cameraControlsHeight?: string;
@@ -196,12 +201,6 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
}
public showDialog(params: MoreInfoDialogParams) {
// The camera player keeps running for the same entity and doesn't send
// its size again
if (params.entityId !== this._entityId) {
this._cameraAspectRatio = undefined;
this._cameraControlsHeight = undefined;
}
this._entityId = params.entityId;
if (!this._entityId) {
this.closeDialog();
@@ -219,7 +218,6 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._detailsYamlMode = false;
this.large = params.large ?? false;
this._fill = false;
this._open = true;
this._loadEntityRegistryEntry();
}
@@ -265,8 +263,6 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._currView = DEFAULT_VIEW;
this._childViewStack = [];
this._returnUrl = undefined;
this._cameraAspectRatio = undefined;
this._cameraControlsHeight = undefined;
this._isEscapeEnabled = true;
window.removeEventListener("dialog-closed", this._enableEscapeKeyClose);
window.removeEventListener("show-dialog", this._disableEscapeKeyClose);
@@ -511,11 +507,29 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
case "download_snapshot":
this._downloadSnapshot();
break;
case "directions":
this._openDirections();
break;
default:
break;
}
}
private _openDirections() {
const stateObj = this._entityId
? (this.hass.states[this._entityId] as HassEntity | undefined)
: undefined;
const location = stateObj && getEntityLocation(stateObj, this.hass.states);
if (!location) {
return;
}
window.open(
navigationUrl(location.latitude, location.longitude),
"_blank",
"noreferrer"
);
}
private async _resetFavorites() {
const favoritesContext = this._getFavoritesContext();
@@ -639,6 +653,16 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
</ha-dropdown-item>
`
: nothing;
const hasLocation =
!!stateObj && !!getEntityLocation(stateObj, this.hass.states);
const directionsMenuItem = hasLocation
? html`
<ha-dropdown-item value="directions">
<ha-svg-icon slot="icon" .path=${mdiDirections}></ha-svg-icon>
${this.hass.localize("ui.dialogs.more_info_control.directions")}
</ha-dropdown-item>
`
: nothing;
const viewTitle = this._computeViewTitle();
const defaultTitle = breadcrumb[breadcrumb.length - 1] || entityId;
if (!viewTitle) {
@@ -691,30 +715,32 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
`
: nothing;
// Also when the camera was opened from a smaller entity's related view
const cameraAspectRatio =
domain === "camera" && isDefaultView
? this._cameraAspectRatio
// Also when it was opened from a smaller entity's related view
const mediaAspectRatio =
(domain === "camera" || domain === "image") && isDefaultView
? this._mediaAspectRatio
: undefined;
// As wide as the picture is when it's as high as there is room for
const fullHeightWidth = `var(--more-info-media-max-height) * ${mediaAspectRatio}`;
const mediaPictureWidth = this._mediaNaturalWidth
? `min(${fullHeightWidth}, ${this._mediaNaturalWidth}px)`
: fullHeightWidth;
return html`
<ha-adaptive-dialog
.open=${this._open}
.width=${
this._fill
? "full"
: this.large || cameraAspectRatio
? "large"
: "medium"
}
class=${classMap({ camera: domain === "camera" })}
.width=${this.large || mediaAspectRatio ? "large" : "medium"}
class=${classMap({
camera: domain === "camera",
image: domain === "image",
})}
style=${styleMap({
"--more-info-camera-controls-height": this._cameraControlsHeight,
"--ha-dialog-width-lg": cameraAspectRatio
? `clamp(var(--ha-dialog-width-md, 580px), calc(var(--video-max-height) * ${cameraAspectRatio}), 1920px)`
"--ha-dialog-width-lg": mediaAspectRatio
? `clamp(var(--ha-dialog-width-md, 580px), calc(${mediaPictureWidth} + var(--more-info-media-inline-padding, 0px)), 1920px)`
: undefined,
})}
@camera-aspect-ratio-changed=${this._cameraAspectRatioChanged}
@media-size-changed=${this._mediaSizeChanged}
@camera-controls-height-changed=${this._cameraControlsHeightChanged}
.accessibleLabel=${title}
@closed=${this._dialogClosed}
@@ -747,7 +773,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
></ha-icon-button-prev>
`
}
<span slot="headerTitle" @click=${this._enlarge} class="title">
<span slot="headerTitle" class="title">
${
breadcrumb.length > 0
? !__DEMO__ && isAdmin
@@ -806,9 +832,10 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
></ha-icon-button>
${
domain === "camera"
domain === "camera" || hasLocation
? html`
${downloadSnapshotMenuItem}
${directionsMenuItem}
<wa-divider></wa-divider>
`
: nothing
@@ -945,7 +972,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
: nothing
}
${
domain === "camera"
domain === "camera" || hasLocation
? html`
<ha-dropdown
slot="headerActionItems"
@@ -961,6 +988,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
.path=${mdiDotsVertical}
></ha-icon-button>
${downloadSnapshotMenuItem}
${directionsMenuItem}
</ha-dropdown>
`
: nothing
@@ -1071,6 +1099,17 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
`;
}
protected willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
// Also when going to a related entity or back. The camera player or image
// of the same entity keeps running and doesn't send its size again.
if (changedProps.has("_entityId")) {
this._mediaAspectRatio = undefined;
this._mediaNaturalWidth = undefined;
this._cameraControlsHeight = undefined;
}
}
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
this.addEventListener("close-dialog", () => this.closeDialog());
@@ -1140,10 +1179,11 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._entry = ev.detail;
}
private _cameraAspectRatioChanged(
ev: HASSDomEvent<HASSDomEvents["camera-aspect-ratio-changed"]>
private _mediaSizeChanged(
ev: HASSDomEvent<HASSDomEvents["media-size-changed"]>
) {
this._cameraAspectRatio = ev.detail.aspectRatio;
this._mediaAspectRatio = ev.detail.aspectRatio;
this._mediaNaturalWidth = ev.detail.naturalWidth;
}
private _cameraControlsHeightChanged(
@@ -1152,12 +1192,6 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._cameraControlsHeight = ev.detail.height;
}
private _enlarge() {
withViewTransition(() => {
this._fill = !this._fill;
});
}
private _handleOpened() {
window.addEventListener("dialog-closed", this._enableEscapeKeyClose);
window.addEventListener("show-dialog", this._disableEscapeKeyClose);
@@ -1216,12 +1250,14 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
--dialog-content-padding: 0;
}
/* The dialog's margin, its header of about 68px and the controls
below the picture */
ha-adaptive-dialog.camera {
--video-max-height: calc(
100vh - var(--ha-space-20) -
68px - var(--more-info-camera-controls-height, 0px)
/* The dialog's margin, the safe area like the dialog's height limit,
its header of about 68px and what the info shows besides the
picture */
ha-adaptive-dialog.camera,
ha-adaptive-dialog.image {
--more-info-media-max-height: calc(
100vh - var(--ha-space-20) - var(--safe-area-inset-y, 0px) -
68px - var(--more-info-media-reserved-height, 0px)
);
/* Along with the height of the picture */
--ha-dialog-width-transition:
@@ -1232,14 +1268,33 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
/* A custom property takes any value, so it can't fall back to the
declaration before it. svh like the height limit of the dialog. */
@supports (height: 1svh) {
ha-adaptive-dialog.camera {
--video-max-height: calc(
100svh - var(--ha-space-20) -
68px - var(--more-info-camera-controls-height, 0px)
ha-adaptive-dialog.camera,
ha-adaptive-dialog.image {
--more-info-media-max-height: calc(
100svh - var(--ha-space-20) - var(--safe-area-inset-y, 0px) -
68px - var(--more-info-media-reserved-height, 0px)
);
}
}
ha-adaptive-dialog.camera {
--more-info-media-reserved-height: var(
--more-info-camera-controls-height,
0px
);
--video-max-height: var(--more-info-media-max-height);
}
/* The info's padding around the picture and the entity's row of 40px
above it, with 16px between them */
ha-adaptive-dialog.image {
--more-info-media-reserved-height: calc(
var(--ha-space-6) +
max(var(--safe-area-inset-bottom, 0px), var(--ha-space-6)) + 56px
);
--more-info-media-inline-padding: calc(var(--ha-space-6) * 2);
}
.content-wrapper {
flex: 1 1 auto;
min-height: 0;
+32 -118
View File
@@ -13,7 +13,6 @@ import { fireEvent } from "../../common/dom/fire_event";
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
import "../../components/animation/ha-fade-in";
import "../../components/ha-adaptive-dialog";
import "../../components/ha-alert";
import "../../components/ha-expansion-panel";
import "../../components/ha-icon-next";
import "../../components/ha-spinner";
@@ -21,10 +20,6 @@ import "../../components/item/ha-list-item-button";
import type { HaListItemButton } from "../../components/item/ha-list-item-button";
import "../../components/list/ha-list-base";
import "../../components/progress/ha-progress-bar";
import {
getBackupState,
type BackupManagerState,
} from "../../data/backup_manager";
import {
extractApiErrorMessage,
ignoreSupervisorError,
@@ -36,14 +31,14 @@ import {
shutdownHost,
} from "../../data/hassio/host";
import { haStyle, haStyleDialog } from "../../resources/styles";
import type { HomeAssistant, ServiceCallRequest } from "../../types";
import type { HomeAssistant } from "../../types";
import { HOST_ACTION_TOAST_ID, showToast } from "../../util/toast";
import { showAlertDialog } from "../generic/show-dialog-box";
import {
showAlertDialog,
showConfirmationDialog,
} from "../generic/show-dialog-box";
import { showRestartWaitDialog } from "./show-dialog-restart";
import "./automation-restart-status";
confirmRestartAction,
showRestartConfirmation,
type RestartAction,
} from "./show-restart-confirmation";
@customElement("dialog-restart")
class DialogRestart extends LitElement {
@@ -74,15 +69,6 @@ class DialogRestart extends LitElement {
}
}
private async _loadBackupState() {
try {
return await getBackupState(this.hass);
} catch (_err) {
// Do nothing
return "idle";
}
}
private async _loadHostInfo() {
this._loadingHostInfo = true;
try {
@@ -273,45 +259,16 @@ class DialogRestart extends LitElement {
duration: 1000,
});
this._restartAction(
"homeassistant",
"reload_all",
this.hass.localize("ui.dialogs.restart.reload.failed")
)();
}
private _getBackupProgressMessage(backupState: BackupManagerState) {
switch (backupState) {
case "create_backup":
return this.hass.localize("ui.dialogs.restart.backup_in_progress");
case "receive_backup":
return this.hass.localize("ui.dialogs.restart.upload_in_progress");
case "restore_backup":
return this.hass.localize("ui.dialogs.restart.restore_in_progress");
default:
return "";
try {
await this.hass.callService("homeassistant", "reload_all");
} catch (err: any) {
showAlertDialog(this, {
title: this.hass.localize("ui.dialogs.restart.reload.failed"),
text: err.message,
});
}
}
private _restartAction =
(
domain: ServiceCallRequest["domain"],
service: ServiceCallRequest["service"],
errorTitle: string,
serviceData?: ServiceCallRequest["serviceData"]
) =>
async () => {
try {
await this.hass.callService(domain, service, serviceData);
} catch (err: any) {
showAlertDialog(this, {
title: errorTitle,
text: err.message,
});
}
};
private _hostAction =
(toastMessage: string, action: "reboot" | "shutdown") => async () => {
showToast(this, {
@@ -343,75 +300,32 @@ class DialogRestart extends LitElement {
};
private async _handleAction(
ev: HASSDomCurrentTargetEvent<
HaListItemButton & {
action: "restart" | "reboot" | "shutdown" | "restart-safe-mode";
}
>
ev: HASSDomCurrentTargetEvent<HaListItemButton & { action: RestartAction }>
) {
if (this._loadingBackupInfo) {
return;
}
this._loadingBackupInfo = true;
const action = ev.currentTarget.action;
const backupState = await this._loadBackupState();
const backupProgressMessage = this._getBackupProgressMessage(backupState);
this._loadingBackupInfo = false;
const confirmed = await showConfirmationDialog(this, {
title: this.hass.localize(`ui.dialogs.restart.${action}.confirm_title`),
text: html`${this.hass.localize(
`ui.dialogs.restart.${action}.confirm_description`
)}${
backupProgressMessage
? html`<br /><br /><ha-alert>${backupProgressMessage}</ha-alert>`
: nothing
} <br /><br /><automation-restart-status></automation-restart-status>`,
confirmText: this.hass.localize(
`ui.dialogs.restart.${action}.confirm_action${backupState === "idle" ? "" : "_backup"}`
),
destructive: true,
});
if (!confirmed) {
return;
try {
const confirmed =
action === "restart" || action === "restart-safe-mode"
? await showRestartConfirmation(this, this.hass, action)
: await confirmRestartAction(
this,
this.hass,
action,
this._hostAction(
this.hass.localize(`ui.dialogs.restart.${action}.action_toast`),
action
)
);
if (confirmed) {
this._dialogOpen = false;
}
} finally {
this._loadingBackupInfo = false;
}
this._dialogOpen = false;
let actionFunc: () => Promise<void>;
if (["restart", "restart-safe-mode"].includes(action)) {
const serviceData =
action === "restart-safe-mode" ? { safe_mode: true } : undefined;
actionFunc = this._restartAction(
"homeassistant",
"restart",
this.hass.localize(`ui.dialogs.restart.${action}.failed`),
serviceData
);
} else {
actionFunc = this._hostAction(
this.hass.localize(
`ui.dialogs.restart.${action as "reboot" | "shutdown"}.action_toast`
),
action as "reboot" | "shutdown"
);
}
if (backupState !== "idle") {
showRestartWaitDialog(this, {
title: this.hass.localize(`ui.dialogs.restart.${action}.title`),
initialBackupState: backupState,
action: actionFunc,
});
return;
}
actionFunc();
}
static get styles(): CSSResultGroup {
@@ -0,0 +1,96 @@
import { html, nothing } from "lit";
import "../../components/ha-alert";
import {
getBackupState,
type BackupManagerState,
} from "../../data/backup_manager";
import type { HomeAssistant } from "../../types";
import {
showAlertDialog,
showConfirmationDialog,
} from "../generic/show-dialog-box";
import "./automation-restart-status";
import { showRestartWaitDialog } from "./show-dialog-restart";
export type RestartAction =
"restart" | "reboot" | "shutdown" | "restart-safe-mode";
type ConfirmationContext = Pick<HomeAssistant, "connection" | "localize">;
function getBackupProgressMessage(
localize: HomeAssistant["localize"],
backupState: BackupManagerState
) {
switch (backupState) {
case "create_backup":
return localize("ui.dialogs.restart.backup_in_progress");
case "receive_backup":
return localize("ui.dialogs.restart.upload_in_progress");
case "restore_backup":
return localize("ui.dialogs.restart.restore_in_progress");
default:
return "";
}
}
export async function confirmRestartAction(
element: HTMLElement,
hass: ConfirmationContext,
action: RestartAction,
run: () => Promise<void>
) {
const backupState = await getBackupState(hass).catch(() => "idle" as const);
const backupProgressMessage = getBackupProgressMessage(
hass.localize,
backupState
);
const confirmed = await showConfirmationDialog(element, {
title: hass.localize(`ui.dialogs.restart.${action}.confirm_title`),
text: html`${hass.localize(
`ui.dialogs.restart.${action}.confirm_description`
)}${
backupProgressMessage
? html`<br /><br /><ha-alert>${backupProgressMessage}</ha-alert>`
: nothing
} <br /><br /><automation-restart-status></automation-restart-status>`,
confirmText: hass.localize(
`ui.dialogs.restart.${action}.confirm_action${backupState === "idle" ? "" : "_backup"}`
),
destructive: true,
});
if (!confirmed) {
return false;
}
if (backupState !== "idle") {
showRestartWaitDialog(element, {
title: hass.localize(`ui.dialogs.restart.${action}.title`),
initialBackupState: backupState,
action: run,
});
} else {
run();
}
return true;
}
export function showRestartConfirmation(
element: HTMLElement,
hass: ConfirmationContext & Pick<HomeAssistant, "callService">,
action: "restart" | "restart-safe-mode" = "restart"
) {
return confirmRestartAction(element, hass, action, async () => {
try {
await hass.callService(
"homeassistant",
"restart",
action === "restart-safe-mode" ? { safe_mode: true } : undefined
);
} catch (err: any) {
showAlertDialog(element, {
title: hass.localize(`ui.dialogs.restart.${action}.failed`),
text: err.message,
});
}
});
}
Loaded 100 of 289 files, more files were not shown because too many files have changed in this diff. Show more