Compare commits

..
Author SHA1 Message Date
Paul Bottein 1388193811 Pass the form context to nested forms 2026-12-02 18:33:36 +01:00
Paul Bottein e96bca7bc2 Translate option descriptions in the select selector (#56369) 2026-12-02 17:57:22 +01:00
Petar Petrov f666f4c5f0 Migrate Lovelace hass-action leaves to contexts (#56367)
* Migrate Lovelace hass-action leaves to contexts

Badges, heading badges, button row, picture header and state-badge element consume contexts and fire hass-action instead of taking hass.

* Rerender the entity badge when the brands token changes

Brand pictures stay on the fallback icon until the token arrives.
2026-12-02 16:24:46 +00:00
Petar Petrov fddf0437a7 Drop hass from the generic entity row (#56365)
* Drop hass from the generic entity row

Rows that pass only config now read their state from the states context.

* Drop the fallback states subscription when a row gets its stateObj

Also remove the rendering test.
2026-12-02 16:24:36 +00:00
Petar Petrov d5880a2b1e Consume localize in selector-only card editors (#56368)
Drop hass and the ha-form hass binding from eight card editors.
2026-12-02 16:24:02 +00:00
WendelinandClaude Opus 5.5 f02cd4e686 Explain why an entity isn't available in the more info dialog (#56314)
* Explain in the more info dialog why an entity isn't available

An entity without a state only showed a one line warning, so the dialog
was one line tall and jumped once the entity came back. An entity its
integration doesn't provide showed greyed out controls and a warning to
delete it, also right after enabling it.

The info view now shows an empty state for these entities, with what
happened and what to do: enable the entity, open its device or
integration. For an integration that doesn't provide the entity, it
shows the setup state and error of the config entry, since when the
entity is unavailable and its last known state from the history.

renderConfigEntryError moves to its own file, so the more info dialog
doesn't load the integration page.

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

* Show the setup error of the integration only to admins

Other users can't act on it, and it can hold addresses and host names.

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

* Drop the minimum height of the unavailable view in the bottom sheet

The bottom sheet has a fixed height already, which is too low for it on a
phone in landscape. navigate() closes the dialog itself.

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

* Keep the registry entry of the more info dialog for its own entity

A lookup that finished after switching to another entity replaced the
entry, and any failed lookup counted as an unregistered entity, which the
info view now shows as not found. Only a not_found error does that now.

The restored state's last_changed is the last restart, so the view only
shows since when the entity is unavailable when the history tells it.

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

* Load the registry entry of the more info dialog again on reconnect

A lookup that failed for another reason than not_found, like a lost
connection, left the info view empty until the dialog was opened again.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-02 17:14:50 +01:00
Maarten Lakerveld 08dafbc5dc Move focus to the new onboarding step and announce IP detection (#56119)
* Move focus to the new onboarding step and announce IP detection

After Next, the analytics and integrations steps rendered without moving
focus, so it dropped to the page and screen readers heard nothing. They
now focus their heading when it appears.

Detecting the location by IP address now announces it in the status
region, like a GPS detection already does.

* Ignore Enter on the analytics heading and keep the early return

Enter on the focused heading reached the step's keypress listener and
saved the defaults before the user read the step. The integrations
restructure was not needed since @query finds the early-return heading.

The integrations step now also waits for the config entries snapshot,
which core sends after an await. Rendering on discoveries alone could
focus the "All set" heading and then replace it with the list, dropping
focus to the body.
2026-12-02 15:36:27 +00:00
Petar Petrov a3c534c2dd Move Lovelace entity list editors to contexts (#56362)
* Move Lovelace entity list editors to contexts

Entity picker table, suggestion entity tree and area controls feature editor read states, registries and i18n from contexts.

* Update area controls chip labels when their entities change

Consume the configured control entities reactively instead of reading the non-reactive states.
2026-12-02 15:35:23 +00:00
Petar Petrov cff3cb1eda Drop hass from the weather entity and cast rows (#56364)
Both rows read their entity, formatters, config, connection and auth from contexts.
2026-12-02 15:33:53 +00:00
Petar Petrov 2dd2a1f688 Move API-backed Lovelace editors to contexts (#56366)
The statistic card, view visibility and user condition editors consume apiContext and i18n instead of hass.
2026-12-02 15:33:23 +00:00
Petar Petrov f6e282d3e7 Move view settings and strategy editors off hass (#56358)
* Move view settings and strategy editors off hass

Header, footer and strategy editors consume localize, i18n and entities contexts instead of hass.

* Refresh editor form labels when the language changes

Memoize the label callbacks on localize so ha-form rerenders without its hass binding.
2026-12-02 15:33:00 +00:00
Petar Petrov 3b6c3216c4 Migrate entity-state Lovelace editors to contexts (#56359)
* Migrate entity-state Lovelace editors to contexts

Feature editors, the alarm panel card editor and the generic entity row editor read their entity and localize from contexts instead of hass.

* Refresh editor form labels when the language changes

Memoize the label callbacks on localize so ha-form rerenders without its hass binding.
2026-12-02 15:32:42 +00:00
Petar Petrov 558fb6f139 Migrate formatter card feature editors to contexts (#56360)
Light effect, media player sound mode and source, select options, vacuum fan speed and entity modes feature editors consume their entity state, formatters and localize instead of hass.
2026-12-02 15:32:38 +00:00
Petar Petrov 20eea322ba Migrate Lovelace condition type editors to contexts (#56363)
Screen, time, state and numeric state condition editors read localize, states and formatters from contexts.
2026-12-02 15:31:32 +00:00
Petar Petrov 512721959d Consume localize in Lovelace localize-only leaves (#56361)
Drop hass from nine Lovelace leaves that only read localize, and remove their callers' bindings.
2026-12-02 15:31:28 +00:00
Petar Petrov 8156895d6e Consume localize in localize-only card feature editors (#56357)
Drop hass from nine feature editors whose only reads were localize and the ha-form binding.
2026-12-02 15:31:24 +00:00
Petar Petrov 0075426172 Drop unused hass from Lovelace special rows, error heading badge and service button (#56356)
These elements never read hass, so the field and the service button's hass guard go.
2026-12-02 15:31:21 +00:00
JulianandClaude Opus 5.5 cde676487c Change Badge Card Styles to match the new style system (#55878)
* Make entity badge pictures circular again

Since pictures became rounded squares, the picture in an entity badge no
longer matched the pill-shaped badge and left an uneven gap around it.
Inside a pill, only a circle keeps the gap even, so badge pictures are
circles again.

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

* Give badges the rounded-square picture shape

Badge pictures are rounded squares again. Badges now use the picture radius
plus the 3px inset as their default radius, so the badge and its picture
are concentric. The shape is set in ha-badge, so all dashboard badges look
the same with or without a picture. The alert badge repeats the default for
its colored background and follows along.

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

* Make badge picture radius follow the badge radius

Co-Authored-By: Claude Opus 5.5 <[EMAIL]>
2026-12-02 15:22:21 +01:00
dependabot[bot] 7065084cfd Bump terser from 5.50.0 to 5.51.4 (#56355)
Bumps [terser](https://github.com/terser/terser) from 5.50.0 to 5.51.4.
- [Changelog](https://github.com/terser/terser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/terser/terser/compare/v5.50.0...v5.51.4)

---
updated-dependencies:
- dependency-name: terser
  dependency-version: 5.51.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-12-02 14:16:00 +00:00
Marcin BauerandClaude Opus 5.5 ade37bc113 Make trigger rows match the other automation rows (#56351)
* Make trigger icons the same size as other automation icons

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

* Use the same icon size in the triggered by condition

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

* Line up trigger rows and the triggered by list with the rest of the editor

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

* Keep 8px between the number and icon in the triggered by list

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-02 15:12:44 +01:00
Aidan Timson 8d9b6134db Render footnotes, heading anchors and alignment in markdown like GitHub (#56324)
* Render footnotes, heading ids and align in markdown like GitHub

* Scroll to anchors in markdown and translate the footnote labels

* Add footnotes, anchors and align to the markdown gallery page

* Leave modified clicks to the browser and focus markdown anchor targets

* Respect link targets, find double-prefixed headings and keep image align with SVG

* Decode ampersands in markdown ids and aria labels once
2026-12-02 14:47:43 +01:00
Aidan TimsonandCopilot Autofix powered by AI 15b78a94e1 Add a skeleton overlay that reads its shape from the content (#56103)
* Add a skeleton overlay that reads its shape from the content

* Add skeleton overlay guidance to the loading skill

* Name the skeleton overlay before translations load

* Read kept and root text and keep SVG geometry in skeletons

* Make hidden skeleton content inert and drop sources that leave

* Cut skeleton pieces to clipping ancestors and keep text with no box

* Keep all loading content inert and hear loading before the first render

* Follow slots to loading sources and keep left-out text's colour

* Find left-out text through shadow roots too

* Share hidden styles between nested skeleton overlays

* Stop re-measuring the skeleton overlay after every update

* Fix skeleton overlay canvas, clipping, style and fade edge cases

* Fade skeleton overlay content in to its own opacity

* Leave out content that hides itself when reading a skeleton

* Hold transitions off hidden skeleton parts and read fade durations in ms or s

* Read hidden stand-ins again when reading a skeleton

* Refactor skeleton overlay to use a div wrapper

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

* Fall back on text bar placement without font metrics

* Leave the skeleton overlay's content inert through its wrapper only

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-12-02 13:46:22 +00:00
70bdc89ba7 Update app pages from Supervisor events instead of polling (#56215)
* Refresh app info from Supervisor events instead of polling

The app info page polled the app info every 5 seconds. The shown state
lagged behind start, stop and crash transitions by up to that interval.

Subscribe to supervisor/subscribe and refetch the app info when
Supervisor reports a state change for this app ("addon" event, or "app"
once Core enables the v2 websocket API) or when a job that references
this app finishes, which covers update, rebuild and install.

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

* Fetch app info once per Supervisor action

An install sent five info requests. Each child job of the install
reports done with the app slug, and every action handler fetched the
info again after the parent dashboard already reloaded it.

Only refresh on root jobs, and drop the per-action refreshes. Clear the
local copy when the parent passes new app data, so option toggles show
the reloaded values without polling.

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

* Only go back after uninstall while the app page is open

The uninstall can take a while. If the user left the app page in the
meantime, the finished uninstall still called goBack and moved the user
one more step back in history.

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

* Reload the installed apps overview from Supervisor events

The overview loaded the app list once when it opened. An uninstall that
finished after the user returned to the overview, or a start, stop or
crash, did not show until the page was opened again.

Reload the list when Supervisor reports an app state change or a
finished root job for an app. Share the check for which app an event
concerns with the app info page.

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

* Apply Supervisor app events in place instead of refetching

Every app event made the installed apps overview fetch the whole list,
and every start or stop made the app info page fetch the app twice.

State events now patch the app state directly. A finished uninstall
drops the app from the overview. Only the root job of an install,
update, rebuild or restore fetches that one app again. Start, stop and
restart jobs add nothing beyond the state events, so they are ignored.

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

* Show installing and uninstalling apps in the installed apps overview

The overview showed an app only after its install finished, and showed
an app that was being uninstalled with its old state until it vanished.

Track the running install and uninstall jobs from the Supervisor job
events and show a spinner with "Installing..." or "Uninstalling..." on
the app card. An app that is being installed is added to the list from
its store info. The overview also reads the running jobs when it loads,
so an uninstall that started on the app page still shows after going
back. Events that arrive while the list loads are applied after it, so
an older list response cannot undo them.

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

* Resync app pages after missed events and stale responses

Events are the only source of updates now, so a missed event or a late
response left the app pages stale with nothing to correct them.

- Accept app manager jobs nested in other jobs. A backup restore runs
  app_manager_restore as a child job, and the pages ignored it.
- Refresh the app info after subscribing, because the dashboard loaded
  it before the info tab opened again.
- Reload the app info and the installed apps overview after each
  websocket reconnect, because events sent while offline are lost.
- Fetch an app again when one of its events arrives while its fetch
  runs, so an older response cannot override a newer state or put back
  an uninstalled app. Drop responses of superseded info refreshes.

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

* Handle store reloads and overlapping loads on the app pages

- Refetch the app info and reload the installed apps overview when
  Supervisor reloads the store, because that can make an update
  available. The removed polling used to pick this up.
- Let the newest overview load win when a reconnect starts a second
  one, and clear an earlier load error once a load succeeds.
- Ignore a running app info refresh when the parent passes newer app
  data, so a saved setting is not reverted by an older response.

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

* Close the remaining refresh races on the app pages

- Discard a single-app response in the overview when a full load
  started after it, because the full load has newer data.
- Reload the overview after "Check for updates" instead of using the
  list that call returns, so cards of installing apps stay.
- Refresh the app info when the parent passes reloaded data but a state
  event arrived while the parent reloaded, because that data can hold
  an older state.

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

* Handle v2 app events and simplify the app page bookkeeping

Supervisor sends "app" events with the full app status when its v2
websocket API is enabled, and "addon" events with only the state
otherwise. Both now become one partial app update. The settings of the
status apply only while the app is installed. A "stopping" state is left
out, because the app info reports the app as running until it stops.

The info page keeps one copy of the app. Supervisor sends an event for
each state change, so the state of the last event wins over the state in
any response, from its own refresh or from the dashboard. This replaces
the event counters, the hass-api-called listener and the refetch on each
state event. The dashboard reloads the app when the Info tab shows
again, instead of the info page on each subscribe.

The installed apps overview reloads the full list when a job finishes,
instead of fetching or removing the one app.

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

* Recover missed app events after a detach and keep all event fields

The panel resolver detaches a panel after 5 minutes in the background
and attaches it again later on the same connection. Events sent while
the page was detached never arrive, so both app pages now load after
each subscription. The info page skips its first subscription, because
the dashboard has just loaded the app.

Supervisor sends an event each time a field of its events changes, so
the info page now keeps all fields of the last events over a response,
not only the state. A v2 settings change no longer gets reverted by an
older refresh.

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

* Keep the v2 version of an app that is not installed

The v2 status reports a null version while the app is not installed.
The parser left it out, so after an uninstall from another client the
info page kept the version of an earlier event and showed the installed
controls. The parser now always passes the v2 version.

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

* Clear event fields when the app page switches to another app

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]>
Co-authored-by: Wendelin <[email protected]>
2026-12-02 15:04:55 +02:00
Petar Petrov d1569f5801 Drop hass from the logbook renderer (#56329)
* Drop hass from the logbook renderer

Logbook rows read their values from contexts, and the logbook helpers take separate values instead of hass.

* Rerender logbook rows when the brands token changes

Rows also narrow the config context and build the cause values once per filter run.

* Pass logbook helper values as separate parameters

Drop the shouldUpdate guard in the renderer now that hass updates are gone.
2026-12-02 14:14:31 +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
374 changed files with 12236 additions and 4178 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.
+21 -1
View File
@@ -10,6 +10,7 @@ Use this skill for every loading state, following the [Loading pattern](https://
## Pick The Indicator
- Use a skeleton from `src/components/skeleton/` (`ha-skeleton`, `ha-skeleton-text`, `ha-skeleton-icon`, `ha-skeleton-log`) when content loads into a layout you already know, such as table rows, tile text, or a log. It holds the layout, so nothing jumps when the content arrives.
- Use `ha-skeleton-overlay` when the content renders before its data arrives, such as a card or badge, or when content reloads over what's already shown. See [Skeleton Overlay](#skeleton-overlay).
- Use `ha-spinner` only when a whole area loads and its shape is unknown.
- Use `ha-button` with `loading`, or `ha-progress-button`, for an action started from a button. Don't put a separate spinner next to it.
@@ -27,7 +28,7 @@ Wrap the indicator in `ha-fade-in` from `src/components/animation/ha-fade-in.ts`
- Fade a skeleton in straight away over about 300ms (`.duration=${300}`), as the data table does. It stands in for the content, so a delay would leave an empty gap.
- Delay a spinner or progress bar, usually by `.delay=${500}`, so a load that finishes within that time never flashes it. Some slower areas, such as backups and updates, use `${1000}`.
- Don't fade in the loaded content itself.
- Don't add your own fade to loaded content. `ha-skeleton-overlay` fades each part in over `--ha-animation-duration-fast`, which reduced motion makes instant.
Give a skeleton group the `progressbar` role and a translated label, as `ha-spinner` has, rather than visible "Loading" text.
@@ -45,6 +46,24 @@ html`
`;
```
## Skeleton Overlay
`ha-skeleton-overlay` reads a skeleton from the content it wraps, so it can't drift from it: each text line, icon, image, control and drawing gets its own piece, and the real parts are hidden underneath until loading ends. Prefer it to drawing a skeleton by hand whenever the content can render before its data.
```ts
html`
<ha-skeleton-overlay .loading=${this._loading}>
<my-content></my-content>
</ha-skeleton-overlay>
`;
```
- Turn it on with `loading`, or fire `skeleton-loading` (`{ loading: true }`, later `{ loading: false }`) from inside the content. The event stops at the nearest overlay, so content doesn't need to know what wraps it.
- Mark parts that shouldn't be read with `data-skeleton`: `none` leaves an element out and showing, `keep` leaves it showing but reads what's inside, and `text`, `round` or `block` force one piece of that kind. Skeletons the content draws itself are left alone.
- Put your own skeleton in the `skeleton` slot to replace the reading altogether.
- Call `refresh()` when the content changes without changing size.
- It gives the skeleton the `progressbar` role and the translated label itself.
## Checking It
Check a loading state in the browser, not only by reading the code. These work on any setup: a dev server, the demo, or the gallery.
@@ -71,5 +90,6 @@ Check a loading state in the browser, not only by reading the code. These work o
};
```
- **Compare the skeleton with the content.** It should take the same space, so nothing moves when the content arrives. Measure the wrapper's height while loading and once loaded (`element.getBoundingClientRect().height` in the console), or take a screenshot of each at the same size and flick between them. Look for pieces that are missing, extra or in the wrong place, and fix those with `data-skeleton`.
- **Compare before and after.** Take screenshots of the same screen on `dev` and on your branch, at the same viewport size, both loading and loaded, and put them side by side. In a pull request, show both.
- **Check every look.** Light and dark themes, a right-to-left language (the wave starts from the right), reduced motion (DevTools, Rendering, "Emulate CSS media feature prefers-reduced-motion": the wave stops), and a phone width (DevTools device toolbar).
+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.
+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>
@@ -61,6 +61,6 @@ The badge component is a small component that displays a number or status inform
**CSS Custom Properties**
- `--ha-badge-size` (default `36px`)
- `--ha-badge-border-radius` (default `calc(var(--ha-badge-size, 36px) / 2)`)
- `--ha-badge-border-radius` (default `calc(var(--ha-border-radius-lg) + 3px)`)
- `--ha-badge-font-size` (default `var(--ha-font-size-s)`)
- `--ha-badge-icon-size` (default `18px`)
@@ -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: {
+23
View File
@@ -54,6 +54,29 @@ lorem | ipsum
`,
})
),
mdContentwithDefaults({
content: `
<p align="center">
<img src="https://img.shields.io/badge/markdown-rendering-brightgreen" alt="Centred badge">
</p>
- [Installation](#installation)
- [Configuration](#configuration)
## Installation
Install it from the Marketplace[^marketplace] and restart Home Assistant.[^restart]
## Configuration
Add the integration from the integrations page.
[Back to the top](#installation)
[^marketplace]: Settings > Marketplace.
[^restart]: Only needed the first time.
`,
}),
];
@customElement("demo-misc-ha-markdown")
+41 -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,17 @@
"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",
"marked-footnote": "1.4.0",
"marked-gfm-heading-id": "4.1.4",
"memoize-one": "7.0.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
"object-hash": "3.0.0",
@@ -136,25 +138,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 +164,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 +200,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 +211,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"
}
+1342 -1240
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:
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "home-assistant-frontend"
version = "20261125.4"
version = "20261125.0"
license = "Apache-2.0"
license-files = ["LICENSE*"]
description = "The Home Assistant frontend"
+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();
},
};
};
+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,
+623
View File
@@ -0,0 +1,623 @@
/**
* Read a skeleton from rendered content, such as a dashboard card: where its
* text lines, icons, images, controls and drawings are, inside shadow roots
* too. The content stays the source of truth for layout, so the skeleton
* can't drift from it.
*
* Any element can say how it's read with a `data-skeleton` attribute:
* - `text`, `round` or `block`: one piece of that kind, the size of the element
* - `none`: left out and left showing, such as a card's own chrome
* - `keep`: left showing, but what's inside it is still read
*
* Skeletons a component already draws itself (`ha-skeleton` and its
* variants) are left out and left showing, as `none`.
*/
export type SkeletonPieceKind = "text" | "round" | "block" | "shape" | "scrim";
type SkeletonOverride = "text" | "round" | "block" | "none" | "keep";
const OVERRIDES = new Set<string>(["text", "round", "block", "none", "keep"]);
const isOverride = (value: string | null): value is SkeletonOverride =>
value !== null && OVERRIDES.has(value);
const skeletonOverride = (element: Element): SkeletonOverride | undefined => {
if (element.localName.startsWith("ha-skeleton")) {
return "none";
}
const value = element.getAttribute("data-skeleton");
return isOverride(value) ? value : undefined;
};
export interface SkeletonPiece {
kind: SkeletonPieceKind;
x: number;
y: number;
width: number;
height: number;
radius?: string;
/* An SVG mask for a drawing, such as a gauge arc */
mask?: string;
/* Where that mask sits in the piece, when something cuts the drawing short:
still the drawing's whole size and place, with the piece only its part */
maskBox?: { x: number; y: number; width: number; height: number };
/* The part sits on a dark overlay, such as a picture card's name bar */
onDark?: boolean;
/* A see-through bar laid over a picture, kept as it is */
background?: string;
}
export interface ExtractedSkeleton {
pieces: SkeletonPiece[];
/* The elements the pieces stand in for, hidden while loading */
parts: (HTMLElement | SVGElement)[];
/* Elements holding text: hide only the text colour, as the same element
often draws a frame, such as a badge's pill, that has to stay */
textParts: HTMLElement[];
}
const ROUND_TAGS = new Set([
"ha-tile-icon",
"ha-state-icon",
"ha-svg-icon",
"ha-icon",
"state-badge",
]);
const BLOCK_TAGS = new Set(["img", "video", "canvas", "ha-camera-stream"]);
/* A canvas to measure fonts with, made on first use */
let measuringContext: CanvasRenderingContext2D | null | undefined;
const fontContext = (style: CSSStyleDeclaration, size: string) => {
measuringContext ??= document.createElement("canvas").getContext("2d");
if (measuringContext) {
measuringContext.font = `${style.fontStyle} ${style.fontWeight} ${size} ${style.fontFamily}`;
}
return measuringContext;
};
/**
* Where a text bar goes on a line of this font: from the top of the
* capitals down to the baseline, measured from the font itself.
* `size` is the size as drawn, after any SVG scaling.
*/
const capitalBand = (style: CSSStyleDeclaration, size: number) => {
const metrics = fontContext(style, `${size}px`)?.measureText("H");
// Missing before Chrome 87 and Firefox 116
if (!metrics?.fontBoundingBoxAscent || !metrics.actualBoundingBoxAscent) {
return { top: size * 0.2, height: size * 0.7 };
}
return {
// The line box holds the font's ascent, so the baseline sits that far down
top: metrics.fontBoundingBoxAscent - metrics.actualBoundingBoxAscent,
height: metrics.actualBoundingBoxAscent,
};
};
/* How wide "…" is in this font, the room cut-off text leaves at its end */
const ellipsisWidth = (style: CSSStyleDeclaration) =>
fontContext(style, style.fontSize)?.measureText("…").width ??
parseFloat(style.fontSize);
/* The icon as drawn, not its box, which a line of text can crop */
const findGlyph = (element: Element, depth = 4): Element | undefined => {
if (depth === 0) {
return undefined;
}
for (const child of [
...(element.shadowRoot?.children ?? []),
...element.children,
]) {
if (child instanceof SVGSVGElement) {
return child;
}
const found = findGlyph(child, depth - 1);
if (found) {
return found;
}
}
return undefined;
};
/* Near-white text or icons, as on a picture card's dark name bar */
const isNearWhite = (color: string): boolean => {
const channels = color
.match(/[\d.]+/g)
?.slice(0, 3)
.map(Number);
return channels?.length === 3 && channels.every((channel) => channel >= 200);
};
const isRendered = (style: CSSStyleDeclaration) =>
style.display !== "none" && style.visibility !== "hidden";
const isSeeThrough = (color: string) => {
const alpha = Number(color.match(/rgba\(.*,\s*([\d.]+)\)/)?.[1] ?? 1);
return alpha > 0 && alpha < 1;
};
/* The first element, inside shadow roots too, that rounds its corners */
const findRounded = (element: Element, depth = 4): Element | undefined => {
if (depth === 0) {
return undefined;
}
const children = [
...(element.shadowRoot?.children ?? []),
...element.children,
];
for (const child of children) {
if (parseFloat(getComputedStyle(child).borderTopLeftRadius) > 0) {
return child;
}
const found = findRounded(child, depth - 1);
if (found) {
return found;
}
}
return undefined;
};
/* Join the pieces of one line of text, such as "Heat", "·" and "21 °C" */
const mergeLines = (pieces: SkeletonPiece[]): SkeletonPiece[] => {
const merged: SkeletonPiece[] = [];
for (const piece of pieces) {
const previous = merged[merged.length - 1];
// Either side, so right-to-left lines join too
const gap = previous
? Math.max(
piece.x - (previous.x + previous.width),
previous.x - (piece.x + piece.width)
)
: Infinity;
const sameLine =
previous?.kind === "text" &&
piece.kind === "text" &&
Math.abs(previous.y - piece.y) < 2 &&
Math.abs(previous.height - piece.height) < 2 &&
gap < 12;
if (sameLine) {
const left = Math.min(previous.x, piece.x);
const right = Math.max(
previous.x + previous.width,
piece.x + piece.width
);
previous.x = left;
previous.width = right - left;
continue;
}
merged.push({ ...piece });
}
return merged;
};
const svgMask = (svg: SVGSVGElement, width: number, height: number) => {
const clone = svg.cloneNode(true);
if (!(clone instanceof SVGSVGElement)) {
return undefined;
}
const originals = [svg, ...svg.querySelectorAll("*")];
const copies = [clone, ...clone.querySelectorAll("*")];
let drawnPaths = 0;
originals.forEach((original, index) => {
const copy = copies[index];
const style = getComputedStyle(original);
if (original.localName === "text" || !isRendered(style)) {
copy.setAttribute("display", "none");
return;
}
if (original !== svg && original.localName !== "g") {
drawnPaths++;
}
copy.removeAttribute("class");
copy.removeAttribute("style");
copy.setAttribute("fill", style.fill === "none" ? "none" : "#000");
copy.setAttribute("stroke", style.stroke === "none" ? "none" : "#000");
copy.setAttribute("stroke-width", style.strokeWidth);
copy.setAttribute("stroke-linecap", style.strokeLinecap);
// Keep what moves or cuts a shape, such as a gauge's needle and the
// dashes that draw its value arc
if (style.transform !== "none") {
copy.setAttribute(
"style",
`transform: ${style.transform}; transform-origin: ${style.transformOrigin}; transform-box: ${style.transformBox}`
);
}
if (style.strokeDasharray !== "none") {
copy.setAttribute("stroke-dasharray", style.strokeDasharray);
copy.setAttribute("stroke-dashoffset", style.strokeDashoffset);
}
});
if (drawnPaths === 0) {
return undefined;
}
clone.setAttribute("width", String(width));
clone.setAttribute("height", String(height));
const markup = new XMLSerializer().serializeToString(clone);
return `url("data:image/svg+xml,${encodeURIComponent(markup)}")`;
};
export const extractSkeleton = (
root: Element,
origin: DOMRect
): ExtractedSkeleton => {
const pieces: SkeletonPiece[] = [];
const parts = new Set<HTMLElement | SVGElement>();
const textParts = new Set<HTMLElement>();
/* The card's own background, the first solid one found */
let surface: string | undefined;
const box = (rect: DOMRect) => ({
x: rect.left - origin.left,
y: rect.top - origin.top,
width: rect.width,
height: rect.height,
});
/* Near-white content on a light card must sit on a dark bar */
const onDark = (style: CSSStyleDeclaration) =>
surface !== undefined && isNearWhite(surface) && isNearWhite(style.color);
/* An element that cuts off its overflow, such as a scrolling list, cuts the
pieces read inside it too, as the overlay draws them on a layer of its
own where that clip doesn't reach */
const clipPieces = (from: number, rect: DOMRect) => {
const bounds = box(rect);
const clipped = pieces.splice(from).flatMap((piece): SkeletonPiece[] => {
const x = Math.max(piece.x, bounds.x);
const y = Math.max(piece.y, bounds.y);
const right = Math.min(piece.x + piece.width, bounds.x + bounds.width);
const bottom = Math.min(piece.y + piece.height, bounds.y + bounds.height);
if (right <= x || bottom <= y) {
return [];
}
const cut = { ...piece, x, y, width: right - x, height: bottom - y };
// A drawing's mask is made for its whole box, so it keeps that box
if (piece.kind === "shape") {
const mask = piece.maskBox ?? {
x: 0,
y: 0,
width: piece.width,
height: piece.height,
};
return [
{
...cut,
maskBox: {
...mask,
x: piece.x + mask.x - x,
y: piece.y + mask.y - y,
},
},
];
}
return [cut];
});
pieces.push(...clipped);
};
const addText = (element: Element | ShadowRoot) => {
const owner = element instanceof ShadowRoot ? element.host : element;
// Text cut short with an ellipsis reaches past its box, so clip to it.
// An owner with no box of its own, such as one with display: contents,
// cuts nothing off.
const clip = owner.getBoundingClientRect();
const clips = clip.width > 0 || clip.height > 0;
element.childNodes.forEach((node) => {
if (!(node instanceof Text) || !node.textContent?.trim()) {
return;
}
// Slotted text takes its font and colour from the slot it shows in,
// so that's where it's measured and hidden
const slot = node.assignedSlot;
const hideTarget = slot ?? owner;
const style = getComputedStyle(hideTarget);
const band = capitalBand(style, parseFloat(style.fontSize));
if (hideTarget instanceof HTMLElement) {
textParts.add(hideTarget);
}
const range = document.createRange();
range.selectNodeContents(node);
for (const rect of range.getClientRects()) {
// Cut-off text ends in "…", on the right or, right to left, on the
// left, so stop the bar where that starts
const left =
clips && rect.left < clip.left - 1
? clip.left + ellipsisWidth(style)
: rect.left;
const right =
clips && rect.right > clip.right + 1
? clip.right - ellipsisWidth(style)
: rect.right;
if (right <= left) {
continue;
}
pieces.push({
kind: "text",
x: left - origin.left,
width: right - left,
y: rect.top - origin.top + band.top,
height: band.height,
onDark: onDark(style),
});
}
});
};
const walk = (node: Element | ShadowRoot) => {
// Text straight inside a shadow root, as state-display renders its state
if (node instanceof ShadowRoot) {
addText(node);
}
for (const child of node.children) {
const style = getComputedStyle(child);
if (!isRendered(style)) {
continue;
}
const rect = child.getBoundingClientRect();
const tag = child.localName;
// Elements such as slots take no space but their content does
const hasSize = rect.width > 0 && rect.height > 0;
const override = skeletonOverride(child);
if (override === "none") {
continue;
}
const clipsOverflow =
hasSize &&
(style.overflowX !== "visible" || style.overflowY !== "visible");
const from = pieces.length;
// Read what's inside, cut to the child where it hides its overflow
const descend = () => {
if (child instanceof HTMLElement) {
addText(child);
}
if (child.shadowRoot) {
walk(child.shadowRoot);
}
walk(child);
if (clipsOverflow) {
clipPieces(from, rect);
}
};
if (override === "keep") {
// Its frame stays, but its own text is read like any other
descend();
continue;
}
if (override !== undefined) {
if (
hasSize &&
(child instanceof HTMLElement || child instanceof SVGElement)
) {
const size = Math.min(rect.width, rect.height);
const piece = box(rect);
pieces.push(
override === "round"
? {
kind: "round",
x: piece.x + (piece.width - size) / 2,
y: piece.y + (piece.height - size) / 2,
width: size,
height: size,
}
: { kind: override, ...piece, radius: style.borderRadius }
);
parts.add(child);
}
continue;
}
if (
surface === undefined &&
hasSize &&
style.backgroundColor !== "rgba(0, 0, 0, 0)" &&
!isSeeThrough(style.backgroundColor)
) {
surface = style.backgroundColor;
}
if (child instanceof HTMLElement && ROUND_TAGS.has(tag)) {
// Use the circle itself, such as the tile icon's 36px background
const circle = (
findRounded(child) ??
findGlyph(child) ??
child
).getBoundingClientRect();
const size =
Math.min(circle.width, circle.height) ||
Math.max(circle.width, circle.height);
const piece = box(circle);
if (size > 0) {
pieces.push({
kind: "round",
x: piece.x + (piece.width - size) / 2,
y: piece.y + (piece.height - size) / 2,
width: size,
height: size,
onDark: onDark(style),
});
parts.add(child);
}
continue;
}
// A see-through bar over a picture stays, so text keeps its contrast
if (
child instanceof HTMLElement &&
hasSize &&
style.position === "absolute" &&
isSeeThrough(style.backgroundColor)
) {
pieces.push({
kind: "scrim",
...box(rect),
radius: style.borderRadius,
background: style.backgroundColor,
});
}
// Pictures drawn as a background, as hui-image does in a fixed ratio
if (
child instanceof HTMLElement &&
hasSize &&
style.backgroundImage.startsWith("url(")
) {
pieces.push({
kind: "block",
...box(rect),
radius: style.borderRadius,
});
parts.add(child);
continue;
}
if (child instanceof HTMLElement && hasSize && BLOCK_TAGS.has(tag)) {
pieces.push({
kind: "block",
...box(rect),
radius: style.borderRadius,
});
parts.add(child);
continue;
}
if (
child instanceof HTMLElement &&
hasSize &&
tag.endsWith("-card-feature")
) {
const control = findRounded(child);
const radius = control
? getComputedStyle(control).borderRadius
: style.borderRadius;
pieces.push({ kind: "block", ...box(rect), radius });
parts.add(child);
continue;
}
if (child instanceof SVGSVGElement && hasSize) {
const piece = box(rect);
const mask = svgMask(child, piece.width, piece.height);
if (mask) {
pieces.push({ kind: "shape", ...piece, mask });
}
child.querySelectorAll("text").forEach((text) => {
const textRect = text.getBoundingClientRect();
if (textRect.width === 0) {
return;
}
// SVG text is scaled with its drawing, as the gauge value is
const scale = text.getScreenCTM()?.a ?? 1;
const textStyle = getComputedStyle(text);
const band = capitalBand(
textStyle,
parseFloat(textStyle.fontSize) * scale
);
pieces.push({
kind: "text",
...box(textRect),
y: textRect.top - origin.top + band.top,
height: band.height,
});
});
parts.add(child);
continue;
}
descend();
}
};
// Text straight inside the root, such as plain text in an overlay
addText(root);
walk(root);
return {
pieces: mergeLines(pieces),
parts: [...parts],
textParts: [...textParts],
};
};
-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;
};
+3 -2
View File
@@ -273,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) {
@@ -1338,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 };
}
}
+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";
+6 -2
View File
@@ -73,7 +73,7 @@ export class HaBadge extends LitElement {
width: auto;
border-radius: var(
--ha-badge-border-radius,
calc(var(--ha-badge-size, 36px) / 2)
calc(var(--ha-border-radius-lg) + 3px)
);
background: var(
--ha-card-background,
@@ -132,7 +132,11 @@ export class HaBadge extends LitElement {
::slotted(img[slot="icon"]) {
width: 30px;
height: 30px;
border-radius: var(--ha-picture-border-radius);
/* Concentric with the badge, the picture sits 3px inside it */
border-radius: calc(
var(--ha-badge-border-radius, calc(var(--ha-border-radius-lg) + 3px)) -
3px
);
object-fit: cover;
overflow: hidden;
margin-left: -10px;
+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 });
}
+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,
@@ -36,6 +36,8 @@ export class HaFormExpandable extends LitElement implements HaFormElement {
key: string
) => string;
@property({ attribute: false }) public context?: Record<string, any>;
@query("ha-form", true) private _form?: HaForm;
public reportValidity(): boolean {
@@ -109,6 +111,7 @@ export class HaFormExpandable extends LitElement implements HaFormElement {
.computeLabel=${this._computeLabel}
.computeHelper=${this._computeHelper}
.localizeValue=${this.localizeValue}
.context=${this.context}
></ha-form>
</div>
</ha-expansion-panel>
+3
View File
@@ -35,6 +35,8 @@ export class HaFormGrid extends LitElement implements HaFormElement {
key: string
) => string;
@property({ attribute: false }) public context?: Record<string, any>;
@queryAll("ha-form", true) private _forms?: HaForm[];
static shadowRootOptions = {
@@ -83,6 +85,7 @@ export class HaFormGrid extends LitElement implements HaFormElement {
.computeLabel=${this.computeLabel}
.computeHelper=${this.computeHelper}
.localizeValue=${this.localizeValue}
.context=${this.context}
></ha-form>
`
)}
@@ -54,6 +54,8 @@ export class HaFormOptionalActions extends LitElement implements HaFormElement {
key: string
) => string;
@property({ attribute: false }) public context?: Record<string, any>;
@state() private _displayActions?: string[];
@query("ha-form") private _form?: HaForm;
@@ -130,6 +132,7 @@ export class HaFormOptionalActions extends LitElement implements HaFormElement {
.computeLabel=${this.computeLabel}
.computeHelper=${this.computeHelper}
.localizeValue=${this.localizeValue}
.context=${this.context}
></ha-form>
`
: nothing
+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,
+121 -1
View File
@@ -1,11 +1,20 @@
import type { PropertyValues } from "lit";
import { ReactiveElement, render, html } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, state } from "lit/decorators";
import { unsafeHTML } from "lit/directives/unsafe-html.js";
import hash from "object-hash";
import { consume } from "../common/decorators/consume";
import { transform } from "../common/decorators/transform";
import { fireEvent } from "../common/dom/fire_event";
import { rewriteHtmlUrls } from "../common/dom/rewrite-html-urls";
import { internationalizationContext } from "../data/context";
import type { FootnoteLabels } from "../resources/markdown-worker";
import {
USER_CONTENT_PREFIX,
userContentId,
} from "../resources/markdown-user-content";
import { renderMarkdown } from "../resources/render-markdown";
import type { HomeAssistantInternationalization } from "../types";
import { CacheManager } from "../util/cache-manager";
const h = (template: ReturnType<typeof unsafeHTML>) => html`${template}`;
@@ -43,8 +52,35 @@ class HaMarkdownElement extends ReactiveElement {
// For content whose relative addresses belong elsewhere, like a README
@property({ attribute: false }) public rewriteUrl?: (url: string) => string;
// Without translations, like on the auth pages, the worker uses English
@state({
hasChanged: (value?: FootnoteLabels, oldValue?: FootnoteLabels) =>
value?.heading !== oldValue?.heading ||
value?.backReference !== oldValue?.backReference,
})
@consume({ context: internationalizationContext, subscribe: true })
@transform<HomeAssistantInternationalization, FootnoteLabels>({
transformer: ({ localize }) => {
const heading = localize("ui.components.markdown.footnotes");
const backReference = localize(
"ui.components.markdown.footnote_back_reference",
{ reference: "{0}" }
);
return heading && backReference ? { heading, backReference } : undefined;
},
})
private _footnoteLabels?: FootnoteLabels;
public connectedCallback() {
super.connectedCallback();
this.addEventListener("click", this._handleAnchorClick);
}
public disconnectedCallback() {
super.disconnectedCallback();
this.removeEventListener("click", this._handleAnchorClick);
if (this.cache) {
const key = this._computeCacheKey();
markdownCache.set(key, this.innerHTML);
@@ -87,6 +123,7 @@ class HaMarkdownElement extends ReactiveElement {
allowDataUrl: this.allowDataUrl,
breaks: this.breaks,
rewriteUrl: Boolean(this.rewriteUrl),
footnoteLabels: this._footnoteLabels,
});
}
@@ -101,6 +138,7 @@ class HaMarkdownElement extends ReactiveElement {
allowSvg: this.allowSvg,
allowDataUrl: this.allowDataUrl,
allowRelativeUrls: Boolean(this.rewriteUrl),
footnoteLabels: this._footnoteLabels,
}
);
@@ -203,6 +241,88 @@ class HaMarkdownElement extends ReactiveElement {
}
private _resize = () => fireEvent(this, "content-resize");
// The content is in a shadow root, so the browser can't scroll to a `#` link
// in it, and the app would navigate to it instead
private _handleAnchorClick = (ev: MouseEvent) => {
// Leave opening the link in a new tab or window to the browser
if (
ev.defaultPrevented ||
ev.button !== 0 ||
ev.metaKey ||
ev.ctrlKey ||
ev.shiftKey
) {
return;
}
const anchor = ev
.composedPath()
.find((node) => node instanceof HTMLAnchorElement);
// Or one the author set to open somewhere else
if (anchor?.target && anchor.target !== "_self") {
return;
}
const href = anchor?.getAttribute("href");
if (!href?.startsWith("#") || href.length === 1) {
return;
}
const fragment = href.slice(1);
// Browsers take #top as the top of the page, READMEs use it for the top
const target =
this._findAnchorTarget(fragment) ??
(fragment.toLowerCase() === "top" ? this : undefined);
// An anchor that isn't in the content does what it did before
if (target) {
ev.preventDefault();
target.scrollIntoView({ block: "start" });
// Move focus there too, like the browser does, so Tab carries on from
// the target. -1 makes a heading focusable without adding it to Tab.
if (target instanceof HTMLElement) {
if (!target.hasAttribute("tabindex") && target.tabIndex < 0) {
target.tabIndex = -1;
}
target.focus({ preventScroll: true });
}
}
};
// Links like `#Setup` and `#%C3%BCber` still find `user-content-setup` and
// `user-content-über`, like on GitHub
private _findAnchorTarget(fragment: string) {
let decoded = fragment;
try {
decoded = decodeURIComponent(fragment);
} catch {
// Not encoded, look for it as written
}
const ids = [fragment, decoded, decoded.toLowerCase()].flatMap((id) => [
userContentId(id),
// Heading ids always get the prefix, so `## user-content-setup` has
// `user-content-user-content-setup`
`${USER_CONTENT_PREFIX}${id}`,
]);
for (const id of new Set(ids)) {
const target = this.querySelector(`[id="${CSS.escape(id)}"]`);
if (target) {
return target;
}
}
return undefined;
}
}
declare global {
+15
View File
@@ -201,6 +201,21 @@ export class HaMarkdown extends LitElement {
margin-inline: 0;
padding-inline: 1em;
}
section[data-footnotes] {
border-top: 1px solid var(--divider-color);
margin-top: var(--ha-space-4);
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
}
/* Read out by screen readers but not shown, like on GitHub */
section[data-footnotes] > h2 {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
` as CSSResultGroup;
}
+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();
@@ -4,7 +4,7 @@ import { consume } from "../../common/decorators/consume";
import { fireEvent } from "../../common/dom/fire_event";
import { transform } from "../../common/decorators/transform";
import { caseInsensitiveStringCompare } from "../../common/string/compare";
import type { ButtonToggleSelector, SelectOption } from "../../data/selector";
import type { ButtonToggleSelector } from "../../data/selector";
import { internationalizationContext } from "../../data/context";
import type { FrontendLocaleData } from "../../data/translation";
import type {
@@ -41,8 +41,8 @@ export class HaButtonToggleSelector extends LitElement {
const options =
this.selector.button_toggle?.options?.map((option) =>
typeof option === "object"
? (option as SelectOption)
: ({ value: option, label: option } as SelectOption)
? { ...option, label: option.label ?? option.value }
: { value: option, label: option }
) || [];
const translationKey = this.selector.button_toggle?.translation_key;
@@ -64,7 +64,7 @@ export class HaButtonToggleSelector extends LitElement {
);
}
const toggleButtons: ToggleButton[] = options.map((item: SelectOption) => ({
const toggleButtons: ToggleButton[] = options.map((item) => ({
label: item.label,
value: item.value,
}));
@@ -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}
@@ -4,7 +4,6 @@ import memoizeOne from "memoize-one";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import { fireEvent } from "../../common/dom/fire_event";
import type { PeriodKey, PeriodSelector } from "../../data/selector";
import type { HomeAssistant } from "../../types";
import { deepEqual } from "../../common/util/deep-equal";
import type { LocalizeFunc } from "../../common/translations/localize";
import "../ha-form/ha-form";
@@ -28,8 +27,6 @@ const PERIODS = {
@customElement("ha-selector-period")
export class HaPeriodSelector extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public selector!: PeriodSelector;
@property({ attribute: false }) public value?: unknown;
@@ -87,7 +84,6 @@ export class HaPeriodSelector extends LitElement {
return html`
<ha-form
.hass=${this.hass}
.data=${data}
.schema=${schema}
.computeHelper=${this._computeHelperCallback}
@@ -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()
@@ -79,6 +93,12 @@ export class HaSelectSelector extends LitElement {
if (localizedLabel) {
option.label = localizedLabel;
}
const localizedDescription = this.localizeValue!(
`${translationKey}.options_description.${option.value}`
);
if (localizedDescription) {
option.description = localizedDescription;
}
});
}
@@ -256,6 +276,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 ?? ""}
@@ -290,8 +327,8 @@ export class HaSelectSelector extends LitElement {
(selector: SelectSelector) =>
selector.select?.options?.map((option) =>
typeof option === "object"
? (option as SelectOption)
: ({ value: String(option), label: option } as SelectOption)
? { ...option, label: option.label ?? option.value }
: { value: String(option), label: option }
) || []
);
@@ -310,6 +347,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 +452,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);
+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),
@@ -0,0 +1,619 @@
import type { ContextType } from "@lit/context";
import type { CSSResultGroup, PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { styleMap } from "lit/directives/style-map";
import { consume } from "../../common/decorators/consume";
import type {
ExtractedSkeleton,
SkeletonPiece,
} from "../../common/dom/extract-skeleton";
import { extractSkeleton } from "../../common/dom/extract-skeleton";
import type { HASSDomEvent } from "../../common/dom/fire_event";
import { parseAnimationDuration } from "../../common/util/parse-animation-duration";
import { internationalizationContext } from "../../data/context";
import type { HaSkeleton } from "./ha-skeleton";
import "./ha-skeleton";
export interface SkeletonLoadingDetail {
loading: boolean;
}
interface ArrivingParts {
/* The whole content, when it was hidden rather than its parts */
content: Element[];
opacityParts: (HTMLElement | SVGElement)[];
colorParts: HTMLElement[];
}
/* Transitions are held off too, so a part hides at once rather than easing
out from under its skeleton */
type HiddenProperty = "opacity" | "color" | "transition";
interface HiddenStyle {
/* The inline value from before anything hid it */
value: string;
/* The value it was hidden with */
hidden: string;
holders: number;
}
/* Overlays nest, as a stack card's cards each have their own, so two can
hide the same element. The first to hide one notes the value it really
had, and only the last to let go puts that back, so neither keeps the
other's hidden value as the one to restore. */
const hiddenStyles: Record<
HiddenProperty,
Map<HTMLElement | SVGElement, HiddenStyle>
> = { opacity: new Map(), color: new Map(), transition: new Map() };
const hideStyle = (
element: HTMLElement | SVGElement,
name: HiddenProperty,
hidden: string
) => {
const held = hiddenStyles[name].get(element);
if (held) {
held.holders++;
} else {
hiddenStyles[name].set(element, {
value: element.style[name],
hidden,
holders: 1,
});
}
element.style[name] = hidden;
};
const releaseStyle = (
element: HTMLElement | SVGElement,
name: HiddenProperty
) => {
const held = hiddenStyles[name].get(element);
if (!held) {
return;
}
held.holders--;
if (held.holders === 0) {
// Content that set its own value while it was hidden keeps that one
if (element.style[name] === held.hidden) {
element.style[name] = held.value;
}
hiddenStyles[name].delete(element);
}
};
const holdersOf = (element: HTMLElement | SVGElement, name: HiddenProperty) =>
hiddenStyles[name].get(element)?.holders ?? 0;
/* What's left out with data-skeleton="none" under an element, through
shadow roots, as the skeleton is read */
const leftOut = (root: Element | ShadowRoot): HTMLElement[] =>
[...root.querySelectorAll("*")].flatMap((element) => [
...(element instanceof HTMLElement && element.dataset.skeleton === "none"
? [element]
: []),
...(element.shadowRoot ? leftOut(element.shadowRoot) : []),
]);
/**
* Shows a skeleton of its content while that content loads, read from the
* content itself: each line of text, icon, image, control and drawing gets
* its own piece. When loading ends, the pieces go and each part fades in.
*
* Loading is on while `loading` is set, or while anything inside has fired
* a `skeleton-loading` event with `{ loading: true }` and not yet
* `{ loading: false }`. The event stops at the nearest overlay, so content
* doesn't need to know what wraps it.
*
* To take over:
* - put your own skeleton in the `skeleton` slot, and it's used instead of
* reading one
* - set `data-skeleton` on any element inside, as described in
* `extract-skeleton`, to change how that part is read or leave it out
* - call `refresh()` when the content changes without changing size
*
* With nothing to read yet, such as before the content's code has loaded,
* it fills itself with one plain wave. The skeleton follows the host's
* corner radius.
*
* @slot - The content.
* @slot skeleton - A skeleton of your own, used instead of reading one.
*/
@customElement("ha-skeleton-overlay")
export class HaSkeletonOverlay extends LitElement {
@property({ type: Boolean }) public loading = false;
@property() public effect: HaSkeleton["effect"] = "sheen";
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n?: ContextType<typeof internationalizationContext>;
/* What's inside that has said it's loading */
@state() private _loadingSources = new Set<EventTarget>();
@state() private _pieces?: SkeletonPiece[];
@state() private _customSkeleton = false;
@state() private _onScreen = true;
@query("slot:not([name])") private _contentSlot?: HTMLSlotElement;
/* The parts this overlay hides, through hideStyle */
private _hiddenOpacity = new Set<HTMLElement | SVGElement>();
private _hiddenColor = new Set<HTMLElement>();
private _heldTransition = new Set<HTMLElement | SVGElement>();
/* Inline colours of content left out inside hidden text, which keeps its
own colour meanwhile */
private _keptColor = new Map<HTMLElement, string>();
private _wasLoading = false;
/* What to fade in once loading has ended */
private _arriving?: ArrivingParts;
/* The fades still running from the last time loading ended */
private _fades: Animation[] = [];
private _measureFrame?: number;
private _resizeObserver = new ResizeObserver(() => this._scheduleMeasure());
private _intersectionObserver = new IntersectionObserver((entries) => {
this._onScreen = entries[entries.length - 1].isIntersecting;
});
constructor() {
super();
// On the host rather than the slot, so content that says it's loading
// as it connects, before the first render, is heard
this.addEventListener("skeleton-loading", this._skeletonLoading);
}
public connectedCallback() {
super.connectedCallback();
this._resizeObserver.observe(this);
this._intersectionObserver.observe(this);
this._scheduleMeasure();
}
public disconnectedCallback() {
super.disconnectedCallback();
this._resizeObserver.disconnect();
this._intersectionObserver.disconnect();
if (this._measureFrame !== undefined) {
cancelAnimationFrame(this._measureFrame);
this._measureFrame = undefined;
}
// Never leave the content hidden while it's away
this._cancelFades();
this._showParts();
}
/** Read the skeleton again, after the content changed but not its size */
public refresh() {
this._scheduleMeasure();
}
private get _isLoading() {
return this.loading || this._loadingSources.size > 0;
}
protected willUpdate(changedProperties: PropertyValues<this>) {
super.willUpdate(changedProperties);
const loading = this._isLoading;
if (loading && !this._wasLoading) {
// A fade still running would show the content over the hidden style
this._cancelFades();
this._customSkeleton = [...this.children].some(
(child) => child.slot === "skeleton"
);
}
if (!loading && this._wasLoading) {
this._endLoading();
}
this._wasLoading = loading;
}
protected updated(changedProperties: PropertyValues<this>) {
super.updated(changedProperties);
// Only when loading starts: loading events, slot changes, sizes and
// refresh() ask for their own, and measuring after every update would
// run each frame for content that animates, such as a spinner, as every
// reading comes out different and updates again
if (this._isLoading && changedProperties.has("loading")) {
this._scheduleMeasure();
}
if (this._arriving) {
this._fadeIn(this._arriving);
this._arriving = undefined;
}
}
protected render() {
const loading = this._isLoading;
// Named like ha-spinner, which falls back to English before translations
// have loaded
const label = this._i18n?.localize("ui.common.loading") || "Loading";
// The content can't be focused, used or read out while it loads, frames
// around the hidden parts included, such as a card that takes clicks
return html`
<div class="content" ?inert=${loading}>
<slot
class=${classMap({
// Before the first reading, or under a skeleton of your own
hidden:
loading && (this._customSkeleton || this._pieces === undefined),
})}
@slotchange=${this._contentChanged}
></slot>
</div>
${
loading
? html`
<div class="skeleton" role="progressbar" aria-label=${label}>
<slot
name="skeleton"
@slotchange=${this._skeletonSlotChanged}
></slot>
${this._customSkeleton ? nothing : this._renderPieces()}
</div>
`
: nothing
}
`;
}
private _renderPieces() {
// Nothing still animates off screen
const effect = this._onScreen ? this.effect : "none";
if (!this._pieces?.length) {
return html`<ha-skeleton class="fill" .effect=${effect}></ha-skeleton>`;
}
return this._pieces.map((piece) =>
piece.kind === "scrim"
? html`<div class="piece" style=${pieceStyle(piece)}></div>`
: html`<ha-skeleton
class=${classMap({
piece: true,
[piece.kind]: true,
"on-dark": Boolean(piece.onDark),
})}
.effect=${effect}
style=${pieceStyle(piece)}
></ha-skeleton>`
);
}
private _skeletonLoading = (ev: HASSDomEvent<SkeletonLoadingDetail>) => {
// The nearest overlay owns it
ev.stopPropagation();
const source = ev.composedPath()[0];
const sources = new Set(this._loadingSources);
if (ev.detail.loading) {
sources.add(source);
} else {
sources.delete(source);
}
this._loadingSources = sources;
this._scheduleMeasure();
};
private _contentChanged() {
this._resizeObserver.disconnect();
this._resizeObserver.observe(this);
this._contentSlot
?.assignedElements()
.forEach((element) => this._resizeObserver.observe(element));
this._pruneSources();
this._scheduleMeasure();
}
/* Content that went away, or moved out of this overlay, can't finish
loading here. Removing it deep inside a card fires no slotchange, so
this runs on every measure too, which any change of size starts. */
private _pruneSources() {
const sources = [...this._loadingSources].filter((source) =>
this._holds(source)
);
if (sources.length !== this._loadingSources.size) {
this._loadingSources = new Set(sources);
}
}
/* Whether a source is still inside this overlay, the way its events
travel: through the slots content shows in, and out of shadow roots */
private _holds(source: EventTarget) {
if (!(source instanceof Node)) {
return true;
}
let node: Node | null = source;
while (node) {
if (node === this) {
return true;
}
node =
node instanceof ShadowRoot
? node.host
: ((node instanceof Element || node instanceof Text
? node.assignedSlot
: null) ?? node.parentNode);
}
return false;
}
private _skeletonSlotChanged(ev: Event) {
const slot = ev.target;
if (!(slot instanceof HTMLSlotElement)) {
return;
}
this._customSkeleton = slot.assignedNodes({ flatten: true }).length > 0;
if (this._customSkeleton) {
// The whole content is hidden under it instead
this._showParts();
this._pieces = undefined;
} else {
// Read from the content again now it's gone
this._scheduleMeasure();
}
}
private _scheduleMeasure() {
if (this._measureFrame !== undefined || !this.isConnected) {
return;
}
this._measureFrame = requestAnimationFrame(() => {
this._measureFrame = undefined;
this._measure();
});
}
/* Read the skeleton from the content, and hide the parts it stands in for */
private _measure() {
this._pruneSources();
if (!this._isLoading || this._customSkeleton) {
return;
}
// Read from the content as it really looks, then hide it again before
// the next paint, so nothing flickers
this._showParts();
const skeleton = extractSkeleton(this, this.getBoundingClientRect());
this._hideParts(skeleton);
if (JSON.stringify(skeleton.pieces) !== JSON.stringify(this._pieces)) {
this._pieces = skeleton.pieces;
}
}
private _hideParts(skeleton: ExtractedSkeleton) {
skeleton.parts.forEach((part) => {
if (!this._hiddenOpacity.has(part)) {
this._hiddenOpacity.add(part);
hideStyle(part, "opacity", "0");
}
});
// What's left out with data-skeleton="none" inside text that's hidden
// keeps the colour it has now, rather than taking the transparent one.
// Read before any text is hidden.
const kept = skeleton.textParts.flatMap((part) =>
leftOut(part).map(
(element) => [element, getComputedStyle(element).color] as const
)
);
// Text goes through its colour, so a frame drawn by the same element,
// such as a badge's pill, stays
skeleton.textParts.forEach((part) => {
if (!this._hiddenColor.has(part)) {
this._hiddenColor.add(part);
hideStyle(part, "color", "transparent");
}
});
kept.forEach(([element, color]) => {
if (!this._keptColor.has(element)) {
this._keptColor.set(element, element.style.color);
}
element.style.color = color;
});
// In the same frame as the hiding, so no transition runs on it
[...skeleton.parts, ...skeleton.textParts].forEach((part) => {
if (!this._heldTransition.has(part)) {
this._heldTransition.add(part);
hideStyle(part, "transition", "none");
}
});
}
private _showParts() {
this._hiddenOpacity.forEach((part) => releaseStyle(part, "opacity"));
this._hiddenColor.forEach((part) => releaseStyle(part, "color"));
this._keptColor.forEach((color, element) => {
element.style.color = color;
});
this._heldTransition.forEach((part) => releaseStyle(part, "transition"));
this._hiddenOpacity.clear();
this._hiddenColor.clear();
this._keptColor.clear();
this._heldTransition.clear();
}
/* Show the content again before the next paint, and note what to fade in */
private _endLoading() {
// Under a skeleton of its own, or before the first reading, the whole
// content was hidden rather than its parts
const wholeContent = this._customSkeleton || this._pieces === undefined;
this._arriving = {
content: wholeContent
? (this._contentSlot?.assignedElements() ?? [])
: [],
// Only what this overlay is the last to hide shows now; a part a
// nested overlay still hides stays hidden, and fades in with that one
opacityParts: [...this._hiddenOpacity].filter(
(part) => holdersOf(part, "opacity") === 1
),
colorParts: [...this._hiddenColor].filter(
(part) => holdersOf(part, "color") === 1
),
};
this._showParts();
this._pieces = undefined;
}
/* Fade each arriving part in, instantly with reduced motion */
private _fadeIn({ content, opacityParts, colorParts }: ArrivingParts) {
// In ms or s, as the token can be either; 150ms only when it isn't set
const token = getComputedStyle(this)
.getPropertyValue("--ha-animation-duration-fast")
.trim();
const fade: KeyframeAnimationOptions = {
duration: token ? parseAnimationDuration(token) : 150,
easing: "ease-out",
};
this._fades = [
// To each part's own opacity, which isn't always 1
...[...content, ...opacityParts].map((part) => {
const opacity = getComputedStyle(part).opacity;
return part.animate([{ opacity: 0 }, { opacity }], fade);
}),
...colorParts.map((part) => {
const color = getComputedStyle(part).color;
return part.animate([{ color: "transparent" }, { color }], fade);
}),
];
}
private _cancelFades() {
this._fades.forEach((fade) => fade.cancel());
this._fades = [];
}
static readonly styles: CSSResultGroup = css`
:host {
display: block;
position: relative;
}
.content {
display: contents;
}
slot.hidden::slotted(*) {
opacity: 0;
}
.skeleton {
position: absolute;
inset: 0;
overflow: hidden;
border-radius: inherit;
pointer-events: none;
}
/* Rounded by the layer it fills, which follows the host */
.fill {
position: absolute;
inset: 0;
--ha-skeleton-border-radius: 0;
}
.piece {
position: absolute;
min-height: 0;
}
.piece.round {
--ha-skeleton-border-radius: var(--ha-border-radius-circle);
}
.piece.shape {
--ha-skeleton-border-radius: 0;
mask-size: 100% 100%;
-webkit-mask-size: 100% 100%;
mask-repeat: no-repeat;
-webkit-mask-repeat: no-repeat;
}
/* Text and icons on a dark bar over a picture */
.piece.on-dark {
--ha-skeleton-color: rgba(255, 255, 255, 0.3);
--ha-skeleton-sheen-color: rgba(255, 255, 255, 0.5);
}
`;
}
const pieceStyle = ({ maskBox, ...piece }: SkeletonPiece) => {
const maskPosition = maskBox ? `${maskBox.x}px ${maskBox.y}px` : undefined;
const maskSize = maskBox
? `${maskBox.width}px ${maskBox.height}px`
: undefined;
return styleMap({
left: `${piece.x}px`,
top: `${piece.y}px`,
width: `${piece.width}px`,
height: `${piece.height}px`,
"--ha-skeleton-border-radius": piece.radius,
"border-radius": piece.kind === "scrim" ? piece.radius : undefined,
"background-color": piece.background,
"mask-image": piece.mask,
"-webkit-mask-image": piece.mask,
"mask-position": maskPosition,
"-webkit-mask-position": maskPosition,
"mask-size": maskSize,
"-webkit-mask-size": maskSize,
});
};
declare global {
interface HTMLElementTagNameMap {
"ha-skeleton-overlay": HaSkeletonOverlay;
}
interface HASSDomEvents {
"skeleton-loading": SkeletonLoadingDetail;
}
// for add event listener
interface HTMLElementEventMap {
"skeleton-loading": HASSDomEvent<HASSDomEvents["skeleton-loading"]>;
}
}
-4
View File
@@ -4,15 +4,12 @@ import { customElement, property } from "lit/decorators";
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../../common/translations/localize";
import type { LogbookEntry } from "../../data/logbook";
import type { HomeAssistant } from "../../types";
import "./hat-logbook-note";
import "../../panels/logbook/ha-logbook-renderer";
import type { TraceExtended } from "../../data/trace";
@customElement("ha-trace-logbook")
export class HaTraceLogbook extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ type: Boolean, reflect: true }) public narrow = false;
@property({ attribute: false }) public trace!: TraceExtended;
@@ -26,7 +23,6 @@ export class HaTraceLogbook extends LitElement {
return this.logbookEntries.length
? html`
<ha-logbook-renderer
.hass=${this.hass}
.entries=${this.logbookEntries}
.narrow=${this.narrow}
no-detail
@@ -566,7 +566,6 @@ export class HaTracePathDetails extends LitElement {
return entries.length
? html`
<ha-logbook-renderer
.hass=${this.hass}
.entries=${entries}
.narrow=${this.narrow}
no-detail
+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,
});
+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,
};
+74
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[],
@@ -758,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;
};
@@ -2591,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;
@@ -2938,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);
+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;
+17 -7
View File
@@ -4,7 +4,7 @@ import type { TimestampStateDomain } from "../common/const";
import { computeDomain } from "../common/entity/compute_domain";
import { computeStateDomain } from "../common/entity/compute_state_domain";
import type { LocalizeFunc } from "../common/translations/localize";
import type { HomeAssistant } from "../types";
import type { HomeAssistant, HomeAssistantFormatters } from "../types";
import { UNAVAILABLE, UNKNOWN } from "./entity/entity";
import { isNumericEntity } from "./history";
@@ -316,24 +316,34 @@ const STATE_ACTION_MESSAGES: Record<
const RESTORABLE_BUTTON_DOMAINS = new Set(["button", "input_button"]);
export type LogbookStateFormatters = Pick<
HomeAssistantFormatters,
"formatEntityState" | "formatEntityAttributeValue"
>;
export const localizeStateMessage = (
hass: HomeAssistant,
localize: LocalizeFunc,
formatters: LogbookStateFormatters,
state: string,
stateObj: HassEntity,
domain: string,
entry?: LogbookEntry
): string => {
if (state === UNKNOWN || state === UNAVAILABLE) {
return hass.formatEntityState(stateObj, state);
return formatters.formatEntityState(stateObj, state);
}
// Events show the triggered event type, falling back to a generic label when
// the type is unknown (the timestamp state is meaningless on its own).
if (domain === "event") {
const eventType = entry?.attributes?.event_type;
if (eventType != null) {
return hass.formatEntityAttributeValue(stateObj, "event_type", eventType);
return formatters.formatEntityAttributeValue(
stateObj,
"event_type",
eventType
);
}
return hass.localize(`${LOGBOOK_LOCALIZE_PATH}.detected_event_no_type`);
return localize(`${LOGBOOK_LOCALIZE_PATH}.detected_event_no_type`);
}
const actionKey: LogbookActionMessage | undefined =
STATE_ACTION_MESSAGES[domain as keyof typeof STATE_ACTION_MESSAGES];
@@ -346,11 +356,11 @@ export const localizeStateMessage = (
actionKey &&
(!RESTORABLE_BUTTON_DOMAINS.has(domain) || matchesEntryTime)
) {
return hass.localize(`${LOGBOOK_LOCALIZE_PATH}.${actionKey}`);
return localize(`${LOGBOOK_LOCALIZE_PATH}.${actionKey}`);
}
// Every other domain reuses the backend state translation, so the logbook
// speaks the same vocabulary as the rest of the UI.
return hass.formatEntityState(stateObj, state);
return formatters.formatEntityState(stateObj, state);
};
export const filterLogbookCompatibleEntities = (entity) => {
+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);
+7 -1
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;
}
@@ -514,7 +520,7 @@ interface SelectBoxOptionImage {
export interface SelectOption {
value: string;
label: string;
label?: string;
description?: string;
image?: string | SelectBoxOptionImage;
disabled?: boolean;
+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",
+136 -2
View File
@@ -1,7 +1,8 @@
import type { Connection } from "home-assistant-js-websocket";
import type { Connection, UnsubscribeFunc } from "home-assistant-js-websocket";
import { getCollection } from "home-assistant-js-websocket";
import type { Store } from "home-assistant-js-websocket/dist/store";
import type { HassioAddonsInfo } from "../hassio/addon";
import type { CallWS } from "../../types";
import type { HassioAddonDetails, HassioAddonsInfo } from "../hassio/addon";
import type { HassioHassOSInfo, HassioHostInfo } from "../hassio/host";
import type { NetworkInfo } from "../hassio/network";
import type { HassioResolution } from "../hassio/resolution";
@@ -112,6 +113,139 @@ const subscribeSupervisorEventUpdates = (
}
);
const subscribeSupervisorEvents = (
conn: Connection,
onEvent: (event: SupervisorEvent) => void
) =>
conn.subscribeMessage<SupervisorEvent>(onEvent, {
type: "supervisor/subscribe",
});
export type SupervisorAppEvent =
// A store reload can change the latest version of any app
| { type: "store" }
| { type: "app"; slug: string; update: Partial<HassioAddonDetails> }
| {
type: "job";
slug: string;
// install, uninstall, update, rebuild or restore
operation: string;
done: boolean;
};
interface SupervisorJob {
name: string;
reference: string | null;
done: boolean;
child_jobs: SupervisorJob[];
}
// Settings in the v2 "app" status that the app info also has
const APP_SETTINGS_KEYS = [
"version_latest",
"update_available",
"boot",
"watchdog",
"ingress_panel",
"protected",
"auto_update",
] as const;
// Older Supervisors name the app manager jobs addon_manager_*
const appManagerOperation = (jobName: string | undefined) =>
/^(?:addon|app)_manager_(\w+)$/.exec(jobName ?? "")?.[1];
/**
* Parse a Supervisor event that changes the info of an app.
*/
export const parseSupervisorAppEvent = (
event: SupervisorEvent
): SupervisorAppEvent | undefined => {
// Supervisor sends "addon" with only the state, or with its v2 websocket API
// enabled "app" with the full status
if (event.event === "addon" || event.event === "app") {
const update: Partial<HassioAddonDetails> = {
// The app info never reports "stopping"; the app runs until it stops
...(event.state !== "stopping" && { state: event.state }),
// The version is null while the app is not installed
...(event.event === "app" && { version: event.version }),
// The status has no settings while the app is not installed
...(event.version &&
Object.fromEntries(APP_SETTINGS_KEYS.map((key) => [key, event[key]]))),
};
return { type: "app", slug: event.slug, update };
}
if (event.event === "store_reloaded") {
return { type: "store" };
}
const job = event.event === "job" ? event.data : undefined;
// Only manager jobs count: their child jobs share the slug, and start, stop
// and restart jobs change nothing beyond the state events. A manager job can
// itself be a child, for example of a backup restore.
// The first event of a job comes before Supervisor sets its reference.
if (!job?.reference) {
return undefined;
}
const operation = appManagerOperation(job.name);
if (!operation) {
return undefined;
}
return {
type: "job",
slug: job.reference,
operation,
done: job.done === true,
};
};
/**
* Return the app manager operations that run now, keyed by app slug.
*/
export const fetchAppOperations = async (
callWS: CallWS
): Promise<Record<string, string>> => {
const { jobs } = await callWS<{ jobs: SupervisorJob[] }>({
type: "supervisor/api",
endpoint: "/jobs/info",
method: "get",
});
const operations: Record<string, string> = {};
const addOperations = (list: SupervisorJob[]) => {
for (const job of list) {
const operation = appManagerOperation(job.name);
if (operation && job.reference && !job.done) {
operations[job.reference] = operation;
}
addOperations(job.child_jobs ?? []);
}
};
addOperations(jobs);
return operations;
};
/**
* Subscribe to Supervisor events that change app info. Events sent while the
* connection is down are lost, so `onReconnect` runs after each reconnect.
*/
export const subscribeSupervisorAppEvents = async (
conn: Connection,
onEvent: (appEvent: SupervisorAppEvent) => void,
onReconnect: () => void
): Promise<UnsubscribeFunc> => {
const unsub = await subscribeSupervisorEvents(conn, (event) => {
const appEvent = parseSupervisorAppEvent(event);
if (appEvent) {
onEvent(appEvent);
}
});
const handleReady = () => onReconnect();
conn.addEventListener("ready", handleReady);
return () => {
conn.removeEventListener("ready", handleReady);
unsub();
};
};
export const getSupervisorEventCollection = (
conn: Connection,
key: string,
+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"],
+4
View File
@@ -104,6 +104,10 @@ export const DOMAINS_HIDE_DEFAULT_MORE_INFO = [
/** Domains that should have the history hidden in the more info dialog. */
export const DOMAINS_MORE_INFO_NO_HISTORY = ["camera", "configurator"];
/** Whether the info view explains why the entity isn't available instead of showing it. */
export const computeShowUnavailableInfo = (stateObj?: HassEntity) =>
!stateObj || Boolean(stateObj.attributes.restored);
export const computeShowHistoryComponent = (
hass: HomeAssistant,
entityId: string
@@ -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"
);
@@ -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,
+135 -57
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,
@@ -84,6 +87,7 @@ import { showConfirmationDialog } from "../generic/show-dialog-box";
import {
computeShowHistoryComponent,
computeShowLogBookComponent,
computeShowUnavailableInfo,
DOMAINS_WITH_MORE_INFO,
EDITABLE_DOMAINS_WITH_ID,
EDITABLE_DOMAINS_WITH_UNIQUE_ID,
@@ -149,10 +153,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;
@@ -183,6 +189,8 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
@state() private _entry?: ExtEntityRegistryEntry | null;
private _entryLoadFailed = false;
@state() private _infoEditMode = false;
@state() private _detailsYamlMode = false;
@@ -196,12 +204,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,22 +221,31 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._detailsYamlMode = false;
this.large = params.large ?? false;
this._fill = false;
this._open = true;
this._loadEntityRegistryEntry();
}
private async _loadEntityRegistryEntry() {
if (!this._entityId) {
const entityId = this._entityId;
if (!entityId) {
return;
}
if (this._entry?.entity_id !== entityId) {
this._entry = undefined;
}
let entry: ExtEntityRegistryEntry | null | undefined;
let failed = false;
try {
this._entry = await getExtendedEntityRegistryEntry(
this.hass.callWS,
this._entityId
);
} catch (_e) {
this._entry = null;
entry = await getExtendedEntityRegistryEntry(this.hass.callWS, entityId);
} catch (err: any) {
// Other errors, like a lost connection, don't tell whether it's
// registered, so it loads again on reconnect
failed = err?.code !== "not_found";
entry = failed ? undefined : null;
}
if (this._entityId === entityId) {
this._entry = entry;
this._entryLoadFailed = failed;
}
}
@@ -259,14 +270,13 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
this._entityId = undefined;
this._parentEntityIds = [];
this._entry = undefined;
this._entryLoadFailed = false;
this._infoEditMode = false;
this._detailsYamlMode = false;
this._initialView = DEFAULT_VIEW;
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);
@@ -295,7 +305,8 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
private _shouldShowHistory(domain: string): boolean {
return (
DOMAINS_WITH_MORE_INFO.includes(domain) &&
(DOMAINS_WITH_MORE_INFO.includes(domain) ||
computeShowUnavailableInfo(this.hass.states[this._entityId!])) &&
(computeShowHistoryComponent(this.hass, this._entityId!) ||
computeShowLogBookComponent(this.hass, this._entityId!))
);
@@ -511,11 +522,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 +668,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 +730,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 +788,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 +847,10 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
></ha-icon-button>
${
domain === "camera"
domain === "camera" || hasLocation
? html`
${downloadSnapshotMenuItem}
${directionsMenuItem}
<wa-divider></wa-divider>
`
: nothing
@@ -945,7 +987,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
: nothing
}
${
domain === "camera"
domain === "camera" || hasLocation
? html`
<ha-dropdown
slot="headerActionItems"
@@ -961,6 +1003,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
.path=${mdiDotsVertical}
></ha-icon-button>
${downloadSnapshotMenuItem}
${directionsMenuItem}
</ha-dropdown>
`
: nothing
@@ -1071,6 +1114,25 @@ 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;
}
if (
this._entryLoadFailed &&
changedProps.has("hass") &&
this.hass.connected &&
!(changedProps.get("hass") as HomeAssistant | undefined)?.connected
) {
this._loadEntityRegistryEntry();
}
}
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
this.addEventListener("close-dialog", () => this.closeDialog());
@@ -1140,10 +1202,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 +1215,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 +1273,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 +1291,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;
+12 -34
View File
@@ -1,5 +1,5 @@
import type { HassEntity } from "home-assistant-js-websocket";
import { css, html, LitElement, nothing } from "lit";
import { css, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import { computeDomain } from "../../common/entity/compute_domain";
import type { ExtEntityRegistryEntry } from "../../data/entity/entity_registry";
@@ -8,12 +8,14 @@ import {
computeShowHistoryComponent,
computeShowLogBookComponent,
computeShowNewMoreInfo,
computeShowUnavailableInfo,
DOMAINS_FULL_HEIGHT_MORE_INFO,
DOMAINS_NO_INFO,
DOMAINS_WITH_MORE_INFO,
} from "./const";
import "./ha-more-info-history";
import "./ha-more-info-logbook";
import "./ha-more-info-unavailable";
import "./more-info-content";
@customElement("ha-more-info-info")
@@ -31,41 +33,21 @@ export class MoreInfoInfo extends LitElement {
protected render() {
const entityId = this.entityId;
const stateObj = this.hass.states[entityId] as HassEntity | undefined;
const entityRegObj = this.hass.entities[entityId];
if (!stateObj || computeShowUnavailableInfo(stateObj)) {
return html`<ha-more-info-unavailable
.entry=${this.entry}
.stateObj=${stateObj}
></ha-more-info-unavailable>`;
}
const domain = computeDomain(entityId);
const isNewMoreInfo = stateObj && computeShowNewMoreInfo(stateObj);
const isNewMoreInfo = computeShowNewMoreInfo(stateObj);
const isFullHeight =
isNewMoreInfo || DOMAINS_FULL_HEIGHT_MORE_INFO.includes(domain);
return html`
<div class="container" data-domain=${domain}>
${
!stateObj
? html`<ha-alert alert-type="warning">
${
this.entry?.disabled_by
? this.hass.localize(
"ui.dialogs.entity_registry.editor.entity_disabled"
)
: this.hass.localize(
"ui.dialogs.entity_registry.editor.unavailable"
)
}
</ha-alert>`
: nothing
}
${
stateObj?.attributes.restored && entityRegObj
? html`<ha-alert alert-type="warning">
${this.hass.localize(
"ui.dialogs.more_info_control.restored.no_longer_provided",
{
integration: entityRegObj.platform,
}
)}
</ha-alert>`
: nothing
}
<div class="content">
${
DOMAINS_NO_INFO.includes(domain) || isNewMoreInfo
@@ -153,10 +135,6 @@ export class MoreInfoInfo extends LitElement {
ha-more-info-logbook {
margin-inline: calc(var(--ha-space-6) * -1);
}
ha-alert {
display: block;
}
`;
}
@@ -0,0 +1,455 @@
import {
mdiCancel,
mdiHelpCircleOutline,
mdiPowerPlugOffOutline,
} from "@mdi/js";
import type { ContextType } from "@lit/context";
import type { HassEntity } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import "@home-assistant/components/card";
import { consume } from "../../common/decorators/consume";
import { transform } from "../../common/decorators/transform";
import { fireEvent } from "../../common/dom/fire_event";
import { navigate } from "../../common/navigate";
import {
adaptiveDialogModeContext,
type DialogSheetMode,
} from "../../components/ha-adaptive-dialog";
import "../../components/ha-alert";
import "../../components/ha-button";
import "../../components/ha-empty-state";
import "../../components/ha-relative-time";
import type { ConfigEntry } from "../../data/config_entries";
import { ERROR_STATES } from "../../data/config_entries";
import {
apiContext,
configContext,
configEntriesContext,
formattersContext,
internationalizationContext,
} from "../../data/context";
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import type { HistoryStates } from "../../data/history";
import type { ExtEntityRegistryEntry } from "../../data/entity/entity_registry";
import { updateEntityRegistryEntry } from "../../data/entity/entity_registry";
import { domainToName } from "../../data/integration";
import { renderConfigEntryError } from "../../panels/config/integrations/render-config-entry-error";
import { showAlertDialog } from "../generic/show-dialog-box";
/**
* @element ha-more-info-unavailable
* @summary Info view of an entity that has no state or that its integration
* doesn't provide, with the reason and how to make it available again.
*/
@customElement("ha-more-info-unavailable")
export class HaMoreInfoUnavailable extends LitElement {
/** `undefined` while the entry loads, `null` when the entity isn't registered. */
@property({ attribute: false }) public entry?: ExtEntityRegistryEntry | null;
/** The `restored` state core keeps while the integration doesn't provide the entity. */
@property({ attribute: false }) public stateObj?: HassEntity;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@state()
@consume({ context: configContext, subscribe: true })
@transform<ContextType<typeof configContext>, boolean>({
transformer: ({ user }) => Boolean(user?.is_admin),
})
private _isAdmin = false;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@state()
@consume({ context: formattersContext, subscribe: true })
private _formatters!: ContextType<typeof formattersContext>;
@state()
@consume({ context: configEntriesContext, subscribe: true })
private _configEntries?: ConfigEntry[];
/** `null` when the history has no state from before. */
@state() private _lastKnown?: { state: string; until: Date } | null;
@state()
@consume({ context: adaptiveDialogModeContext, subscribe: true })
private _dialogMode?: DialogSheetMode;
@state() private _enabling = false;
private _lastKnownRequest = 0;
@state() private _error?: string;
protected willUpdate(changedProps: PropertyValues<this>) {
super.willUpdate(changedProps);
const platform = this.entry?.platform;
if (platform && changedProps.get("entry")?.platform !== platform) {
// Only the titles of loaded integrations are fetched by default
this._i18n.loadBackendTranslation("title", platform);
}
if (
changedProps.has("stateObj") &&
changedProps.get("stateObj")?.last_changed !== this.stateObj?.last_changed
) {
this._fetchLastKnown();
}
}
private async _fetchLastKnown() {
this._lastKnown = undefined;
const request = ++this._lastKnownRequest;
const stateObj = this.stateObj;
if (!stateObj) {
return;
}
const end = new Date(stateObj.last_changed);
// Short periods first, as a sensor can write thousands of states a day
for (const days of [1, 7, 30]) {
let history: HistoryStates;
try {
// eslint-disable-next-line no-await-in-loop
history = await this._api.callWS<HistoryStates>({
type: "history/history_during_period",
start_time: new Date(end.getTime() - days * 86400000).toISOString(),
end_time: end.toISOString(),
entity_ids: [stateObj.entity_id],
minimal_response: true,
no_attributes: true,
});
} catch (_err) {
this._lastKnown = null;
return;
}
if (request !== this._lastKnownRequest) {
return;
}
const states = history[stateObj.entity_id] ?? [];
for (let i = states.length - 1; i >= 0; i--) {
if (states[i].s !== UNAVAILABLE && states[i].s !== UNKNOWN) {
const next = states[i + 1];
this._lastKnown = {
state: states[i].s,
until: next ? new Date((next.lc ?? next.lu) * 1000) : end,
};
return;
}
}
}
this._lastKnown = null;
}
protected render() {
return html`
<div
class=${classMap({
container: true,
"bottom-sheet": this._dialogMode === "bottom-sheet",
})}
>
${this._renderContent()}
</div>
`;
}
private _renderContent() {
if (this.entry === undefined) {
return nothing;
}
const localize = this._i18n.localize;
if (this.entry === null) {
return html`
<ha-empty-state
.icon=${mdiHelpCircleOutline}
.heading=${localize(
"ui.dialogs.more_info_control.unavailable.not_found_title"
)}
.description=${localize(
"ui.dialogs.more_info_control.unavailable.not_found"
)}
></ha-empty-state>
`;
}
const entry = this.entry;
const integration = domainToName(localize, entry.platform);
if (!entry.disabled_by) {
const configEntry = entry.config_entry_id
? this._configEntries?.find(
(item) => item.entry_id === entry.config_entry_id
)
: undefined;
return html`
<ha-empty-state
.icon=${mdiPowerPlugOffOutline}
.heading=${localize(
"ui.dialogs.more_info_control.unavailable.not_provided_title"
)}
.description=${this._notProvidedDescription(integration, configEntry)}
>
${this._renderDetails(configEntry)}
${this._isAdmin ? this._renderOpenIntegration() : nothing}
</ha-empty-state>
`;
}
const canEnable =
entry.disabled_by === "user" || entry.disabled_by === "integration";
return html`
<ha-empty-state
.icon=${mdiCancel}
.heading=${localize(
"ui.dialogs.more_info_control.unavailable.disabled_title"
)}
.description=${localize(
`ui.dialogs.more_info_control.unavailable.disabled_by.${entry.disabled_by}`,
{ integration }
)}
>
${
this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing
}
${
!this._isAdmin
? nothing
: canEnable
? html`
<ha-button
.loading=${this._enabling}
.disabled=${this._enabling}
@click=${this._enableEntry}
>
${localize(
"ui.dialogs.more_info_control.unavailable.enable_entity"
)}
</ha-button>
`
: entry.disabled_by === "device" && entry.device_id
? html`
<ha-button appearance="plain" @click=${this._openDevice}>
${localize(
"ui.dialogs.more_info_control.unavailable.open_device"
)}
</ha-button>
`
: this._renderOpenIntegration()
}
</ha-empty-state>
`;
}
private _notProvidedDescription(
integration: string,
configEntry?: ConfigEntry
) {
const localize = this._i18n.localize;
const key = "ui.dialogs.more_info_control.unavailable.integration_state";
switch (configEntry?.state) {
case "setup_retry":
return localize(`${key}.setup_retry`, { integration });
case "setup_error":
case "migration_error":
return localize(`${key}.setup_error`, { integration });
case "setup_in_progress":
return localize(`${key}.setup_in_progress`, { integration });
case "not_loaded":
case "failed_unload":
case "unload_in_progress":
return localize(`${key}.not_loaded`, { integration });
default:
return localize(
this.stateObj
? `${key}.no_longer_provided`
: "ui.dialogs.more_info_control.unavailable.not_provided",
{ integration }
);
}
}
private _renderDetails(configEntry?: ConfigEntry) {
const localize = this._i18n.localize;
const key = "ui.dialogs.more_info_control.unavailable.details";
const reason =
this._isAdmin &&
configEntry?.reason &&
ERROR_STATES.includes(configEntry.state)
? renderConfigEntryError(this._i18n, configEntry)
: undefined;
// Only the history tells since when, the restored state's last_changed is the last restart
const lastKnown = this.stateObj ? this._lastKnown : undefined;
if (!reason && !lastKnown) {
return nothing;
}
return html`
<hac-card>
<dl>
${
reason
? html`<div class="stacked">
<dt>${localize(`${key}.reason`)}</dt>
<dd>${reason}</dd>
</div>`
: nothing
}
${
lastKnown
? html`<div>
<dt>${localize(`${key}.unavailable_since`)}</dt>
<dd>
<ha-relative-time
.datetime=${lastKnown.until}
capitalize
></ha-relative-time>
</dd>
</div>
<div>
<dt>${localize(`${key}.last_known_state`)}</dt>
<dd>
${this._formatters.formatEntityState(
this.stateObj!,
lastKnown.state
)}
</dd>
</div>`
: nothing
}
</dl>
</hac-card>
`;
}
private _renderOpenIntegration() {
return html`
<ha-button appearance="plain" @click=${this._openIntegration}>
${this._i18n.localize(
"ui.dialogs.more_info_control.unavailable.open_integration"
)}
</ha-button>
`;
}
private _openIntegration() {
navigate(`/config/integrations/integration/${this.entry!.platform}`);
}
private _openDevice() {
navigate(`/config/devices/device/${this.entry!.device_id}`);
}
private async _enableEntry() {
this._error = undefined;
this._enabling = true;
try {
const result = await updateEntityRegistryEntry(
this._api.callWS,
this.entry!.entity_id,
{ disabled_by: null }
);
fireEvent(this, "entity-entry-updated", result.entity_entry);
if (result.require_restart) {
showAlertDialog(this, {
text: this._i18n.localize(
"ui.dialogs.entity_registry.editor.enabled_restart_confirm"
),
});
}
if (result.reload_delay) {
showAlertDialog(this, {
text: this._i18n.localize(
"ui.dialogs.entity_registry.editor.enabled_delay_confirm",
{ delay: result.reload_delay }
),
});
}
} catch (err: any) {
this._error = err.message;
} finally {
this._enabling = false;
}
}
static styles = css`
:host {
display: flex;
flex: 1;
}
.container {
display: flex;
flex: 1;
min-height: 400px;
}
/* The bottom sheet has a fixed height, which is lower on a phone in landscape */
.container.bottom-sheet {
min-height: 0;
}
ha-empty-state {
flex: 1;
height: auto;
}
hac-card {
width: 100%;
--hac-card-content-padding: var(--ha-space-3) var(--ha-space-4);
}
dl {
display: flex;
flex-direction: column;
gap: var(--ha-space-2);
margin: 0;
text-align: start;
}
dl > div {
display: flex;
gap: var(--ha-space-4);
justify-content: space-between;
}
dl > div.stacked {
flex-direction: column;
gap: 0;
}
.stacked dd {
text-align: start;
}
dt {
flex: none;
color: var(--secondary-text-color);
}
dd {
margin: 0;
text-align: end;
overflow-wrap: anywhere;
}
ha-alert {
display: block;
text-align: start;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-more-info-unavailable": HaMoreInfoUnavailable;
}
}
+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,
});
}
});
}
+1 -1
View File
@@ -158,7 +158,7 @@ class DialogEditSidebar extends DirtyStateProviderMixin<SidebarState>()(
].map<DisplayItem>((panel) => ({
value: panel.url_path,
label:
(getPanelTitle(this.hass, panel) || panel.url_path) +
(getPanelTitle(this.hass.localize, panel) || panel.url_path) +
`${defaultPanel === panel.url_path ? ` (${this.hass.localize("ui.sidebar.default")})` : ""}`,
icon: getPanelIcon(panel),
iconPath: getPanelIconPath(panel),
@@ -145,7 +145,9 @@ export class HaVoiceAssistantSetupDialog extends LitElement {
return html`
<ha-dialog
.open=${this._open}
header-title="Voice Satellite setup"
header-title=${this.hass.localize(
"ui.panel.config.voice_assistants.satellite_wizard.title"
)}
prevent-scrim-close
@closed=${this._dialogClosed}
>
Loaded 100 of 374 files, more files were not shown because too many files have changed in this diff. Show more