Compare commits

..
229 Commits
Author SHA1 Message Date
WendelinandClaude Opus 5.5 fb7d5eb3af Prepare @home-assistant/components for its first beta release
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-04 11:27:14 +01:00
WendelinandClaude Opus 5.5 4bc3b0e9b0 Add hac-popover to the component library (#56348)
* Add hac-popover and a shared popup base to the component library

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

* Let themes set the popover's border, radius and padding

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

* Use a 1px border on the popover

Browsers round sub-pixel borders up to 1px anyway.

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

* Say why the popover closed and type its trigger

The hide events carry detail.reason, so a parent can react differently to
Escape than to a click outside. The trigger takes one word: click, hover
(which still opens on click) or manual.

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

* Hand aria-expanded to button components and document popover usage

The popover sets the ariaExpanded property instead of the attribute, so a
button component can pass it on to its inner button. Native buttons still
get the attribute. The JSDoc explains how to use the popover and that it is
not a tooltip. aria-controls and the generated id are gone, as no screen
reader relies on them.

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

* Say that the anchor hook does nothing by default

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

* Make the popup's open and close checks easier to read

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

* Use only semantic tokens in the popover

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

* Follow a replaced anchor and keep state when a hide is cancelled

A parent may render a new anchor with the same id; capture listeners on the
root bind it before its own events run. A cancelled hide keeps focus where
it is and keeps the popover pinned. Old browsers without min() keep the
popover within the free space.

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

* Handle trigger changes, programmatic opens and anchor changes while open

Hover timers check the trigger when they fire. An anchor click closes a
popover opened from code. Open popups are tracked on window, so scoped
copies share one Escape order. While open, the popup rebinds to a replaced
anchor or closes when it is gone.

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

* Notice a removed anchor through autoUpdate instead of a MutationObserver

autoUpdate's ResizeObserver already fires when the anchor leaves the DOM,
so the reposition callback checks isConnected and rebinds or closes.

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

* Keep the popover working inside a closed shadow root

A press inside a closed shadow root only shows its host to the document,
so the popup decides after its own and the anchor's listeners have seen
the press. Focus inside is looked up from the popup's own root.

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

* Keep the popover at its anchor and hide it while the anchor is scrolled away

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

* Drop the undocumented base part of the popover

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-04 09:48:48 +00:00
afe3e31d9c Don't list disabled entities under the Unavailable status filter (#56438)
Claude-Session: https://claude.ai/code/session_01CDc15sh8fUNmnB9T6EqcML

Co-authored-by: stoppyz0r <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-04 09:08:45 +00:00
Petar Petrov db89abfc52 Measure initial column count in sections view before first render (#56424)
* Measure initial column count in sections view before first render

* Read column gap from custom property in sections view

* Resolve sections view column gap to pixels
2026-12-04 08:59:16 +00:00
cerealkiller57540andcerealkiller57540 1633f06297 Add a theme variable for the media browser list item background (#56456)
Co-authored-by: cerealkiller57540 <[email protected]>
2026-12-04 08:50:19 +00:00
Paul Bottein 7fec500672 Move gauge card editor translations to the standard structure (#56429) 2026-12-04 08:47:10 +00:00
WendelinandClaude Opus 5.5 237fd4341a Add an empty state to the installed apps page (#56434)
* Add an empty state to the installed apps page

Without installed apps, the page showed a search for 0 apps and a small
link card. It now shows an empty state like the automation, scene and
script pickers, with a centered Install app button and popular apps from
the store fading in one after another around it and drifting slowly.

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

* Give each featured app a fixed place and drop the fill-up

Featured apps and their places are one list now. An app missing from
the store leaves its place empty instead of being replaced by another
store app, so the list of hidden apps is no longer needed.

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

* Move the apps empty state into a lazy-loaded component

The empty state, its store request and the icon reveal now live in
supervisor-apps-empty-state, which the installed apps page only loads
when no app is installed. The component reads contexts instead of hass,
so fetchSupervisorStore takes callWS now.

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

* Load the store apps with try/catch

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-04 08:39:28 +00:00
Paul Bottein 9b5ad7d6bd Move tile card editor translations up to the card level (#56428) 2026-12-04 08:36:35 +00:00
dependabot[bot] b6a6c17053 Bump cross-spawn from 7.0.6 to 7.1.2 (#56457)
Bumps [cross-spawn](https://github.com/moxystudio/node-cross-spawn) from 7.0.6 to 7.1.2.
- [Release notes](https://github.com/moxystudio/node-cross-spawn/releases)
- [Changelog](https://github.com/moxystudio/node-cross-spawn/blob/master/CHANGELOG.md)
- [Commits](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.6...v7.1.2)

---
updated-dependencies:
- dependency-name: cross-spawn
  dependency-version: 7.1.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-12-04 08:35:39 +00:00
Petar Petrov 971fe1fec6 Move typed Lovelace editor hosts to contexts (#56408)
* Move typed Lovelace editor hosts to contexts

Entities, glance, distribution, map and stack card editors and the sub-element editor read localize and states from contexts and drop the ha-form hass binding.

* Don't throw in consumeLocalize before the context has a value

ha-form consumes localize since #56402, so the gallery threw before provideHass ran.

* Move the consumeLocalize fix to its own PR

It lands separately in #56418.
2026-12-04 08:33:42 +00:00
Clément NotinandWendelin 60d1400f46 Show keyboard shortcuts for reordering items (#55747)
* Add keyboard shortcut hints for moving editor rows

* Limit move shortcut hints to dashboard condition handles

* Show keyboard reorder hints on drag handles

* Show reorder shortcut hints only when focused

* Fix reorder shortcut hints from review

* Fix reorder shortcut hints and preserve accessible names

* Use upstream tooltip description association

* Clear reorder tooltip association when disabled

* Prepare Web Awesome tooltip dependency update

* Update Web Awesome to 3.15.0-ha.0

* Fix copilot review

---------

Co-authored-by: Wendelin <[email protected]>
2026-12-04 08:33:13 +00:00
Petar Petrov f6cdf9cc5f Stop re-rendering ha-sidebar on unrelated entity state updates (#56419)
* Stop re-rendering ha-sidebar on unrelated entity state updates

* Move count updates out of shouldUpdate and test countInstallableUpdates
2026-12-04 08:29:57 +00:00
renovate[bot] 3273d6804a Update dependency @rspack/core to v2.3.5 (#56455)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-04 09:28:38 +01:00
WendelinandClaude Opus 5.5 dad8eebe51 Upgrade webawesome to 3.15.0-ha.0 (#56440)
* Upgrade webawesome to 3.15.0-ha.0

Use the new button-group and tooltip part names, and describe the editor
mode shortcut tooltips instead of labelling their buttons with them.

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

* Re-seed bundle budget for Web Awesome 3.15

Web Awesome 3.15 inlines 100 system icons instead of 61 in
library.system.js (+27.6 KiB), which wa-icon imports statically, so
every entrypoint using Web Awesome components grows. New translation
strings add another 3.3 KiB.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-04 09:26:24 +01:00
Nathan Burns 86a05fb48b Add occupancy sensor to the area settings dialog (#56377)
Core stores one motion or occupancy entity per area (home-assistant/core#195471). Add the field to the area registry types and a picker for it next to the temperature and humidity sensors.
2026-12-04 09:21:31 +01:00
Lazizbek Ergashev 493579cee0 Keep pinging the backend after a reconnect (#56452) 2026-12-04 09:11:17 +01:00
Erik Montnemery 1b7932bf91 Clear the name when duplicating a YAML-only script or automation (#56454) 2026-12-04 09:08:27 +01:00
Erik Montnemery aa1d28022b Normalize script config in the YAML editor and for new scripts (#56453)
* Normalize script config in the YAML editor and for new scripts

* Normalize null YAML before accessing the config sequence
2026-12-04 08:37:53 +01:00
Erik Montnemery ed63a7a4bb Fall back to service when describing an action (#56451) 2026-12-04 08:35:12 +01:00
renovate[bot] ee8ae2a2ef Update dependency marked to v18.4.0 (#56445)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-03 18:51:52 +00:00
renovate[bot] 5b73d7bb50 Update dependency tar to v8.0.4 (#56444)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-03 18:50:29 +00:00
Matthias de BaatandClaude Opus 5.5 194356846b Revert "Add design to the AI policy" (#56439)
Revert "Add design to the AI policy (#55795)"

This reverts commit 432762a2ea.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-03 19:39:46 +01:00
Maarten Lakerveld 0f2148445b Use the entity state names from home-assistant-js-websocket (#56442)
home-assistant-js-websocket 9.9.0 renamed the state types and
subscription helpers to avoid confusion with the entity registry and
deprecated the old names: HassEntity, HassEntities, HassEntityBase,
HassEntityAttributeBase and subscribeEntities.
2026-12-03 19:38:39 +01:00
Bram KragtenandClaude Opus 5.5 0a637a0d52 Harden pull_request_target workflows and check workflows with zizmor (#56432)
Run zizmor in CI so a new privileged trigger or template injection is
caught in review, and fix the two findings it reports today. Give the
labeler an empty top-level token and cap both pull_request_target jobs
at 10 minutes.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-03 17:50:45 +02:00
WendelinandClaude Opus 5.5 c09bfad8c2 Return the focus to the opener after a dialog closes (#56426)
* Return the focus to the opener after a dialog closes

DialogMixin dialogs never returned the focus, because the manager removed
its focus listener during the same dialog-closed dispatch. A dialog opened
from another one now returns the focus to where the first one would have,
and the manager no longer takes away focus the browser already restored.

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

* Stop waiting for a stale dialog history entry after a timeout

A dialog entry left in the history with no dialog open kept the next
dialog from ever opening when nothing went back from it. Wait at most
DIALOG_WAIT_TIMEOUT, like navigate() does, then show the dialog in that
entry.

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

* Say what the focus restore test expects

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-03 17:50:05 +02:00
WendelinandClaude Opus 5.5 d9f115b5c6 Move the add integration dialog to contexts and DialogMixin (#56425)
* Move the add integration dialog to contexts and DialogMixin

The add device or integration dialog and ha-domain-integrations read
from Lit contexts instead of hass. The dialog uses DialogMixin, so
the contexts are connected before it loads.

protocolIntegrationPicked and getIntegrationDescriptions take the
plain values they need instead of hass, so their callers update too.

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

* Open config flows from the add dialog's parent

The config flow keeps the element it was opened from, to show the
application credentials dialog and restart the flow later. With
DialogMixin the add dialog is gone by then, so ha-domain-integrations
now gets the dialog's saved parent and opens flows from it.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-03 17:49:41 +02:00
Felipe Santos 081506950c Call each domain's own toggle action from dashboard cards (#56381)
* Use cover.toggle for the toggle action on covers

Core's cover toggle stops a moving cover, moves a part-open one away from its last move and can reach a device's own toggle (ESPHome toggle_action). The card picked open or close from the state on screen, so it could do none of that.

* Call the domain's toggle action when it has one

Core decides what toggle does: covers and valves stop while moving and
otherwise reverse their last move. Domains without a toggle action, such
as lock, button and scene, keep the on or off choice. Valves now need
open and close support to offer Toggle, as covers do.

* Keep the valve feature enum out of the entry bundles
2026-12-03 16:30:20 +01:00
Paul Bottein ef0348cc97 Keep the cover moving arrows clear of the handle (#56435) 2026-12-03 16:26:51 +01:00
Paul Bottein 9503f4077c Move tile card editor translations to a standard structure (#56370) 2026-12-03 15:02:07 +01:00
Paul Bottein b6f38595a5 Use a round handle with chevrons in the cover drawing (#56420)
* Use a round handle with chevrons in the cover drawing

* Keep the cover handle centered on the edge at the ends
2026-12-03 14:51:15 +01:00
Aidan Timson 9c70ae4153 Tell agents which docs a frontend change needs (#56423)
* Tell agents which docs repositories a frontend change needs

* Describe the demo embed as a public API in the demo skill

* Keep skills current with the code they describe
2026-12-03 15:26:35 +02:00
Paul Bottein 1e5c78d802 Use the state selector in more feature editors (#56412) 2026-12-03 14:48:26 +02:00
Lex PostmaandClaude Opus 5.5 306fe007f7 Add "No …" options to filters (#56026)
* Add "No …" options and an Includes/Excludes toggle to filters

Filters can now show the items without an area, device, label, category,
device class, voice assistant or blueprint, and show the items that don't
match their selection instead of the ones that do.

- A segmented Includes/Excludes toggle on the Area, Device, Label,
  Category, Integration, Domain, Device class, Voice assistant, Entity and
  Blueprint filters of the config tables, the Type, Integration and
  Triggered by filters of History and Logbook, the Locations filter of
  Backups, and the Level and Integration filters of the Logs errors list.
- An excluding filter shows a "≠" in its count badge, so this stays clear
  while it is collapsed.
- Links keep the new choices with `no_<param>=1` and `exclude=<params>`.
- A filter that only includes ids still sends a plain list, so stored
  filters and pages that don't use the mode keep working.
- The Logbook keeps activity without an entity, like Home Assistant
  starting, while it only excludes.

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

* Address review: refresh No blueprint, disabled helpers, logbook live updates

- Look up the items without a blueprint again when automations or scripts
  are added or removed, as No area and No device already do.
- Let the Helpers device filter match disabled helpers, as its area filter
  does, so No device and Excludes stay each other's complement.
- Resume logbook live updates when an exclusion-only entity filter leaves
  nothing to show, as the cause filter already does.

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

* Label the filter mode With and Without

"Includes" and "Excludes" are long in most languages. Next to the Any/All
toggle of home-assistant/frontend#56040 they only fit on one row of the
filter pane in English; "With" and "Without" fit in most languages, and
read naturally with what a filter picks, such as "With: Kitchen".

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

* Get the current blueprints when finding items without one

A blueprint can be imported while the automations or scripts page stays
open, so No blueprint fetches the blueprints again instead of using the
list from when the filter first loaded. This also updates that list.

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

* Limit and reuse the No device and No blueprint lookups

No device searched each automation, script or scene at once, so a large
setup sent hundreds of requests in parallel, and every mode change ran the
whole search again. The searches now run 10 at a time, and the result is
reused until the items, devices or entities change or the page is shown
again. No blueprint does the same for its search of each blueprint.

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

* Look up No device and No blueprint again when the page is shown

An automation, script or scene can be edited while the cached page is
hidden. Dropping the cached lookup alone didn't refresh a filter that
stays selected, so search again when No device or No blueprint is
selected.

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

* Store a filter's mode when nothing is selected

The config tables only stored a filter when the URL changed, so a link
isn't stored as the user's choice. The URL leaves out the mode of a filter
without a selection, so picking With or Without then wasn't stored, and
the table opened again with the other mode. Also store a change to the
mode.

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

* Only look up No device again when device links change

The lookup of the automations, scripts and scenes without a device was
dropped on any device or entity registry update, like renaming an entity,
so a large setup searched each item again. Keep it while the devices and
the device of each entity the search uses stay the same.

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

* Look up No device and No blueprint again after reconnecting

Home Assistant may have restarted with edited automations or scripts while
the connection was down, without their entity ids or the registries
changing. Drop the cached lookups and search again when the connection
comes back with No device or No blueprint selected.

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

* Leave the With/Without toggle for another PR

Reviewers asked to keep this PR to the "No …" options. The With/Without
toggle, its badge and the `exclude` URL param move to their own PR, and the
filters and pages that only changed for it are as on dev again.

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

* Keep No device and No blueprint lookups to their own items

The lookups were cached on every state id, so any entity being added or
removed searched all automations, scripts or scenes again. They now
compare only the ids of the items they look up.

A lookup that a newer one replaces is now aborted, so it starts no more
searches and the limit of 10 at a time holds.

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

* Reject a mapping that aborts during its last calls

The workers only checked the signal before starting a call, so an abort
while the last calls ran still resolved with their results.

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

* Stop No device and No blueprint lookups when the filter leaves the page

A lookup kept searching after the page was left, and its cache was only
thrown away on return. Leaving the page now aborts it, and the newer
request id makes it drop its result.

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

* Put the "No …" options at the top of the filters, without italics

As asked in review, the options now match "No area" from #55629: first in
the list and in the same style as the other options. "No area" is back at
the top.

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

* Skip the state scan, repeat searches and stateless entities in filters

- The No device and No blueprint filters only collect the state ids while
  their option is ticked, so other state updates skip the scan.
- The page sending a filter's value back as a plain list no longer counts
  as a change, so it doesn't start the same searches again.
- No device class leaves out entities without a state, like disabled ones,
  as their class is unknown rather than missing.

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

* Keep No device working when the search fails for one item

Home Assistant can fail the related search for a single automation or
script, which failed the whole No device lookup and left the filter
without results. Leave that item out, as its devices are unknown, and
keep the other results.

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

* Keep No device to the entities and helpers tables

Finding the automations, scripts and scenes without a device takes a
search for each of them, which is too much for large setups. That will
come back in a follow-up built on a core endpoint that answers it in one
call. The entities and helpers tables keep No device, which the
registries tell.

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

* Match No voice assistant only once exposure is known

While the exposure settings load, or after loading them fails, no entity
is known to be exposed or not, so "No voice assistant" matches none of
them instead of all.

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

* Keep filtering when a related search fails

A blueprint or device whose related search fails now finds nothing,
so the filter still applies the others instead of not applying at all.
"No blueprint" doesn't keep a result with a failed search, so it looks
them up again next time, and falls back to the blueprints listed
already when getting them fails.

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

* Don't search picked blueprints twice with No blueprint

The lookup for "No blueprint" already searches every blueprint, so the
picked ones now come from it. Only a picked blueprint it didn't find,
such as one whose search failed, is searched again.

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

* Drop the limit on concurrent related searches

It was there for "No device" on automations, scripts and scenes, which
moved to a follow-up. The blueprint filter runs one search per
blueprint, which setups have few of, so it searches them all at once as
before.

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

* Match No blueprint only once every blueprint is searched

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-03 13:46:01 +01:00
Aidan TimsonandCopilot Autofix powered by AI 566b749518 Add a shared 12 or 24 hour time format selector (#56320)
* Add a shared 12 or 24 hour time format selector

* Fix locale handling in DateTimeFormat

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

* Format the time format selector example

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-12-03 14:41:20 +02:00
Paul Bottein 6a0da93a8c Use the state selector in the mode and select options feature editors (#56413) 2026-12-03 14:23:27 +02:00
Paul Bottein 423b62b8f0 Show climate and water heater modes in a fixed order in state pickers (#56411)
* Show climate and water heater modes in a fixed order in state pickers

* Keep the standard mode order in the single state picker

* Order the merged states of all entities
2026-12-03 14:23:26 +02:00
Petar Petrov 623a195e16 Move feature-hosting card reads to contexts (#56415)
The area, thermostat and humidifier cards and their editors read states, registries, i18n, formatters, config and themes from Lit contexts and keep hass only to forward it to features.
2026-12-03 12:58:28 +01:00
Petar Petrov 01a5dfdab2 Move Lovelace editor dialog reads to contexts (#56416)
* Move Lovelace editor dialog reads to contexts

Editor dialogs and preview hosts read localize, i18n, registries and config from contexts; documentation URL helpers take the version.

* Narrow the save config dialog's config context to the version

The help link only needs the core version, so the dialog no longer rerenders on other config changes.
2026-12-03 12:44:11 +01:00
Petar Petrov c17a70beef Move own reads of contract-forwarding Lovelace cards to contexts (#56410)
* Move own reads of contract-forwarding Lovelace cards to contexts

Entity, picture-elements, heading and stack cards keep hass only to forward it; computeEntityUnitDisplay takes formatters.

* Keep waiting for hass before rendering picture elements

hui-image still needs hass to resolve media-source state images.
2026-12-03 12:35:38 +01:00
Petar Petrov ef9e314132 Don't throw in consumeLocalize before the context has a value (#56418)
ha-form consumes localize since #56402, so the gallery threw before provideHass ran.
2026-12-03 10:56:49 +00:00
Petar Petrov b30871d7ef Move Lovelace contract callers to contexts (#56417)
calcUnusedEntities and computeUnusedEntities take states; pickers, editors and dialogs keep hass only for previews and stub configs.
2026-12-03 11:52:24 +01:00
Paul Bottein a47cc16bf1 Disable chips of a disabled multiple select (#56382) 2026-12-03 10:32:19 +00:00
Aidan Timson afae3420af Fade content in where it replaces a skeleton (#56105)
* Add a shared fade for content that replaces a skeleton

* Fade in data tables and device cells after their skeletons

* Fade in logs after their skeletons

* Use the shared skeleton and fade in the backup summary

* Fade in editors, onboarding and tile text after their skeletons

* Fade data table rows in only where they replace skeleton rows

* Skip a pending skeleton arrival when loading starts again

* Stub animations in the data table tests

* Build data table skeleton rows only while they show

* Fade only backup row text that replaced its skeleton

* Keep one padded span around the onboarding divider label

* Fade streamed logs in as their first lines arrive

* Fade streamed logs in only when the viewer was empty

* Fade logs in after a waiting message that followed their skeleton

* Stub animations in the live log dialog tests

* Let data table cell templates return directives

* Read the arrival fade duration in ms or s

* Only show backup supporting text with a description

* Start the skeleton arrival fade before the first paint
2026-12-03 10:26:48 +00:00
Aidan Timson 5868b7a595 Make up demo history and statistics like a real home, and let demo areas have a picture (#56174)
* Make up demo history that drifts and switches like a real home

* Make up demo statistics around each entity's state, with units and single statistics

* Import the statistics chart in the statistics graph card

* Let demo areas have a picture

* Count only whole hours in a demo statistic, without spreading them into Math.min or Math.max

* Place the demo energy tariffs from midnight for a single statistic

* Make up a demo statistic one day at a time, and none for an unknown ID

* Keep drifted demo values on the same side of 0 as the state

* Give demo power statistics in the unit asked for

* Scale a demo meter's change with the length of its period

* Speed up long demo statistics periods
2026-12-03 12:26:10 +02:00
Petar Petrov 4e2c2784b3 Use consumeLocalize and Themes type in ha-mermaid-diagram (#56407) 2026-12-03 10:23:33 +00:00
Aidan Timson a72cd0353b Add time card feature (#56316)
* Return the service call from the time and datetime setters

* Add time card feature

* Add time format option to the time card feature editor

* Fix time zone, pending writes and RTL in the time card feature

* Keep time selections until the entity updates and follow entity switches

* Match reported times to sent ones in the time card feature

* Confirm one sent time per report in the time card feature

* Avoid toSpliced in the time card feature

* Track each time card feature write by id

* Read only localize in the time card feature editor

* Confirm time card feature writes per entity in tested helpers
2026-12-03 10:16:47 +00:00
Aidan TimsonandCopilot Autofix powered by AI 0c480ef32e Render mermaid diagrams in markdown (#56333)
* Share the theme RGB variable parser between components

* Render mermaid code blocks in markdown as diagrams

* Add mermaid diagrams to the markdown gallery page

* Leave the copyleft ELK layout out of the mermaid build

* Refactor ha-mermaid-diagram and update markdown-worker

Refactor theme handling and improve SVG caching logic in ha-mermaid-diagram component. Update markdown-worker to wrap ha-mermaid-diagram in a div.

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

* Fill the mermaid cache inside the queued draw and fix its comments

* Keep mermaid diagrams drawn across detaching and theme changes

* Skip unwanted mermaid draws and draw in a hidden container

* Draw mermaid diagrams on see-through cards over the page colour

* Give mermaid diagram links the same rules as markdown links

* Keep the RGB variable parser in the QR code

* Scroll to headings from fragment links in diagrams

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-12-03 12:10:21 +02:00
Matthias AlphartandClaude Fable 5.2 985be1ba66 Show icon of selected option in ha-select field (#56406)
* Show icon of selected option in ha-select field

When the selected option of ha-select has an iconPath, render the icon
next to the value in the trigger field, like the dropdown items do.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* Remove ha-select rendering test

Co-Authored-By: Claude Fable 5.2 <[email protected]>

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
2026-12-03 09:44:07 +00:00
renovate[bot] 3823386297 Update dependency tar to v8.0.3 (#56393)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-03 11:34:21 +02:00
Thomas Freudenberg dfae0a7a38 Respect profile date format for date-only states (#56296) 2026-12-03 09:34:09 +00:00
Petar Petrov 45c5bb2d3f Rerender ha-form when the language changes (#56402)
* Rerender ha-form when the language changes

Consume the localize context in ha-form so labels and helpers update for forms that no longer get hass.

* Pass the consumed localize to ha-form fields
2026-12-03 09:32:42 +00:00
Petar Petrov 5429cd2bb1 Drop hass from the confirm entity rows (#56395)
The button, input button, lock, scene and script rows read contexts, and confirmAction takes the user id and localize.
2026-12-03 09:31:56 +00:00
Petar Petrov 2d5d97b8aa Migrate Lovelace service rows to contexts (#56394)
Date, time, fan, number, select and text rows consume entity state, i18n, formatters, config and the API instead of taking hass.
2026-12-03 09:31:29 +00:00
Petar Petrov f86e59b58e Move the condition evaluator onto Lit context (#56400)
* Move the condition evaluator onto Lit context

The visibility evaluator reads states, config, locale, registries and the connection from context; ha-visibility-status drops hass.

* Pass time condition inputs as separate values

Skip evaluator input rebuilds on hosts without conditions and drop the redundant hass trigger in the conditional listener mixin.
2026-12-03 09:30:36 +00:00
Petar Petrov e33b94e34c Move areas strategy editor and location condition editor to contexts (#56397)
getAreaGroupedEntities, resolveLocationZones and migrateLocationCondition take the values they read.
2026-12-03 09:29:53 +00:00
Petar Petrov 235a5d01e2 Drop hass from the display entity rows (#56398)
Climate, cover, event, humidifier, sensor, simple, timer, toggle, update, valve and attribute rows read their entity, localize, config and formatters from contexts.
2026-12-03 09:29:44 +00:00
Petar Petrov 8479c83c49 Move group, select and media player rows to contexts (#56399)
The rows read their entity, formatters, config and services from Lit contexts instead of hass.
2026-12-03 09:28:38 +00:00
Petar Petrov 6869fa1ad6 Pass separate values to computeTooltip in Lovelace tooltip users (#56396)
Buttons row, header and base, and the icon, state-icon and state-label picture elements read contexts instead of hass.
2026-12-03 09:28:05 +00:00
6bace34775 Add MQTT network visualization (#55786)
* Add MQTT network visualization

Add a map to the MQTT config panel that shows how MQTT devices, entities,
device triggers and tags are set up, where they came from and the topics
they use. A focused item shows its config, and a topic shows its stored
and live messages.

The topic view and the payload helpers are based on the MQTT explorer
from #55656.

Co-authored-by: Erwin Douna <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

* Fix MQTT map build and review findings

Keep the template placeholders of the broker tooltip intact for the
minifier, show tag scanners without a device, take hidden nodes before
renumbering the categories, ignore stale topic subscriptions, show the
QoS of the live subscription, follow theme and language changes, and
use narrow contexts in the config and message views.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Show the last message of MQTT tags and device triggers

Show the last received message of the topic of a focused tag or device
trigger in its tooltip, like for entities.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Show the raw MQTT payloads when the key diff finds no change

Parsing JSON hides changes in whitespace or in numbers beyond the safe
integer range, so show the previous and current payload instead.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Show the physics button on the MQTT map

With physics off, nodes in the MQTT map can be dragged. The
physicsToggle property is removed again, as nothing else uses it.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Group MQTT subentries under one node

Subentries share one "Subentries" source node, with the device of each
subentry right under it, instead of a source node per subentry above its
device. All sources have the same color.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Add a tree view to the MQTT map and show items on focus

A button switches the MQTT map between the graph and a tree from left
to right, remembered in the browser. Entities, device triggers and tags
start switched off in the legend; a focused device shows its own items,
and a focused item shows only itself with its topics.

ha-network-graph gets two opt-in properties: fixedLayout places the
nodes at the positions of the data, and hiddenCategories sets the
selection of the legend.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Show the graph icon on the tree view button in the tree view

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Keep the selected node left in the MQTT tree and ring every selection

In a fixed layout, which grows to the right like a tree, the selected
node sits at a quarter of the width and only its children to the right,
with room for their labels, decide the zoom.

The selected node of the MQTT map gets the ring color of the theme, also
an entity with a border color of its own.

Co-authored-by: Claude Opus 5.5 <[email protected]>

* Fit the network graph view after switching the layout

* Do not pin nodes dragged in a fixed network graph layout

* Animate the network graph view after switching the layout

* Keep the MQTT map layout button above the zoom reset button

* Move network graph nodes smoothly between the tree and force layouts

* Restore the force layout view and fit the tree after a layout switch

* Move the network graph view along with the nodes on a layout switch

* Focus the parent node when a node is deselected

* Keep force layout positions on legend changes in the tree and stop wheel zoom on reset

* Show the MQTT map details in an adaptive dialog on narrow screens

* Keep nodes of a fixed layout readable around a selected node

* Toggle MQTT map sources with the keyboard too

* Use the shared chart control frame for the MQTT source filter

* Announce the state of the MQTT map layout toggle

* Address Copilot review of the MQTT map

* Show MQTT states in the tooltip as they are

* Keep physics on after leaving the MQTT map mid transition

* Test the visibility of nodes on the MQTT map

* Apply UX suggestions to the MQTT map

* Address review of the MQTT map

* Read the zoom of the MQTT map from the series option

* Address review of the MQTT map

* Refresh the last messages of the MQTT map on an unchanged structure

* Keep the whitespace of raw payloads in the MQTT topic view

* Keep the MQTT map state stable on language, fetch and viewport changes

* Move the MQTT map source filter next to the search

* Clear the MQTT map focus when its node leaves the map

Pass darkMode and localize to the chart data builder instead of hass.

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

* Use the split network graph changes in the MQTT map

Take ha-network-graph from #56309, #56310 and #56313 and use treeLayout
instead of fixedLayout. The wheel zoom glide is dropped.

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

* Take over the review fixes of the split network graph PRs

Take ha-network-graph and its helpers from #56309 (8a6fe8cee1) and #56313
(cfbc45bb2e), with the fixes for the Copilot reviews.

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

* Take over the layout controller and zoom reset fix of #56313

Take ha-network-graph and its helpers from #56309 (ed8794a548) and
#56313 (149f159880, ca68e3a2c2). Without the style fade the map fades
without animation, and the topic diamonds lose their transparent
border, as nodeClickRadius already makes them easy to click.

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

* Keep the node size along with an animated view move

Take network-graph-view.ts, network-layout-controller.ts and their tests
from #56313 (d3cf4fa2fe).

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

* Drop the node size fix again

Revert 5acba41905: #56313 dropped d3cf4fa2fe, and the size change
during an animated view move is reported upstream as
apache/echarts#21894.

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

---------

Co-authored-by: Erwin Douna <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-03 10:25:21 +02:00
Paul Bottein 852d0b750a Use the state selector in the light effect feature editor (#56375) 2026-12-03 09:03:41 +02:00
Paul Bottein b4ab33bc08 Add a reorderable chips display to the state selector (#56374)
* Add a reorderable chips display to the state selector

* Disable the chips without an entity and add the default label

* Disable the chips with an empty entity list and keep any state exclusive
2026-12-03 09:03:40 +02:00
Balloob BotandPaulus Schoutsen b16979b1f5 Collapse long lists of energy meter suggestions (#56390)
* Collapse long energy suggestion lists

* Preserve keyboard focus when expanding energy suggestions

---------

Co-authored-by: Paulus Schoutsen <[email protected]>
2026-12-03 08:49:47 +02:00
renovate[bot] 9ba31a3d5f Update Node.js to v24.23.0 (#56391)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-03 08:42:10 +02:00
renovate[bot] 27308b03f9 Update dependency glob to v15 (#56392)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-03 08:42:01 +02:00
Paul Bottein ffc4233111 Read the gauge card entity from the form context (#56372) 2026-12-03 06:20:50 +00:00
Jan BouwhuisandClaude Opus 5.5 40a2317637 Add a left-to-right tree layout to the network graph (#56313)
With treeLayout set, the graph shows every node at the x and y of the
data, without the force layout, the physics button or saved positions.
Nodes keep their size on zoom, and the selected node is kept left with
room for its label and children.

NetworkLayoutController moves the view to a selected node and along with
the nodes on a switch between the tree and the force layout, with a
series center/zoom that ECharts animates. The chart base also checks the
graph roam when a render finishes, so the zoom reset shows after such a
move.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-03 07:50:09 +02:00
renovate[bot] d5c9dc89df Update pnpm to v12.25.1 (#56387)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-02 23:52:13 +00:00
renovate[bot] a7d9a8721e Update dependency glob to v14.0.7 (#56386)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-02 23:51:41 +00:00
Paul Bottein 30cf5240a1 Pass the form context to nested forms (#56373) 2026-12-02 23:43:21 +00:00
renovate[bot] 81e088885d Update dependency temporal-polyfill to v1.0.9 (#56379)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-02 20:08:09 +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
925 changed files with 31891 additions and 9640 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.
@@ -108,3 +108,5 @@ Panels commonly extend `SubscribeMixin(LitElement)` and receive route and narrow
Lovelace cards should implement `LovelaceCard`, validate config in `setConfig()`, handle loading, error, unavailable, and missing-entity states, and add a configuration editor when needed.
Cards are user-story surfaces. Support different households, entity types, responsive layouts, and accessible interaction states.
A new card, badge, or card feature, or a change to their options, needs documentation in other repositories. Follow "Documentation Elsewhere" in `ha-frontend-review`.
+4 -2
View File
@@ -44,6 +44,8 @@ Lazy contexts subscribe on first consumer and tear down after the last consumer:
The single-field contexts such as `localizeContext`, `themesContext`, and `userContext` are deprecated. Use grouped contexts instead.
Custom cards request contexts by key with a `context-request` event, as the custom card documentation on contributors.home-assistant.io describes, so the keys in `src/data/context/index.ts` and their values are a public API. Renaming or removing a key, changing its value, or dropping a deprecated context breaks them. A change to how card, badge, or feature hosts pass data, such as no longer setting `hass` or offering a new context, changes what custom cards should do too. For both, follow "Documentation Elsewhere" in `ha-frontend-review`.
## Consumption Patterns
Import `consume` from `src/common/decorators/consume`, not from `@lit/context`. The `@lit/context` version forces a host update on every context change, so every consumed field rerenders the component, even without `@state()`, and `@transform` cannot skip anything. Our `consume` leaves update scheduling to the field:
@@ -60,7 +62,7 @@ Use entity-scoped helpers when the component watches an entity ID held on the ho
```ts
@state() @consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntity;
private _stateObj?: HassEntityState;
@state() @consumeEntityRegistryEntry({ entityIdPath: ["_config", "entity"] })
private _entity?: EntityRegistryDisplayEntry;
@@ -73,7 +75,7 @@ Use `consumeEntityStates` when the host property contains one or more entity IDs
```ts
@state() @consumeEntityStates({ entityIdPath: ["_config", "entities"] })
private _stateObjs?: Record<string, HassEntity>;
private _stateObjs?: Record<string, HassEntityState>;
```
For a single field from a grouped context, pair `@consume` with `@transform`:
+11 -1
View File
@@ -1,6 +1,6 @@
---
name: ha-frontend-demo
description: Home Assistant standalone demo structure, configurations, URL navigation, mocked APIs, shared demo stubs used by gallery, and verification. Use when changing files under demo/, changing gallery consumers of demo/src/stubs/, or running and validating the demo.
description: Home Assistant standalone demo structure, configurations, URL navigation, mocked APIs, shared demo stubs used by gallery, the embed other sites use, and verification. Use when changing files under demo/, including demo/src/embed/, changing gallery consumers of demo/src/stubs/, or running and validating the demo.
---
# HA Frontend Demo
@@ -52,6 +52,7 @@ http://localhost:8090/?demo=<second slug>#/energy/water
- `demo/src/configs/<slug>/`: One directory per demo configuration, containing entities, dashboard, and theme data.
- `demo/src/configs/demo-configs.ts`: Registry of demo configurations and URL slug handling.
- `demo/src/stubs/`: Mocked WebSocket and REST APIs.
- `demo/src/embed/`: The embed, built as `embed.js`. Its `ha-embed-*` elements put cards, sections, views, and dashboards on other sites, against a mocked backend.
- `demo/script/develop_demo`, `demo/script/build_demo`: Development server and static build wrappers.
## Core Data
@@ -64,6 +65,15 @@ The service descriptions in `src/fake_data/demo_services.ts` and the trigger and
The two consumers use a stub differently, so demo behavior does not predict gallery behavior. A gallery page calls stubs against the `hass` from `provideHass`, where `hass.config` is the shared `demoConfig` object. A stub that mutates `hass.config` in place is therefore visible to the page. `demo/src/ha-demo.ts` copies `components` into a new array before the stubs run, so the same mutation never reaches the demo. A change can look correct in the demo while quietly breaking a gallery page.
## Embed
The embed puts parts of the dashboard on any web page, against a mocked backend: a single card with `ha-embed-card`, a section with `ha-embed-section`, a view with `ha-embed-view`, and a whole dashboard with `ha-embed-dashboard`. An `ha-embed-provider` holds the entities and other data they share. The live dashboard demos on home-assistant.io use it, and so can card authors, following the embed's page on contributors.home-assistant.io. Treat the `ha-embed-*` element names, their attributes, and the data the provider takes as a public API.
- `demo/src/html/components.html.template` documents the embed, at `/components.html` of the demo. Update it in the same pull request as an embed change.
- The provider takes most of its mocks from `demo/src/stubs/`, so a stub change reaches the embed as well as the demo and the gallery.
- demo.home-assistant.io deploys from `master`, and the development demo from `dev` (`.github/workflows/demo_deployment.yaml`), so other sites get an embed change only once it is released.
- When the embed's elements or data change, or a change alters what a live demo can show, follow "Documentation Elsewhere" in `ha-frontend-review`.
## Verification
Load `ha-frontend-testing` and use its demo and gallery workflows. Validate both consumers when changing shared stubs. Documentation-only changes do not require code tests unless examples or commands change.
+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.
- Content that takes a skeleton's place fades in over `--ha-animation-duration-fast`, which reduced motion makes instant. `ha-skeleton-overlay` does this for you. Elsewhere, use `skeletonOr(loading, skeleton, () => content)` from `src/components/skeleton/skeleton-arrival.ts`: it shows the skeleton while loading and fades the content in once when it replaces it, but not where no skeleton showed, such as table rows made as the table scrolls. Put text in an element of its own inside the content, as only elements fade. For content that fills in where it already is, such as a log, call `fadeInArrival(element)` once when its skeleton goes. Don't add any other fade to loaded content.
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).
+16 -2
View File
@@ -1,6 +1,6 @@
---
name: ha-frontend-review
description: Home Assistant frontend PR and review guidance, including implementation quality, existing review feedback, established design patterns, and the authority of UI/UX evidence. Use when reviewing frontend changes, preparing a PR, checking recurring review issues, or applying the PR template.
description: Home Assistant frontend PR and review guidance, including implementation quality, existing review feedback, established design patterns, the authority of UI/UX evidence, and documentation needed in other repositories. Use when reviewing frontend changes, preparing a PR, checking recurring review issues, applying the PR template, or working out which docs a change needs.
---
# HA Frontend Review
@@ -20,10 +20,23 @@ 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.
## Documentation Elsewhere
A frontend change that adds or changes something users see or configure, or an API others build on, needs companion documentation in the user or contributor docs, or the docs miss it. Spot this while making the change, and recommend the documentation changes it needs.
- home-assistant.io documents what users see and configure: a new card, badge, card feature, or heading entity; a new, changed, or removed option or default; a renamed label or menu path; and anything visible that its pages show, in screenshots or in live demos of the demo embed.
- contributors.home-assistant.io documents the design of components and cards in its Design area, and the APIs that custom cards, badges, card features, strategies, and themes use. When a change touches something they could rely on, search its custom UI and Marketplace pages for it. Announce a removal or rename there in a blog post.
To make the change:
- Read the other repository's agent instructions and skills first, and follow them for where and how the change goes.
- Docs follow what people can use. User docs can wait until a feature is usable, such as the last pull request of a stack, and an API still being tried out may stay undocumented, so recommend the docs.
- When a documentation pull request goes with a frontend one, link them to each other, and say in the description when one needs the other merged first.
## Pre-Submission Checklist
- `pnpm lint` passes when practical for the scope.
@@ -34,6 +47,7 @@ When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the body
- Entity existence is checked before property access.
- Event listeners and subscriptions are cleaned up.
- UI is accessible to screen readers and keyboard users.
- Documentation the change needs in other repositories is linked.
## Recurring Review Issues
@@ -17,6 +17,7 @@ Use this skill when editing CSS, layout, visual hierarchy, theme integration, re
- Prefer `ha-*` components and current Web Awesome wrappers.
- Avoid adding new legacy Material Web Components (`mwc-*`).
- Scope styles to the component. Do not rely on global styles for component internals.
- Themes set theme variables and design tokens by name, so renaming or removing one breaks them. The theme variables reference on contributors.home-assistant.io is generated from the frontend, but its theme guides may need a change too: follow "Documentation Elsewhere" in `ha-frontend-review`.
Spacing tokens are defined in `src/resources/theme/core.globals.ts`. The scale runs from `--ha-space-1` at 4px through `--ha-space-20` at 80px in 4px increments. Common values are `--ha-space-2` at 8px, `--ha-space-4` at 16px, and `--ha-space-8` at 32px.
+2 -1
View File
@@ -20,8 +20,9 @@ runs:
steps:
- name: Build ${{ inputs.target }}
shell: bash
run: ./node_modules/.bin/gulp ${{ inputs.target }}
run: ./node_modules/.bin/gulp "$TARGET"
env:
TARGET: ${{ inputs.target }}
GITHUB_TOKEN: ${{ inputs.github-token }}
IS_TEST: ${{ inputs.is-test }}
RSPACK_CACHE: ${{ inputs.rspack-cache }}
+19
View File
@@ -40,3 +40,22 @@ jobs:
curl -sSfL "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" \
| tar -xz actionlint
./actionlint -color
zizmor:
name: Check workflow security
runs-on: ubuntu-latest
env:
# renovate: datasource=github-releases depName=zizmorcore/zizmor
ZIZMOR_VERSION: 1.33.1
steps:
- name: Check out files from GitHub
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Run zizmor
env:
GH_TOKEN: ${{ github.token }}
run: |
curl -sSfL "https://github.com/zizmorcore/zizmor/releases/download/v${ZIZMOR_VERSION}/zizmor-x86_64-unknown-linux-gnu.tar.gz" \
| tar -xz zizmor
./zizmor --format=github .
+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
+3 -1
View File
@@ -47,4 +47,6 @@ jobs:
site-id: ${{ secrets.NETLIFY_GALLERY_SITE_ID }}
- name: Generate summary
run: echo "${{ steps.deploy.outputs.netlify_url }}" >> "$GITHUB_STEP_SUMMARY"
env:
NETLIFY_URL: ${{ steps.deploy.outputs.netlify_url }}
run: echo "$NETLIFY_URL" >> "$GITHUB_STEP_SUMMARY"
+3
View File
@@ -2,6 +2,8 @@ name: "Pull Request Labeler"
on: pull_request_target # zizmor: ignore[dangerous-triggers] -- safe: checks out base repo scripts only and reads PR files through the API, never PR head code
permissions: {}
# Runs one at a time per pull request, so an older run can't undo a newer one
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
@@ -13,6 +15,7 @@ jobs:
contents: read
pull-requests: write
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Apply labels
id: labeler
@@ -20,6 +20,7 @@ jobs:
check:
name: Check pull request follows contribution standards
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
pull-requests: write # To label and comment on pull requests
steps:
+1 -1
View File
@@ -1 +1 @@
24.22.3
24.23.0
+6 -3
View File
@@ -49,14 +49,17 @@ Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching
- `ha-frontend-testing`: lint, typecheck, Vitest, Playwright e2e dev servers, and benchmarks.
- `ha-frontend-query-params`: typed URL query params, `QueryParamsController`, data table URL sync, in-app links, and My Home Assistant redirect params.
- `ha-frontend-user-facing-text`: localization, terminology, sentence case, and Home Assistant text style.
- `ha-frontend-review`: PR template use, existing review feedback, review checklist, recurring issues, and UI/UX evidence including gallery specifications.
- `ha-frontend-review`: PR template use, documentation needed in other repositories, existing review feedback, review checklist, recurring issues, and UI/UX evidence including gallery specifications.
- `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-demo`: standalone demo structure, configurations, navigation, shared stubs, the embed other sites use, 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.
Keep skills current with the code they describe. When a change makes a skill wrong, or adds an area no skill covers yet, update or add the skill in the same pull request, or in one stacked on it. Change skills in a pull request of their own only for a large rework.
## 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
-8
View File
@@ -28,18 +28,10 @@ AI can be a helpful tool for writing code and documentation. However, due to the
All contributions must be reviewed and understood by the contributor before submission. You should be able to explain every change in a pull request you submit. Pull requests that appear to be unreviewed AI output will be closed without review.
## Design contributions
AI can be a helpful tool to explore ideas and build mockups and prototypes. But AI tends to give the most common answer, not the one that fits Home Assistant and its users. So we require a human who brings the point of view and owns the design decisions.
You should be able to explain the problem your design solves and why you made your choices. If a mockup or prototype was mostly generated with AI, say so when you share it. Check your work against the [design guidelines](https://contributors.home-assistant.io/design/), as AI tools often make up components, colors, or spacing that don't exist in Home Assistant. Design proposals that look like unreviewed AI output may be closed or hidden.
## Our use of AI
Some of our projects use AI tools to assist with code reviews, issue triaging, reporting, and other project management tasks. These tools may leave comments on pull requests or issues. As with any automated tooling, these comments are not always correct.
We also use AI to help keep the design system, the Figma kit, and the code in sync. The design decisions behind them are made by people.
If an AI tool leaves a comment on your contribution, treat it as you would any other review comment. If you believe it is incorrect, say so; a brief explanation is sufficient. Maintainers always have the final say. If in doubt, ask a maintainer.
## Enforcement
+8 -8
View File
@@ -1,15 +1,15 @@
{
"_comment": "Initial JS budget (raw/uncompressed bytes) for the cold-load critical entrypoints. Enforced by build-scripts/check-bundle-size.cjs in CI. Re-seed after an intentional change with `--update --headroom=<percent>`.",
"frontend-modern": {
"app": 627654,
"core": 57901,
"authorize": 593862,
"onboarding": 709255
"app": 655843,
"core": 58038,
"authorize": 620096,
"onboarding": 753790
},
"frontend-legacy": {
"app": 724225,
"core": 163115,
"authorize": 693913,
"onboarding": 812415
"app": 755140,
"core": 146919,
"authorize": 723005,
"onboarding": 861854
}
}
@@ -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.
+3
View File
@@ -466,6 +466,9 @@ const createRspackConfig = ({
),
}),
...componentsSourceAliases,
// elkjs isn't installed (see pnpm-workspace.yaml), so Mermaid's ELK
// layout chunk gets an empty module
"elkjs/lib/elk.bundled.js": false,
"lit/static-html$": "lit/static-html.js",
"lit/decorators$": "lit/decorators.js",
"lit/directive$": "lit/directive.js",
+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 || "");
+3 -2
View File
@@ -1,5 +1,5 @@
import { ContextProvider, provide } from "@lit/context";
import type { HassEntities } from "home-assistant-js-websocket";
import type { HassEntityStates } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
@@ -207,6 +207,7 @@ export class HaEmbedProvider extends LitElement {
}));
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
}));
this._applyColorScheme();
@@ -316,6 +317,6 @@ declare global {
"ha-embed-provider": HaEmbedProvider;
}
interface HASSDomEvents {
"states-changed": { states: HassEntities };
"states-changed": { states: HassEntityStates };
}
}
+4 -2
View File
@@ -580,8 +580,10 @@ provider.entities = Object.values(provider.hass.states).map((entity) =&gt;
<ul>
<li>
<code>areas</code>: a list of areas, each with an
<code>area_id</code> and a <code>name</code>. Without it, each
<code>area_id</code> of the entities and devices becomes an area.
<code>area_id</code> and a <code>name</code>, and optionally an
<code>icon</code> and a <code>picture</code>, the URL of an image.
Without it, each <code>area_id</code> of the entities and devices
becomes an area.
</li>
<li>
<code>devices</code>: a list of devices, each with an
+5 -1
View File
@@ -6,8 +6,11 @@ export interface DemoArea {
name: string;
floor_id?: string;
icon?: string;
// An image URL, such as for an area card with `display_type: picture`
picture?: string;
temperature_entity_id?: string;
humidity_entity_id?: string;
occupancy_entity_id?: string;
}
let areas: AreaRegistryEntry[] = [];
@@ -19,9 +22,10 @@ export const toAreaRegistryEntry = (area: DemoArea): AreaRegistryEntry => ({
icon: area.icon ?? null,
temperature_entity_id: area.temperature_entity_id ?? null,
humidity_entity_id: area.humidity_entity_id ?? null,
occupancy_entity_id: area.occupancy_entity_id ?? null,
aliases: [],
labels: [],
picture: null,
picture: area.picture ?? null,
created_at: 0,
modified_at: 0,
});
+67
View File
@@ -0,0 +1,67 @@
// Made-up values for the mock history and statistics that look like a real
// home and are the same on every load, so a chart doesn't change each time
// the page opens.
const HOUR = 60 * 60 * 1000;
/** A number from 0 up to 1 for each key, the same every time. */
export const hashFraction = (key: string): number => {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash * 31 + key.charCodeAt(i)) % 2147483647;
}
return hash / 2147483647;
};
/**
* How far a value drifts from its state: 10% of it, or 5% above 80, as for a
* temperature or a power reading. A state of 0 drifts by up to 1.
*/
export const driftScale = (value: number): number =>
value === 0 ? 1 : Math.abs(value) * (Math.abs(value) > 80 ? 0.05 : 0.1);
/**
* A drifted reading kept on the same side of 0 as the state, as a reading such
* as a power or a speed doesn't cross 0. A state of 0 stays at 0 or above.
*/
export const sameSideOfZero = (value: number, drifted: number): number =>
value < 0 ? Math.min(drifted, 0) : Math.max(drifted, 0);
// The point each wave starts at, kept once picked from its key, as a long
// period asks for the drift of hundreds of thousands of hours
const phases = new Map<string, number>();
const phase = (key: string): number => {
let value = phases.get(key);
if (value === undefined) {
value = 2 * Math.PI * hashFraction(key);
phases.set(key, value);
}
return value;
};
const wave = (key: string, time: number, period: number): number =>
Math.sin((2 * Math.PI * time) / period + phase(key));
/**
* The value of an entity at a time, drifting slowly around its state: a swing
* over the day and two faster, smaller ones, each starting at a point picked
* from the entity ID.
*/
export const driftedValue = (
key: string,
time: number,
value: number
): number =>
sameSideOfZero(
value,
value +
driftScale(value) *
(0.6 * wave(`${key}:day`, time, 24 * HOUR) +
0.3 * wave(`${key}:hours`, time, 5 * HOUR) +
0.1 * wave(`${key}:hour`, time, 1.3 * HOUR))
);
+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",
+102 -23
View File
@@ -1,9 +1,10 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HistoryStates } from "../../../src/data/history";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
import { driftedValue, hashFraction } from "./drift";
const generateStateHistory = (
state: HassEntity,
state: HassEntityState,
deltas,
start_date: Date,
end_date: Date
@@ -40,6 +41,76 @@ const generateStateHistory = (
const incrementalUnits = ["clients", "queries", "ads"];
// Changes over the range of an on/off entity, ending in its state
const ON_OFF_CHANGES = 6;
// The most points of a number over the range
const NUMBER_POINTS = 96;
// An on/off entity, such as a light, switches a few times over the range, at
// times picked from its entity ID, and ends in its state
const generateOnOffHistory = (
state: HassEntityState,
start: Date,
end: Date
): HistoryStates[string] => {
const span = end.getTime() - start.getTime();
const opposite = state.state === "on" ? "off" : "on";
return Array.from({ length: ON_OFF_CHANGES }, (_, index) => {
const time =
index === 0
? start.getTime()
: start.getTime() +
(span *
(index - 0.3 + 0.6 * hashFraction(`${state.entity_id}:${index}`))) /
ON_OFF_CHANGES;
return {
a: state.attributes,
s: (ON_OFF_CHANGES - 1 - index) % 2 === 0 ? state.state : opposite,
lc: time / 1000,
lu: time / 1000,
};
});
};
// A number drifts around its state over the range, the same on every load,
// with as many decimals as its state, and ends in its state
const generateNumberHistory = (
state: HassEntityState,
value: number,
start: Date,
end: Date
): HistoryStates[string] => {
const decimals = Math.max(state.state.split(".")[1]?.length ?? 0, 1);
const step = Math.max(
(end.getTime() - start.getTime()) / NUMBER_POINTS,
5 * 60 * 1000
);
const history: HistoryStates[string] = [];
for (let time = start.getTime(); time < end.getTime(); time += step) {
history.push({
a: state.attributes,
s: driftedValue(state.entity_id, time, value).toFixed(decimals),
lc: time / 1000,
lu: time / 1000,
});
}
history.push({
a: state.attributes,
s: state.state,
lc: end.getTime() / 1000,
lu: end.getTime() / 1000,
});
return history;
};
export const mockHistory = (mockHass: MockHomeAssistant) => {
mockHass.mockWS(
"history/stream",
@@ -70,6 +141,11 @@ export const mockHistory = (mockHass: MockHomeAssistant) => {
continue;
}
if (state.state === "on" || state.state === "off") {
states[entityId] = generateOnOffHistory(state, start, end);
continue;
}
if (!state.attributes.unit_of_measurement) {
states[entityId] = generateStateHistory(
state,
@@ -92,32 +168,35 @@ export const mockHistory = (mockHass: MockHomeAssistant) => {
continue;
}
const statesToGenerate = 15;
let genFunc;
if (incrementalUnits.includes(state.attributes.unit_of_measurement)) {
let initial = Math.floor(
numberState * 0.4 + numberState * Math.random() * 0.2
if (!incrementalUnits.includes(state.attributes.unit_of_measurement)) {
states[entityId] = generateNumberHistory(
state,
numberState,
start,
end
);
const diff = Math.max(
1,
Math.floor((numberState - initial) / statesToGenerate)
);
genFunc = () => {
initial += diff;
return Math.min(numberState, initial);
};
} else {
const diff = Math.floor(
numberState * (numberState > 80 ? 0.05 : 0.5)
);
genFunc = () =>
numberState - diff + Math.floor(Math.random() * 2 * diff);
continue;
}
// A counter climbs to its state
const statesToGenerate = 15;
let initial = Math.floor(
numberState * 0.4 + numberState * Math.random() * 0.2
);
const diff = Math.max(
1,
Math.floor((numberState - initial) / statesToGenerate)
);
states[entityId] = generateStateHistory(
state,
Array.from({ length: statesToGenerate }, genFunc),
Array.from({ length: statesToGenerate }, () => {
initial += diff;
return Math.min(numberState, initial);
}),
start,
end
);
+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,
+386 -66
View File
@@ -1,19 +1,37 @@
import { TZDate } from "@date-fns/tz";
import type { Day } from "date-fns";
import {
addDays,
addHours,
addMinutes,
addMonths,
addWeeks,
addYears,
constructFrom,
differenceInHours,
endOfDay,
startOfDay,
startOfHour,
startOfMonth,
startOfWeek,
startOfYear,
} from "date-fns";
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HaDurationData } from "../../../src/components/ha-duration-input";
import type {
Statistic,
Statistics,
StatisticsMetaData,
StatisticsUnitConfiguration,
StatisticValue,
} from "../../../src/data/recorder";
import { StatisticMeanType } from "../../../src/data/recorder";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
import {
driftedValue,
driftScale,
hashFraction,
sameSideOfZero,
} from "./drift";
const getFirstDate = (
start: Date,
@@ -31,34 +49,57 @@ const getNextDate = (
currentDate: Date,
period: "5minute" | "hour" | "day" | "month"
): Date => {
return period === "day"
? addDays(currentDate, 1)
: period === "month"
? addMonths(currentDate, 1)
: period === "hour"
? addHours(currentDate, 1)
: addMinutes(currentDate, 5);
if (period === "day") {
return addDays(currentDate, 1);
}
if (period === "month") {
return addMonths(currentDate, 1);
}
// An hour or 5 minutes is the same length in any timezone, so a plain Date
// will do. Making a timezone date for each one is slow over a long period,
// which has hundreds of thousands of hours.
return new Date(
currentDate.getTime() + (period === "hour" ? 60 : 5) * 60 * 1000
);
};
// The mean of each period drifts around the entity's state, as its history
// does, and the same on every load. Longer periods span more of the drift.
// The values drift in the entity's unit, then are multiplied by factor to give
// them in the unit asked for.
const generateMeanStatistics = (
id: string,
start: Date,
end: Date,
period: "5minute" | "hour" | "day" | "month" = "hour",
maxDiff: number
value: number,
factor = 1
): StatisticValue[] => {
const statistics: StatisticValue[] = [];
const spread =
driftScale(value) *
(period === "5minute" || period === "hour" ? 0.2 : 0.8) *
factor;
let currentDate = getFirstDate(start, period);
const now = new Date();
while (end > currentDate && currentDate < now) {
const delta = Math.random() * maxDiff;
const mean = delta;
const nextDate = getNextDate(currentDate, period);
const mean =
driftedValue(
id,
(currentDate.getTime() + nextDate.getTime()) / 2,
value
) * factor;
statistics.push({
start: currentDate.getTime(),
end: nextDate.getTime(),
mean,
min: mean - Math.random() * maxDiff,
max: mean + Math.random() * maxDiff,
min: sameSideOfZero(value, mean - spread),
max: sameSideOfZero(value, mean + spread),
last_reset: 0,
state: mean,
sum: null,
@@ -73,7 +114,9 @@ const generateSumStatistics = (
end: Date,
period: "5minute" | "hour" | "day" | "month" = "hour",
initValue: number,
maxDiff: number | ((start: Date, end: Date) => number)
maxDiff: number | ((start: Date, end: Date) => number),
// A number from 0 up to 1 for each period's share of maxDiff
random: (periodStart: Date) => number = () => Math.random()
): StatisticValue[] => {
const statistics: StatisticValue[] = [];
let currentDate = getFirstDate(start, period);
@@ -83,7 +126,8 @@ const generateSumStatistics = (
const nextDate = getNextDate(currentDate, period);
const bound =
typeof maxDiff === "function" ? maxDiff(currentDate, nextDate) : maxDiff;
const add = Math.random() * bound;
const add = random(currentDate) * bound;
sum += add;
statistics.push({
start: currentDate.getTime(),
@@ -372,70 +416,346 @@ const derivedBatteryFlows: Record<string, { source: string; share: number }> = {
},
};
const hasSum = (stateObj: HassEntityState | undefined): boolean =>
stateObj?.attributes.state_class === "total" ||
stateObj?.attributes.state_class === "total_increasing";
// Like Core, statistics are given in the unit asked for, such as power in kW
// for the energy dashboard while the demo's power sensors are in W
const unitFactor = (
stateObj: HassEntityState | undefined,
units?: StatisticsUnitConfiguration
): number => {
const unit = stateObj?.attributes.unit_of_measurement;
if (unit === "W" && units?.power === "kW") {
return 1 / 1000;
}
if (unit === "kW" && units?.power === "W") {
return 1000;
}
return 1;
};
const getStatistics = (
hass: MockHomeAssistant,
statisticIds: string[],
start: Date,
end: Date,
period: "5minute" | "hour" | "day" | "month",
units?: StatisticsUnitConfiguration
): Statistics => {
const statistics: Record<string, StatisticValue[]> = {};
const cache: Record<string, StatisticValue[]> = {};
const getStats = (id: string) => {
cache[id] ??= statisticsFunctions[id](id, start, end, period);
return cache[id];
};
const scaleStats = (source: string, factor: number) => {
let sum = 0;
return getStats(source).map((statistic) => {
const change = (statistic.change ?? 0) * factor;
sum += change;
return { ...statistic, change, state: sum, sum };
});
};
statisticIds.forEach((id: string) => {
if (id in derivedCosts) {
const { source, price } = derivedCosts[id];
statistics[id] = scaleStats(source, price);
} else if (id in derivedBatteryFlows) {
const { source, share } = derivedBatteryFlows[id];
statistics[id] = scaleStats(source, share);
} else if (id in statisticsFunctions) {
statistics[id] = getStats(id);
} else {
const entityState = hass.states[id];
// Like Core, only an entity with a state class has statistics, so the
// history of a light has no empty chart of them
if (entityState && !entityState.attributes.state_class) {
return;
}
const state = entityState ? Number(entityState.state) : 1;
// Each period's share is picked from the entity ID, so a meter's bars
// are the same on every load. The cap grows with the period's length,
// so a day's bar adds up to about 24 hours' worth.
statistics[id] = hasSum(entityState)
? generateSumStatistics(
start,
end,
period,
state,
(periodStart, periodEnd) =>
state *
(state > 80 ? 0.01 : 0.05) *
((periodEnd.getTime() - periodStart.getTime()) / 3600000),
(periodStart) => hashFraction(`${id}:${periodStart.getTime()}`)
)
: generateMeanStatistics(
id,
start,
end,
period,
state,
unitFactor(entityState, units)
);
}
});
return statistics;
};
const durationMs = (duration?: HaDurationData): number =>
duration
? ((duration.days ?? 0) * 24 + (duration.hours ?? 0)) * 3600000 +
(duration.minutes ?? 0) * 60000 +
(duration.seconds ?? 0) * 1000 +
(duration.milliseconds ?? 0)
: 0;
const WEEK_STARTS = {
sun: 0,
mon: 1,
tue: 2,
wed: 3,
thu: 4,
fri: 5,
sat: 6,
} satisfies Record<string, Day>;
interface StatisticDuringPeriodMessage {
statistic_id: string;
types?: string[];
fixed_period?: { start_time?: string; end_time?: string };
calendar?: {
period: "hour" | "day" | "week" | "month" | "year";
offset?: number;
first_weekday?: keyof typeof WEEK_STARTS;
};
rolling_window?: { duration: HaDurationData; offset?: HaDurationData };
units?: StatisticsUnitConfiguration;
}
// The start and end of the period of recorder/statistic_during_period, as
// Core reads it, in the server timezone
const statisticPeriodBounds = (
message: StatisticDuringPeriodMessage,
timeZone: string
): [Date, Date] => {
const now = new TZDate(Date.now(), timeZone);
if (message.fixed_period) {
const { start_time, end_time } = message.fixed_period;
return [
new TZDate(start_time ? Date.parse(start_time) : 0, timeZone),
new TZDate(end_time ? Date.parse(end_time) : Date.now(), timeZone),
];
}
if (message.rolling_window) {
const end = new TZDate(
now.getTime() + durationMs(message.rolling_window.offset),
timeZone
);
return [
new TZDate(
end.getTime() - durationMs(message.rolling_window.duration),
timeZone
),
end,
];
}
if (message.calendar) {
const offset = message.calendar.offset ?? 0;
switch (message.calendar.period) {
case "hour": {
const start = addHours(startOfHour(now), offset);
return [start, addHours(start, 1)];
}
case "week": {
const weekStartsOn =
WEEK_STARTS[message.calendar.first_weekday ?? "mon"];
const start = addWeeks(startOfWeek(now, { weekStartsOn }), offset);
return [start, addWeeks(start, 1)];
}
case "month": {
const start = addMonths(startOfMonth(now), offset);
return [start, addMonths(start, 1)];
}
case "year": {
const start = addYears(startOfYear(now), offset);
return [start, addYears(start, 1)];
}
default: {
const start = addDays(startOfDay(now), offset);
return [start, addDays(start, 1)];
}
}
}
// All the history, which the mock makes up for the last day
return [addDays(now, -1), now];
};
export const mockRecorder = (mockHass: MockHomeAssistant) => {
mockHass.mockWS(
"recorder/get_statistics_metadata",
(): StatisticsMetaData[] => []
(
{ statistic_ids }: { statistic_ids?: string[] },
hass
): StatisticsMetaData[] =>
(statistic_ids ?? []).flatMap((id) => {
const stateObj = hass.states[id];
if (!stateObj?.attributes.state_class) {
return [];
}
const sum = hasSum(stateObj);
return [
{
statistic_id: id,
source: "recorder",
name: stateObj.attributes.friendly_name ?? null,
statistics_unit_of_measurement:
stateObj.attributes.unit_of_measurement ?? null,
has_sum: sum,
mean_type: sum
? StatisticMeanType.NONE
: StatisticMeanType.ARITHMETIC,
unit_class: null,
},
];
})
);
mockHass.mockWS(
"recorder/list_statistic_ids",
(): StatisticsMetaData[] => []
);
mockHass.mockWS(
"recorder/statistics_during_period",
({ statistic_ids, start_time, end_time, period }, hass): Statistics => {
(
{ statistic_ids, start_time, end_time, period, units },
hass
): Statistics =>
// Calendar buckets follow the server timezone, independent of the browser.
const start = new TZDate(start_time, hass.config.time_zone);
const end = new TZDate(end_time ?? Date.now(), hass.config.time_zone);
getStatistics(
hass,
statistic_ids,
new TZDate(start_time, hass.config.time_zone),
new TZDate(end_time ?? Date.now(), hass.config.time_zone),
period,
units
)
);
const statistics: Record<string, StatisticValue[]> = {};
const cache: Record<string, StatisticValue[]> = {};
const getStats = (id: string) => {
cache[id] ??= statisticsFunctions[id](id, start, end, period);
return cache[id];
// The statistic card asks for one number over a period: the mean, lowest,
// highest or change of the hourly statistics in it
mockHass.mockWS(
"recorder/statistic_during_period",
(message: StatisticDuringPeriodMessage, hass): Statistic => {
const [start, end] = statisticPeriodBounds(
message,
hass.config.time_zone
);
const id = message.statistic_id;
// Like Core, an ID without statistics, such as a misspelled one, gets
// none, rather than values made up for it
const hasStatistics =
id in hass.states ||
id in statisticsFunctions ||
id in derivedCosts ||
id in derivedBatteryFlows;
// The energy demo's tariffs place their phases from the start they're
// asked for, as the energy dashboard asks from midnight. So the hours
// are made up one day at a time from each midnight, then only those
// inside the period count. Like Core, an hour that runs past the end
// isn't counted, so a day ending at 23:59:59.999 leaves out the hour
// from 23:00.
const days: Date[] = [];
for (
let day = startOfDay(start);
hasStatistics && day < end;
day = addDays(day, 1)
) {
days.push(day);
}
const values = days
.flatMap(
(day) =>
getStatistics(
hass,
[id],
day,
addDays(day, 1),
"hour",
message.units
)[id] ?? []
)
.filter(
(value) =>
value.start >= start.getTime() && value.end <= end.getTime()
);
const numbers = (key: "mean" | "min" | "max" | "change") =>
values.flatMap((value) => (value[key] == null ? [] : [value[key]]));
const means = numbers("mean");
const mins = numbers("min");
const maxes = numbers("max");
const changes = numbers("change");
return {
mean: means.length
? means.reduce((total, mean) => total + mean, 0) / means.length
: null,
// Reduced rather than spread, as a long period has more hours than a
// call can take as arguments
min: mins.length
? mins.reduce((lowest, min) => Math.min(lowest, min))
: null,
max: maxes.length
? maxes.reduce((highest, max) => Math.max(highest, max))
: null,
change: changes.length
? changes.reduce((total, change) => total + change, 0)
: null,
};
const scaleStats = (source: string, factor: number) => {
let sum = 0;
return getStats(source).map((statistic) => {
const change = statistic.change! * factor;
sum += change;
return { ...statistic, change, state: sum, sum };
});
};
statistic_ids.forEach((id: string) => {
if (id in derivedCosts) {
const { source, price } = derivedCosts[id];
statistics[id] = scaleStats(source, price);
} else if (id in derivedBatteryFlows) {
const { source, share } = derivedBatteryFlows[id];
statistics[id] = scaleStats(source, share);
} else if (id in statisticsFunctions) {
statistics[id] = getStats(id);
} else {
const entityState = hass.states[id];
const state = entityState ? Number(entityState.state) : 1;
statistics[id] =
entityState &&
(entityState.attributes.state_class === "total" ||
entityState.attributes.state_class === "total_increasing")
? generateSumStatistics(
start,
end,
period,
state,
state * (state > 80 ? 0.01 : 0.05)
)
: generateMeanStatistics(
start,
end,
period,
state * (state > 80 ? 0.05 : 0.1)
);
}
});
return statistics;
}
);
};
+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) {
@@ -122,6 +122,7 @@ const AREAS: AreaRegistryEntry[] = [
labels: [],
temperature_entity_id: null,
humidity_entity_id: null,
occupancy_entity_id: null,
created_at: 0,
modified_at: 0,
},
@@ -135,6 +136,7 @@ const AREAS: AreaRegistryEntry[] = [
labels: [],
temperature_entity_id: null,
humidity_entity_id: null,
occupancy_entity_id: null,
created_at: 0,
modified_at: 0,
},
@@ -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: {} },
@@ -118,6 +118,7 @@ const area = (areaId: string, name: string): AreaRegistryEntry => ({
labels: [],
temperature_entity_id: null,
humidity_entity_id: null,
occupancy_entity_id: null,
created_at: 0,
modified_at: 0,
});
@@ -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: {
+7 -7
View File
@@ -1,6 +1,6 @@
import type {
HassEntity,
HassEntityAttributeBase,
HassEntityState,
HassEntityStateAttributeBase,
} from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
@@ -94,7 +94,7 @@ const BINARY_SENSOR_DEVICE_CLASSES = [
"window",
];
const ENTITIES: HassEntity[] = [
const ENTITIES: HassEntityState[] = [
// Alarm control panel
createEntity("alarm_control_panel.disarmed", "disarmed"),
createEntity("alarm_control_panel.armed_home", "armed_home"),
@@ -305,8 +305,8 @@ function createEntity(
entity_id: string,
state: string,
device_class?: string,
attributes?: HassEntityAttributeBase | HassEntity["attributes"]
): HassEntity {
attributes?: HassEntityStateAttributeBase | HassEntityState["attributes"]
): HassEntityState {
return {
entity_id,
state,
@@ -325,14 +325,14 @@ function createEntity(
}
interface EntityRowData {
stateObj: HassEntity;
stateObj: HassEntityState;
entity_id: string;
state: string;
device_class?: string;
domain: string;
}
function createRowData(stateObj: HassEntity): EntityRowData {
function createRowData(stateObj: HassEntityState): EntityRowData {
return {
stateObj,
entity_id: stateObj.entity_id,
+51
View File
@@ -54,6 +54,57 @@ 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.
`,
}),
mdContentwithDefaults({
content: `
\`\`\`mermaid
flowchart LR
router[Router] --> switch[Switch]
switch --> nas[(NAS)]
switch --> ha[[Home Assistant]]
ha -. Zigbee .-> lights([Lights])
\`\`\`
\`\`\`mermaid
sequenceDiagram
Door sensor->>Home Assistant: Opened
Home Assistant->>Hallway light: Turn on
Hallway light-->>Home Assistant: On
\`\`\`
`,
}),
mdContentwithDefaults({
content: `
A diagram that doesn't parse shows the error and its source:
\`\`\`mermaid
flowchart LR
A -->
\`\`\`
`,
}),
];
@customElement("demo-misc-ha-markdown")
+46 -44
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",
"@home-assistant/webawesome": "3.14.0-ha.2",
"@lezer/common": "1.5.6",
"@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.15.0-ha.0",
"@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,18 @@
"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.4.0",
"marked-footnote": "1.4.0",
"marked-gfm-heading-id": "4.1.4",
"memoize-one": "7.0.0",
"mermaid": "12.4.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
"object-hash": "3.0.0",
@@ -122,7 +125,7 @@
"sortablejs": "1.15.7",
"stacktrace-js": "2.0.2",
"superstruct": "2.0.2",
"temporal-polyfill": "1.0.8",
"temporal-polyfill": "1.0.9",
"tinykeys": "4.0.1",
"weekstart": "2.0.0",
"workbox-cacheable-response": "7.4.1",
@@ -136,25 +139,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.5",
"@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 +165,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",
@@ -188,7 +190,7 @@
"fancy-log": "2.0.0",
"fs-extra": "11.4.1",
"generate-license-file": "4.2.5",
"glob": "14.0.6",
"glob": "15.0.0",
"globals": "17.14.0",
"gulp": "5.0.1",
"gulp-json-transform": "0.5.0",
@@ -199,7 +201,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,20 +212,20 @@
"rspack-manifest-plugin": "5.2.2",
"serve": "14.2.8",
"sinon": "22.1.0",
"tar": "7.5.23",
"tar": "8.0.4",
"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]5.1",
"volta": {
"node": "24.22.3"
"node": "24.23.0"
}
}
+17
View File
@@ -0,0 +1,17 @@
# Changelog
## 0.1.0-beta.0
First beta release.
- `hac-card`: card that groups related content, with an optional header and
footer.
- `hac-spinner`: progress indicator for a task of unknown duration, named for
screen readers.
- `hac-popover`: panel opened from a button, for content people read or
interact with, like help text with links.
- Global registration (`@home-assistant/components/<element>`) and scoped
registration for custom cards (`@home-assistant/components/<element>/scoped`
with `ScopedElementsMixin` or `createScopedElementRegistry`).
- A custom elements manifest at
`@home-assistant/components/custom-elements.json`.
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+32 -9
View File
@@ -3,7 +3,21 @@
Home Assistant Components (`hac-*`): framework-agnostic web components built
with [Lit](https://lit.dev).
> Work in progress, not published yet.
> [!WARNING]
> **This package is in beta. The API of every component can still change in
> any release, without notice or a major version bump.** This covers
> attributes, properties, events, slots, CSS parts and CSS custom properties.
> Pin an exact version and read the [changelog](CHANGELOG.md) before you
> update.
## Installation
```bash
npm install --save-exact @home-assistant/components@beta
npm install lit
```
`lit` is a peer dependency.
## Registration
@@ -86,8 +100,6 @@ Only elements rendered inside the shadow root use the scoped registry. Light
DOM content, such as slotted elements, uses the registry of the tree it is
written in.
`lit` is a peer dependency.
### TypeScript
Each element's entry points declare its tag in `HTMLElementTagNameMap`, so
@@ -102,6 +114,18 @@ import type { HacCard } from "@home-assistant/components/card/scoped";
The package has no root entry point: each element and the scoped helpers
(`@home-assistant/components/scoped`) have their own.
### Custom elements manifest
`@home-assistant/components/custom-elements.json` describes every element's
attributes, properties, events, slots, parts and CSS custom properties, for
editors and documentation tools.
## Events
Events are named after the element that fires them, like
`hac-popover-show`, and bubble out of shadow roots. A listener further out
can therefore tell a popover closing from a dialog closing around it.
## Theming
Each component exposes its own `--hac-*` custom properties, documented in its
@@ -124,17 +148,16 @@ Each element has its own directory, named like its import path:
```
src/components/card/ <hac-card> -> @home-assistant/components/card
hac-card.ts class, does not register itself
info.ts tag name and version
hac-card.ts class and tag name, does not register itself
global.ts registers globally
scoped.ts element for a scoped registry -> …/card/scoped
```
Shared code lives in `src/utils/`: `registration/` for defining elements
(global and scoped) and `element/` for helpers that components use
themselves, like slot checks.
Every element has its own version in `info.ts`.
(global and scoped), `element/` for helpers that components use
themselves, like slot checks, and `popup/` for the base of floating elements
like `hac-popover`, positioned with
[Floating UI](https://floating-ui.com).
Entry points are mapped with subpath patterns in `package.json`, so a new
element directory needs no `package.json` change. Only `global.ts` files have
@@ -41,10 +41,30 @@ const publicApiOnly = () => ({
declaration.members = declaration.members?.filter(
(member) => !member.privacy || member.privacy === "public"
);
// Events dispatched with a computed name, like the popup base's, have no
// name here; the element documents them with @fires instead
declaration.events = declaration.events?.filter((event) => event.name);
});
},
});
// Only elements and their base classes are documented. Module constants like
// TAG_NAME are internal, as no entry point exports them.
const classesOnly = () => ({
name: "classes-only",
packageLinkPhase({ customElementsManifest }) {
for (const module of customElementsManifest.modules) {
module.declarations = module.declarations?.filter(
(declaration) => declaration.kind === "class"
);
const names = new Set(module.declarations?.map(({ name }) => name));
module.exports = module.exports?.filter((entry) =>
names.has(entry.declaration.name)
);
}
},
});
const distPaths = () => {
const toDist = (value) => value.replace(/^src\/(.+)\.ts$/, "dist/$1.js");
const rewrite = (node) => {
@@ -72,13 +92,15 @@ const distPaths = () => {
};
export default {
globs: ["src/components/**/hac-*.ts"],
// Base classes are analyzed too, so elements list the members they inherit
globs: ["src/components/**/hac-*.ts", "src/utils/popup/*.ts"],
outdir: "dist",
litelement: true,
plugins: [
packageReadme(),
summaryAsDescription(),
publicApiOnly(),
classesOnly(),
distPaths(),
],
};
+16 -8
View File
@@ -1,8 +1,16 @@
{
"name": "@home-assistant/components",
"version": "0.0.0",
"version": "0.1.0-beta.0",
"description": "Home Assistant web components (hac-* elements) built with Lit",
"keywords": [
"home-assistant",
"web-components",
"custom-elements",
"lit"
],
"license": "Apache-2.0",
"homepage": "https://github.com/home-assistant/frontend/tree/dev/packages/components#readme",
"bugs": "https://github.com/home-assistant/frontend/issues",
"repository": {
"type": "git",
"url": "git+https://github.com/home-assistant/frontend.git",
@@ -21,16 +29,12 @@
"import": "./dist/scoped.js"
},
"./package.json": "./package.json",
"./custom-elements.json": "./dist/custom-elements.json",
"./*/scoped": {
"ha-source": "./src/components/*/scoped.ts",
"types": "./dist/components/*/scoped.d.ts",
"import": "./dist/components/*/scoped.js"
},
"./*/info": {
"ha-source": "./src/components/*/info.ts",
"types": "./dist/components/*/info.d.ts",
"import": "./dist/components/*/info.js"
},
"./*": {
"ha-source": "./src/components/*/global.ts",
"types": "./dist/components/*/global.d.ts",
@@ -38,7 +42,8 @@
}
},
"files": [
"dist"
"dist",
"CHANGELOG.md"
],
"publishConfig": {
"access": "public"
@@ -48,12 +53,15 @@
"dev": "rslib build --watch",
"prepublishOnly": "pnpm run build"
},
"dependencies": {
"@floating-ui/dom": "^1.8.0"
},
"peerDependencies": {
"lit": "^3.3.0"
},
"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"
}
@@ -1,6 +1,5 @@
import { define } from "../../utils/registration/define";
import { HacCard } from "./hac-card";
import { TAG_NAME } from "./info";
import { HacCard, TAG_NAME } from "./hac-card";
// Registers <hac-card> in the global registry, as used by Home Assistant
define(TAG_NAME, HacCard);
@@ -5,6 +5,9 @@ import {
hasAssignedElements,
} from "../../utils/element/slot";
/** Tag name of the element. */
export const TAG_NAME = "hac-card";
/**
* @element hac-card
*
@@ -21,13 +24,13 @@ import {
* @csspart footer - Wrapper of the footer slot.
*
* @cssprop --hac-card-background - Background of the card.
* @cssprop --hac-card-color - Text color of the card.
* @cssprop --hac-card-border-color - Border color of the card and the footer divider.
* @cssprop --hac-card-border-width - Border width of the card.
* @cssprop --hac-card-border-radius - Border radius of the card.
* @cssprop {<color>} --hac-card-color - Text color of the card.
* @cssprop {<color>} --hac-card-border-color - Border color of the card and the footer divider.
* @cssprop {<length>} [--hac-card-border-width=1px] - Border width of the card.
* @cssprop {<length>} [--hac-card-border-radius=12px] - Border radius of the card.
* @cssprop --hac-card-box-shadow - Box shadow of the card.
* @cssprop --hac-card-content-padding - Padding of the content.
* @cssprop --hac-card-footer-padding - Padding of the footer.
* @cssprop [--hac-card-content-padding=16px] - Padding of the content.
* @cssprop [--hac-card-footer-padding=8px] - Padding of the footer.
*/
export class HacCard extends LitElement {
/**
@@ -1,5 +0,0 @@
/** Tag name of the element. */
export const TAG_NAME = "hac-card";
/** Version of <hac-card>. */
export const VERSION = "0.1.0";
@@ -1,6 +1,5 @@
import type { ElementDefinition } from "../../utils/registration/definition";
import { HacCard } from "./hac-card";
import { TAG_NAME } from "./info";
import { HacCard, TAG_NAME } from "./hac-card";
export { HacCard };
@@ -0,0 +1,7 @@
import { define } from "../../utils/registration/define";
import { HacPopover, TAG_NAME } from "./hac-popover";
// Registers <hac-popover> in the global registry, as used by Home Assistant
define(TAG_NAME, HacPopover);
export { HacPopover };
@@ -0,0 +1,276 @@
import type { Placement } from "@floating-ui/dom";
import { css, type PropertyValues } from "lit";
import { property } from "lit/decorators.js";
import { containsComposed, deepActiveElement } from "../../utils/element/focus";
import { setAriaExpanded } from "../../utils/element/aria";
import { listen } from "../../utils/element/listen";
import { PopupBase, type PopupHideDetail } from "../../utils/popup/popup-base";
/** Tag name of the element. */
export const TAG_NAME = "hac-popover";
/**
* Works like a disclosure: the anchor gets `aria-expanded`, and focus stays on
* the anchor when the popover opens.
*
* - Set `for` to the id of a `<button>`, or of a button component that
* passes the `ariaExpanded` property on to its inner button.
* - Place the popover right after its anchor, so Tab and screen readers move
* from the anchor into the content.
* - Give an icon-only anchor a name, like `aria-label="About logging in"`.
* - Keep it to a few links or buttons. Tab moves on past the last one and
* closes the popover, so use a dialog for forms and other tasks.
* - Not a tooltip: it doesn't open on focus and isn't announced as a
* description, so don't use it to label an icon.
* - With `trigger="manual"` the parent opens it, like a picker. The parent
* then adds the roles and keys, like `role="combobox"` and arrow keys.
*
* @element hac-popover
*
* @summary
* Panel opened from a button for content people read or interact with, like
* help text with links.
*
* @slot - The popover's content.
*
* @csspart body - The popover's container.
*
* @cssprop {<color>} --hac-popover-background-color - Background of the popover.
* @cssprop {<length>} [--hac-popover-max-width=280px] - Maximum width.
* @cssprop {<length>} [--hac-popover-max-height=360px] - Maximum height.
* @cssprop --hac-popover-box-shadow - Shadow of the popover.
* @cssprop --hac-popover-border - Border shorthand. Set to `none` to remove it.
* @cssprop {<length>} [--hac-popover-border-radius=24px] - Corner radius.
* @cssprop [--hac-popover-padding=16px] - Padding around the content.
*
* @fires hac-popover-show - The popover is about to open. Cancelable.
* @fires hac-popover-after-show - The popover opened.
* @fires hac-popover-hide - The popover is about to close. Cancelable. `detail.reason` says why.
* @fires hac-popover-after-hide - The popover closed. `detail.reason` says why.
*/
export class HacPopover extends PopupBase {
/**
* What opens the popover. `hover` also opens it while a mouse rests on the
* anchor; a click still works, for touch and keyboard. `manual` leaves it to
* `show()`, `hide()` and `open`.
*/
@property() public trigger: "click" | "hover" | "manual" = "click";
/**
* Preferred placement relative to the anchor: `top`, `right`, `bottom` or
* `left`, optionally followed by `-start` or `-end`. Flips to the other
* side when there is no room.
*/
@property({ reflect: true }) public placement: Placement = "bottom-start";
protected readonly eventPrefix = TAG_NAME;
private _pinned = false;
private _timer?: number;
public disconnectedCallback(): void {
super.disconnectedCallback();
clearTimeout(this._timer);
}
protected willUpdate(changedProps: PropertyValues<this>): void {
super.willUpdate(changedProps);
if (changedProps.has("open")) {
if (this.anchor) {
setAriaExpanded(this.anchor, this.open);
}
}
}
protected updated(changedProps: PropertyValues<this>): void {
super.updated(changedProps);
// A cancelled hide has set `open` back by now, so it stays pinned
if (changedProps.has("open") && !this.open) {
this._pinned = false;
}
}
protected anchorChanged(
anchor: HTMLElement | null,
oldAnchor: HTMLElement | null
): void {
if (oldAnchor && oldAnchor !== anchor) {
setAriaExpanded(oldAnchor, null);
}
if (anchor) {
setAriaExpanded(anchor, this.open);
}
}
protected attachAnchor(anchor: HTMLElement): (() => void)[] {
return [
listen(anchor, "click", this._handleClick),
listen(anchor, "pointerenter", this._handleEnter),
listen(anchor, "pointerleave", this._handleLeave),
listen(anchor, "focusout", this._handleFocusOut),
listen(this, "pointerenter", this._handleEnter),
listen(this, "pointerleave", this._handleLeave),
listen(this, "focusout", this._handleFocusOut),
];
}
protected async handleEscape(): Promise<void> {
const focusInside = this._focusInside();
this.close("escape-key");
await this.updateComplete;
// A listener may have cancelled the hide
if (focusInside && !this.open) {
this.anchor?.focus();
}
}
private _focusInside(): boolean {
const root = this.getRootNode();
const active = deepActiveElement(
root instanceof ShadowRoot ? root : document
);
return (
containsComposed(this, active) ||
(this.anchor ? containsComposed(this.anchor, active) : false)
);
}
private _opensOnClick(): boolean {
return this.trigger !== "manual";
}
private _handleClick = (): void => {
if (!this._opensOnClick()) {
return;
}
clearTimeout(this._timer);
// Only hover opens it unpinned; a click then pins it instead of closing
if (this.open && (this._pinned || this.trigger !== "hover")) {
this.close("anchor-click");
return;
}
this._pinned = true;
this.open = true;
};
private _handleEnter = (ev: PointerEvent): void => {
if (ev.pointerType !== "mouse" || this.trigger !== "hover") {
return;
}
clearTimeout(this._timer);
if (!this.open) {
this._timer = window.setTimeout(() => {
// The trigger may have changed while waiting
if (this.trigger === "hover") {
this.open = true;
}
}, 150);
}
};
private _handleLeave = (ev: PointerEvent): void => {
if (
ev.pointerType !== "mouse" ||
this.trigger !== "hover" ||
this._pinned
) {
return;
}
clearTimeout(this._timer);
this._timer = window.setTimeout(() => {
// Keyboard users may have moved into the content; focusout closes it
if (this.trigger === "hover" && !this._focusInside()) {
this.close("mouse-leave");
}
}, 150);
};
private _handleFocusOut = (ev: FocusEvent): void => {
const next = ev.relatedTarget as Node | null;
if (!this.open || !next) {
return;
}
const insideAnchor = this.anchor
? containsComposed(this.anchor, next)
: false;
const insidePopover = containsComposed(this, next);
if (!insideAnchor && !insidePopover) {
this.close("focus-out");
}
};
static styles = [
PopupBase.styles,
css`
.body {
max-width: min(
var(--hac-popover-max-width, 280px),
var(--available-width, 100vw)
);
max-height: min(
var(--hac-popover-max-height, 360px),
var(--available-height, 100vh)
);
overflow: auto;
padding: var(--hac-popover-padding, var(--ha-space-4, 16px));
border: var(
--hac-popover-border,
1px solid var(--ha-color-border-neutral-quiet, rgba(0, 0, 0, 0.12))
);
border-radius: var(
--hac-popover-border-radius,
var(--ha-border-radius-3xl, 24px)
);
background-color: var(
--hac-popover-background-color,
var(--ha-color-surface-default, #fff)
);
color: var(--ha-color-text-primary, #141414);
box-shadow: var(
--hac-popover-box-shadow,
0 8px 28px rgba(0, 0, 0, 0.18)
);
font-family: var(--ha-font-family-body, inherit);
font-size: var(--ha-font-size-m, 14px);
line-height: 1.45;
overflow-wrap: anywhere;
animation: hac-popover-in 160ms ease;
}
@keyframes hac-popover-in {
from {
opacity: 0;
transform: translateY(4px);
}
}
/* min() needs Chrome 79; without it the whole max-width is dropped */
@supports not (max-width: min(1px, 2px)) {
.body {
max-width: var(--hac-popover-max-width, 280px);
max-height: var(--available-height, 100vh);
}
}
@media (prefers-reduced-motion: reduce) {
.body {
animation: none;
}
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
"hac-popover": HacPopover;
}
interface HTMLElementEventMap {
"hac-popover-show": CustomEvent<null>;
"hac-popover-after-show": CustomEvent<null>;
"hac-popover-hide": CustomEvent<PopupHideDetail>;
"hac-popover-after-hide": CustomEvent<PopupHideDetail>;
}
}
@@ -0,0 +1,14 @@
import type { ElementDefinition } from "../../utils/registration/definition";
import { HacPopover, TAG_NAME } from "./hac-popover";
export { HacPopover };
/**
* The bundled <hac-popover> for a scoped registry:
* `ScopedElementsMixin(LitElement, [hacPopover])` or
* `createScopedElementRegistry([hacPopover])`.
*/
export const hacPopover: ElementDefinition<typeof HacPopover> = {
tagName: TAG_NAME,
element: HacPopover,
};
@@ -1,6 +1,5 @@
import { define } from "../../utils/registration/define";
import { HacSpinner } from "./hac-spinner";
import { TAG_NAME } from "./info";
import { HacSpinner, TAG_NAME } from "./hac-spinner";
// Registers <hac-spinner> in the global registry, as used by Home Assistant
define(TAG_NAME, HacSpinner);
@@ -1,6 +1,9 @@
import { css, html, LitElement, nothing } from "lit";
import { property } from "lit/decorators.js";
/** Tag name of the element. */
export const TAG_NAME = "hac-spinner";
/**
* @element hac-spinner
*
@@ -14,13 +17,11 @@ import { property } from "lit/decorators.js";
* parent's name.
*
* @csspart spinner - The `svg` element.
* @csspart base - Same as `spinner`, kept for styles written for `ha-spinner`.
* Temporary, like the legacy variables.
*
* @cssprop --hac-spinner-size - Diameter of the spinner. Overrides `size`.
* @cssprop --hac-spinner-indicator-color - Color of the moving arc.
* @cssprop --hac-spinner-track-color - Color of the track.
* @cssprop --hac-spinner-track-width - Stroke width of the track and arc.
* @cssprop {<length>} --hac-spinner-size - Diameter of the spinner. Overrides `size`.
* @cssprop {<color>} --hac-spinner-indicator-color - Color of the moving arc.
* @cssprop {<color>} --hac-spinner-track-color - Color of the track.
* @cssprop {<length>} [--hac-spinner-track-width=4px] - Stroke width of the track and arc.
*/
export class HacSpinner extends LitElement {
/** Preset diameter: 16, 28, 48 or 68 pixels. Defaults to 48 pixels. */
@@ -57,7 +58,7 @@ export class HacSpinner extends LitElement {
protected render() {
return html`
<svg
part="spinner base"
part="spinner"
role="progressbar"
aria-label=${this.accessibleLabel || this.defaultLabel()}
aria-hidden=${this.getAttribute("aria-hidden") ?? nothing}
@@ -1,5 +0,0 @@
/** Tag name of the element. */
export const TAG_NAME = "hac-spinner";
/** Version of <hac-spinner>. */
export const VERSION = "0.1.0";
@@ -1,6 +1,5 @@
import type { ElementDefinition } from "../../utils/registration/definition";
import { HacSpinner } from "./hac-spinner";
import { TAG_NAME } from "./info";
import { HacSpinner, TAG_NAME } from "./hac-spinner";
export { HacSpinner };
@@ -0,0 +1,20 @@
/**
* Sets `aria-expanded` through the `ariaExpanded` property, so a button
* component can pass it on to the button inside it instead of getting the
* attribute on its host. Falls back to the attribute where browsers lack ARIA
* reflection, before Chrome 81 and Firefox 119.
*/
export const setAriaExpanded = (
element: HTMLElement,
expanded: boolean | null
): void => {
const value = expanded === null ? null : String(expanded);
const target: object = element;
if ("ariaExpanded" in target) {
element.ariaExpanded = value;
} else if (value === null) {
element.removeAttribute("aria-expanded");
} else {
element.setAttribute("aria-expanded", value);
}
};
@@ -0,0 +1,35 @@
/**
* Like `Node.contains`, but follows slots and shadow hosts, so slotted content
* counts as inside the element it is slotted into.
*/
export const containsComposed = (
container: Node,
node: Node | null
): boolean => {
let current: Node | null = node;
while (current) {
if (current === container) {
return true;
}
current =
(current as Element).assignedSlot ??
current.parentNode ??
(current as ShadowRoot).host ??
null;
}
return false;
};
/**
* The focused element, looking into open shadow roots. Pass the root an
* element lives in to also find focus inside a closed shadow root.
*/
export const deepActiveElement = (
root: Document | ShadowRoot = document
): Element | null => {
let active = root.activeElement;
while (active?.shadowRoot?.activeElement) {
active = active.shadowRoot.activeElement;
}
return active;
};
@@ -0,0 +1,14 @@
/**
* Adds an event listener and returns a function that removes it. Unlike the
* `signal` option, this also works before Chrome 90 and Safari 15.
*/
export const listen = <K extends keyof HTMLElementEventMap>(
target: EventTarget,
type: K,
listener: (ev: HTMLElementEventMap[K]) => void,
options?: boolean | AddEventListenerOptions
): (() => void) => {
target.addEventListener(type, listener as EventListener, options);
return () =>
target.removeEventListener(type, listener as EventListener, options);
};
@@ -0,0 +1,485 @@
import {
autoUpdate,
computePosition,
flip,
hide,
limitShift,
offset,
type Placement,
shift,
type SideObject,
size,
} from "@floating-ui/dom";
import {
css,
type CSSResultGroup,
html,
LitElement,
nothing,
type PropertyValues,
type TemplateResult,
} from "lit";
import { property, query } from "lit/decorators.js";
import { containsComposed } from "../element/focus";
import { listen } from "../element/listen";
const supportsPopover =
typeof HTMLElement !== "undefined" &&
Object.prototype.hasOwnProperty.call(HTMLElement.prototype, "popover");
// Open popups, newest last, so Escape closes only the topmost one. Kept on
// window, so scoped copies of the library on one page share it.
const popupRegistry = (typeof window === "undefined" ? {} : window) as Record<
symbol,
PopupBase[]
>;
const OPEN_POPUPS = Symbol.for("hac-open-popups");
popupRegistry[OPEN_POPUPS] ??= [];
const openPopups = popupRegistry[OPEN_POPUPS];
const VIEWPORT_PADDING = 8;
/**
* Why a popup closed. `programmatic` covers `hide()`, setting `open`,
* `disabled` and the anchor going away.
*/
export type PopupHideReason =
| "anchor-click"
| "click-outside"
| "escape-key"
| "focus-out"
| "mouse-leave"
| "programmatic";
export interface PopupHideDetail {
reason: PopupHideReason;
}
const SIDES = ["top", "right", "bottom", "left"] as const;
// Distance to keep from each viewport edge: the padding plus the safe area,
// like a notch or the Android navigation bar, which flip, shift and size
// otherwise ignore
const edgePadding = (body: HTMLElement): SideObject => {
const styles = getComputedStyle(body);
const padding = {} as SideObject;
for (const side of SIDES) {
padding[side] =
VIEWPORT_PADDING +
(parseFloat(styles.getPropertyValue(`--_safe-area-${side}`)) || 0);
}
return padding;
};
/**
* Base of floating elements like hac-popover: finds the anchor by id, shows
* the body in the top layer where the Popover API exists (fixed positioning
* otherwise), positions it with floating-ui and closes it with Escape or a
* press outside. Events are named after the element, like
* `hac-popover-show`, so a listener further out can tell them apart from
* those of a dialog or menu around it.
*/
export abstract class PopupBase extends LitElement {
/** The id of the anchor element, in the same root as the popup. */
@property() public for?: string;
/** Whether the popup is shown. */
@property({ type: Boolean, reflect: true }) public open = false;
/**
* Preferred placement relative to the anchor: `top`, `right`, `bottom` or
* `left`, optionally followed by `-start` or `-end`. Flips to the other
* side when there is no room.
*/
@property({ reflect: true }) public placement: Placement = "top";
/** Distance from the anchor in pixels. */
@property({ type: Number }) public distance = 8;
/** Offset along the anchor in pixels. */
@property({ type: Number }) public skidding = 0;
/** Prevents the popup from opening. */
@property({ type: Boolean, reflect: true }) public disabled = false;
@query(".body", true) protected body?: HTMLElement;
protected anchor: HTMLElement | null = null;
/** Prefix of the events, usually the tag name. */
protected abstract readonly eventPrefix: string;
// Whether the body is shown. `open` can briefly differ while a show or hide
// event is being cancelled.
private _shown = false;
private _hideReason?: PopupHideReason;
private _insidePress?: Event;
private _detachAnchor: (() => void)[] = [];
private _detachDocument: (() => void)[] = [];
private _detachRoot: (() => void)[] = [];
private _stopAutoUpdate?: () => void;
public show(): void {
this.open = true;
}
public hide(): void {
this.open = false;
}
public connectedCallback(): void {
super.connectedCallback();
// A parent may render a new anchor with the same id. Capture listeners on
// the root run before the anchor's own, so they can bind the new one in
// time for the event.
const root = this.getRootNode();
this._detachRoot = [
listen(root, "click", this._refreshAnchor, true),
listen(root, "pointerover", this._refreshAnchor, true),
listen(root, "focusin", this._refreshAnchor, true),
listen(this, "pointerdown", this._markInsidePress, true),
];
if (this.hasUpdated) {
this._resolveAnchor();
}
}
public disconnectedCallback(): void {
super.disconnectedCallback();
this._detachRoot.forEach((detach) => detach());
this._detachRoot = [];
this._setAnchor(null);
this._teardownOpen();
}
protected updated(changedProps: PropertyValues<this>): void {
super.updated(changedProps);
// Also retry while the anchor is missing, as it may render after the popup
if (changedProps.has("for") || (this.for && !this.anchor?.isConnected)) {
this._resolveAnchor();
}
if (changedProps.has("disabled") && this.disabled && this.open) {
this.open = false;
}
if (changedProps.has("open")) {
this._syncOpen();
}
if (
this._shown &&
(changedProps.has("placement") ||
changedProps.has("distance") ||
changedProps.has("skidding"))
) {
this._reposition();
}
}
/**
* Adds the listeners that open and close the popup to the anchor. Returns
* the functions that remove them again.
*/
protected abstract attachAnchor(anchor: HTMLElement): (() => void)[];
/** Called after the anchor changed, to update its ARIA attributes. */
protected anchorChanged(
_anchor: HTMLElement | null,
_oldAnchor: HTMLElement | null
): void {
// Does nothing by default
}
/** Closes the popup and passes the reason to the hide events. */
protected close(reason: PopupHideReason): void {
if (this.open) {
this._hideReason = reason;
this.open = false;
}
}
/** Closes the popup on Escape. Subclasses may also move focus. */
protected handleEscape(): void {
this.close("escape-key");
}
protected renderBody(): TemplateResult {
return html`<slot></slot>`;
}
protected render(): TemplateResult {
return html`<div
part="body"
class="body"
popover=${supportsPopover ? "manual" : nothing}
?hidden=${!this.open}
>
${this.renderBody()}
</div>`;
}
private _resolveAnchor(): void {
// A popup outside the document has an element as its root, which can't
// look up ids
const root = this.getRootNode();
const anchor =
this.for && (root instanceof Document || root instanceof ShadowRoot)
? root.getElementById(this.for)
: null;
if (anchor !== this.anchor) {
this._setAnchor(anchor);
}
}
private _setAnchor(anchor: HTMLElement | null): void {
const oldAnchor = this.anchor;
this._detachAnchor.forEach((detach) => detach());
this.anchor = anchor;
this._detachAnchor = anchor
? [
...this.attachAnchor(anchor),
listen(anchor, "pointerdown", this._markInsidePress, true),
]
: [];
this.anchorChanged(anchor, oldAnchor);
if (!anchor && this.open) {
this.open = false;
}
if (anchor && this._shown) {
this._startAutoUpdate();
}
}
// Runs a show or hide when `open` and the shown state differ. A cancelled
// event resets `open`, which then matches again and runs nothing.
private _syncOpen(): void {
const reason = this._hideReason ?? "programmatic";
this._hideReason = undefined;
if (this.open === this._shown) {
return;
}
if (this.open) {
if (!this.anchor?.isConnected) {
this._resolveAnchor();
}
if (this.disabled || !this.anchor) {
this.open = false;
return;
}
const canceled = this._fire("show", true);
if (canceled) {
this.open = false;
return;
}
this._showBody();
this._fire("after-show");
return;
}
const detail: PopupHideDetail = { reason };
const canceled = this._fire("hide", true, detail);
if (canceled) {
this.open = true;
return;
}
this._teardownOpen();
this._fire("after-hide", false, detail);
}
private _showBody(): void {
const body = this.body;
if (!body) {
return;
}
this._shown = true;
if (supportsPopover && !body.matches(":popover-open")) {
body.showPopover();
}
openPopups.push(this);
this._detachDocument = [
// Capture phase on window, so Escape closes the popup before a dialog
// around it sees the key
listen(window, "keydown", this._handleKeyDown, true),
listen(document, "pointerdown", this._handlePointerDown, true),
];
this._startAutoUpdate();
}
private _startAutoUpdate(): void {
this._stopAutoUpdate?.();
const body = this.body;
this._stopAutoUpdate =
this.anchor && body
? autoUpdate(this.anchor, body, () => this._reposition())
: undefined;
}
private _teardownOpen(): void {
if (!this._shown) {
return;
}
this._shown = false;
this._detachDocument.forEach((detach) => detach());
this._detachDocument = [];
this._stopAutoUpdate?.();
this._stopAutoUpdate = undefined;
const index = openPopups.indexOf(this);
if (index !== -1) {
openPopups.splice(index, 1);
}
const body = this.body;
if (supportsPopover && body?.matches(":popover-open")) {
body.hidePopover();
}
}
private async _reposition(): Promise<void> {
// autoUpdate's ResizeObserver also fires when the anchor leaves the DOM,
// so rebind to a replacement here, or close when there is none
if (this.anchor && !this.anchor.isConnected) {
this._refreshAnchor();
return;
}
const anchor = this.anchor;
const body = this.body;
if (!anchor || !body || !this._shown) {
return;
}
const padding = edgePadding(body);
const position = await computePosition(anchor, body, {
strategy: "fixed",
placement: this.placement,
middleware: [
offset({ mainAxis: this.distance, crossAxis: this.skidding }),
flip({ padding }),
// Keeps it at the anchor, not at the edge of the screen
shift({ padding, limiter: limitShift() }),
size({
padding,
apply: ({ availableWidth, availableHeight }) => {
body.style.setProperty(
"--available-width",
`${Math.max(0, availableWidth)}px`
);
body.style.setProperty(
"--available-height",
`${Math.max(0, availableHeight)}px`
);
},
}),
// The top layer isn't clipped by scrolling containers, so hide it
// while its anchor is scrolled out of view
hide(),
],
});
const { x, y, placement, middlewareData } = position;
body.style.left = `${x}px`;
body.style.top = `${y}px`;
body.style.visibility = middlewareData.hide?.referenceHidden
? "hidden"
: "";
body.dataset.placement = placement;
}
private _refreshAnchor = (): void => {
if (this.for && !this.anchor?.isConnected) {
this._resolveAnchor();
}
};
private _handleKeyDown = (ev: KeyboardEvent): void => {
if (
ev.key !== "Escape" ||
ev.isComposing ||
openPopups[openPopups.length - 1] !== this
) {
return;
}
ev.preventDefault();
ev.stopPropagation();
this.handleEscape();
};
private _markInsidePress = (ev: PointerEvent): void => {
this._insidePress = ev;
};
private _handlePointerDown = (ev: PointerEvent): void => {
const path = ev.composedPath();
if (path.includes(this) || (this.anchor && path.includes(this.anchor))) {
return;
}
// In a closed shadow root the path stops at its host. The popup's and
// anchor's own listeners see the press later, so decide after them.
const target = ev.target as Node | null;
if (target && containsComposed(target, this)) {
setTimeout(() => {
if (this._insidePress !== ev) {
this.close("click-outside");
}
});
return;
}
this.close("click-outside");
};
// Returns whether a listener canceled the event
private _fire(
type: string,
cancelable = false,
detail: PopupHideDetail | null = null
): boolean {
return !this.dispatchEvent(
new CustomEvent(`${this.eventPrefix}-${type}`, {
bubbles: true,
composed: true,
cancelable,
detail,
})
);
}
static styles: CSSResultGroup = css`
:host {
display: contents;
/* Home Assistant's insets include the companion app's */
--_safe-area-top: var(
--safe-area-inset-top,
env(safe-area-inset-top, 0px)
);
--_safe-area-right: var(
--safe-area-inset-right,
env(safe-area-inset-right, 0px)
);
--_safe-area-bottom: var(
--safe-area-inset-bottom,
env(safe-area-inset-bottom, 0px)
);
--_safe-area-left: var(
--safe-area-inset-left,
env(safe-area-inset-left, 0px)
);
}
.body {
position: fixed;
inset: auto;
left: 0;
top: 0;
z-index: 1000;
box-sizing: border-box;
width: max-content;
max-width: var(--available-width, 100vw);
margin: 0;
border: 0;
overflow: visible;
}
.body[hidden] {
display: none;
}
`;
}
+285
View File
@@ -0,0 +1,285 @@
import { afterEach, describe, expect, it } from "vitest";
import "../src/components/popover/global";
import type { HacPopover } from "../src/components/popover/hac-popover";
const mount = async () => {
document.body.innerHTML = `
<button id="anchor">More info</button>
<hac-popover for="anchor"><a id="link" href="#">Learn more</a></hac-popover>
<button id="outside">Next</button>
`;
const popover = document.querySelector("hac-popover") as HacPopover;
await popover.updateComplete;
const get = (id: string) => document.getElementById(id) as HTMLElement;
return {
popover,
anchor: get("anchor"),
link: get("link"),
outside: get("outside"),
};
};
const pressEscape = () =>
window.dispatchEvent(
new KeyboardEvent("keydown", { key: "Escape", bubbles: true })
);
afterEach(() => {
document.body.innerHTML = "";
});
// Keyboard and screen reader users rely on the anchor's state and on focus
// coming back to the anchor; nothing else shows them the popover closed.
describe("hac-popover", () => {
it("links the anchor and toggles on click", async () => {
const { popover, anchor } = await mount();
expect(anchor.getAttribute("aria-expanded")).toBe("false");
anchor.click();
await popover.updateComplete;
expect(popover.open).toBe(true);
expect(anchor.getAttribute("aria-expanded")).toBe("true");
anchor.click();
await popover.updateComplete;
expect(popover.open).toBe(false);
expect(anchor.getAttribute("aria-expanded")).toBe("false");
});
it("returns focus to the anchor on Escape from inside", async () => {
const { popover, anchor, link } = await mount();
anchor.click();
await popover.updateComplete;
link.focus();
pressEscape();
await popover.updateComplete;
expect(popover.open).toBe(false);
expect(document.activeElement).toBe(anchor);
});
it("closes when focus leaves the anchor and the content", async () => {
const { popover, anchor, link, outside } = await mount();
anchor.focus();
anchor.click();
await popover.updateComplete;
link.focus();
await popover.updateComplete;
expect(popover.open).toBe(true);
outside.focus();
await popover.updateComplete;
expect(popover.open).toBe(false);
});
it("stays open while focus is inside when the mouse leaves", async () => {
const { popover, anchor, link } = await mount();
popover.trigger = "hover";
const mouse = (type: string) =>
anchor.dispatchEvent(new PointerEvent(type, { pointerType: "mouse" }));
mouse("pointerenter");
await new Promise((resolve) => {
setTimeout(resolve, 200);
});
expect(popover.open).toBe(true);
link.focus();
mouse("pointerleave");
await new Promise((resolve) => {
setTimeout(resolve, 200);
});
expect(popover.open).toBe(true);
});
it("runs each transition once when one is cancelled", async () => {
const { popover, anchor } = await mount();
const fired: string[] = [];
for (const type of ["show", "after-show", "hide", "after-hide"]) {
popover.addEventListener(`hac-popover-${type}`, () => fired.push(type));
}
popover.addEventListener("hac-popover-hide", (ev) => ev.preventDefault(), {
once: true,
});
anchor.click();
await popover.updateComplete;
popover.hide();
await popover.updateComplete;
await popover.updateComplete;
expect(popover.open).toBe(true);
expect(fired).toEqual(["show", "after-show", "hide"]);
});
// A picker cancels some hides; the popover must then behave as if still open
it("keeps focus and pinning when a hide is cancelled", async () => {
const { popover, anchor, link } = await mount();
popover.addEventListener("hac-popover-hide", (ev) => ev.preventDefault(), {
once: true,
});
anchor.click();
await popover.updateComplete;
link.focus();
pressEscape();
await popover.updateComplete;
await popover.updateComplete;
expect(popover.open).toBe(true);
expect(document.activeElement).toBe(link);
anchor.click();
await popover.updateComplete;
expect(popover.open).toBe(false);
});
// Lit re-renders can swap the anchor for a new element with the same id
it("follows an anchor that was replaced", async () => {
const { popover, anchor } = await mount();
const replacement = document.createElement("button");
anchor.replaceWith(replacement);
replacement.id = "anchor";
replacement.click();
await popover.updateComplete;
expect(popover.open).toBe(true);
expect(replacement.getAttribute("aria-expanded")).toBe("true");
});
it("closes on an anchor click after opening from code", async () => {
const { popover, anchor } = await mount();
popover.show();
await popover.updateComplete;
anchor.click();
await popover.updateComplete;
expect(popover.open).toBe(false);
});
it("rebinds or closes when the anchor changes while open", async () => {
const { popover, anchor } = await mount();
anchor.click();
await popover.updateComplete;
const replacement = document.createElement("button");
replacement.id = "anchor";
anchor.replaceWith(replacement);
// Browsers report the removal through ResizeObserver, which jsdom lacks
window.dispatchEvent(new Event("resize"));
await popover.updateComplete;
expect(popover.open).toBe(true);
expect(replacement.getAttribute("aria-expanded")).toBe("true");
replacement.remove();
window.dispatchEvent(new Event("resize"));
await popover.updateComplete;
await popover.updateComplete;
expect(popover.open).toBe(false);
});
// A custom card may put the popover in a closed shadow root, which hides it
// from the document's view of events and focus
it("works inside a closed shadow root", async () => {
const host = document.createElement("div");
document.body.append(host);
const root = host.attachShadow({ mode: "closed" });
root.innerHTML = `
<button id="anchor">More info</button>
<hac-popover for="anchor"><a id="link" href="#">Learn more</a></hac-popover>
`;
const popover = root.querySelector("hac-popover") as HacPopover;
const anchor = root.getElementById("anchor") as HTMLElement;
const link = root.getElementById("link") as HTMLElement;
const press = (target: Element) =>
target.dispatchEvent(
new PointerEvent("pointerdown", { bubbles: true, composed: true })
);
const settle = () =>
new Promise((resolve) => {
setTimeout(resolve);
});
await popover.updateComplete;
anchor.click();
await popover.updateComplete;
press(link);
await settle();
expect(popover.open).toBe(true);
link.focus();
pressEscape();
await popover.updateComplete;
expect(popover.open).toBe(false);
expect(root.activeElement).toBe(anchor);
anchor.click();
await popover.updateComplete;
press(document.body);
await settle();
expect(popover.open).toBe(false);
});
// Parents like a picker react differently to Escape than to a press outside
it("tells why it closed", async () => {
const { popover, anchor, outside } = await mount();
const reasons: string[] = [];
popover.addEventListener("hac-popover-after-hide", (ev) =>
reasons.push(ev.detail.reason)
);
const closeWith = async (close: () => void) => {
anchor.click();
await popover.updateComplete;
close();
await popover.updateComplete;
};
await closeWith(() => anchor.click());
await closeWith(pressEscape);
await closeWith(() =>
outside.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }))
);
await closeWith(() => popover.hide());
expect(reasons).toEqual([
"anchor-click",
"escape-key",
"click-outside",
"programmatic",
]);
});
it("finds an anchor rendered after the popover", async () => {
document.body.innerHTML = `<hac-popover for="late">Text</hac-popover>`;
const popover = document.querySelector("hac-popover") as HacPopover;
await popover.updateComplete;
const anchor = document.createElement("button");
anchor.id = "late";
popover.before(anchor);
popover.show();
await popover.updateComplete;
expect(popover.open).toBe(true);
expect(anchor.getAttribute("aria-expanded")).toBe("true");
});
// Button components put the state on their inner button; on the host it
// would be announced a second time
it("hands aria-expanded to a button component as a property", async () => {
document.body.innerHTML = `<hac-popover for="anchor">Text</hac-popover>`;
const popover = document.querySelector("hac-popover") as HacPopover;
// Stands in for a component that overrides the ariaExpanded property
const anchor = document.createElement("span");
anchor.id = "anchor";
let expanded: string | null = null;
Object.defineProperty(anchor, "ariaExpanded", {
get: () => expanded,
set: (value: string | null) => {
expanded = value;
},
});
popover.before(anchor);
popover.show();
await popover.updateComplete;
expect(expanded).toBe("true");
expect(anchor.hasAttribute("aria-expanded")).toBe(false);
});
});
+2223 -1300
View File
File diff suppressed because it is too large. Load diff
+4
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:
@@ -32,6 +34,8 @@ overrides:
clean-css: 5.3.3
"@lit/reactive-element": 2.1.2
tslib: 2.9.1
# ELK is copyleft (EPL-2.0 or GPL-3.0) and diagrams use dagre, so leave it out
"mermaid>elkjs": "-"
patchedDependencies:
[email protected]: patches/[email protected]
+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"
+17 -2
View File
@@ -62,6 +62,15 @@
"datasourceTemplate": "github-releases",
"extractVersionTemplate": "^v(?<version>.+)$"
},
{
"description": "Keep zizmor used in CI up to date",
"customType": "regex",
"managerFilePatterns": ["/^\\.github/workflows/actionlint\\.yaml$/"],
"matchStrings": ["ZIZMOR_VERSION: (?<currentValue>\\S+)"],
"depNameTemplate": "zizmorcore/zizmor",
"datasourceTemplate": "github-releases",
"extractVersionTemplate": "^v(?<version>.+)$"
},
{
"description": "Keep gh-actions-lock in CI and Renovate's lockfile generator on the same version",
"customType": "regex",
@@ -94,6 +103,12 @@
"matchDepTypes": ["peerDependencies"],
"rangeStrategy": "widen"
},
{
"description": "Keep semver ranges for dependencies of the published components package, so consumers can share one copy with other libraries",
"matchFileNames": ["packages/components/package.json"],
"matchDepTypes": ["dependencies"],
"rangeStrategy": "bump"
},
{
"description": "Group all Python version updates from home-assistant/core",
"matchDepNames": ["python"],
@@ -126,9 +141,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",
+1
View File
@@ -28,6 +28,7 @@ const ALLOWED_LICENSES = new Set([
"CC0-1.0",
"(MIT OR CC0-1.0)",
"(MIT OR Apache-2.0)",
"(MPL-2.0 OR Apache-2.0)", // dompurify, used under Apache-2.0
"(MIT AND Zlib)",
"PSF-2.0", // argparse - Python Software Foundation License (permissive)
"Public Domain",
+1 -7
View File
@@ -1,8 +1,6 @@
/* eslint-disable lit/prefer-static-styles */
import { html } from "lit";
import { customElement, state } from "lit/decorators";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../common/translations/localize";
import { customElement } from "lit/decorators";
import { HaForm } from "../components/ha-form/ha-form";
import "./ha-auth-form-string";
@@ -10,10 +8,6 @@ const localizeBaseKey = "ui.panel.page-authorize.form";
@customElement("ha-auth-form")
export class HaAuthForm extends HaForm {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
protected getFormProperties(): Record<string, any> {
return {
localize: this._localize,
+20 -7
View File
@@ -1,5 +1,6 @@
import type { HassConfig } from "home-assistant-js-websocket";
import { listenMediaQuery } from "../dom/media_query";
import type { HomeAssistant } from "../../types";
import type { FrontendLocaleData } from "../../data/translation";
import type {
TimeCondition,
VisibilityCondition,
@@ -19,7 +20,8 @@ const MAX_TIMEOUT_DELAY = 2147483647;
* Delays past the setTimeout max are capped and retried without firing.
*/
function scheduleTimeBoundaryListener(
getHass: () => HomeAssistant,
getLocale: () => FrontendLocaleData,
getConfig: () => HassConfig,
timeCondition: Omit<TimeCondition, "condition">,
addListener: (unsub: () => void) => void,
onBoundary: () => void
@@ -27,8 +29,12 @@ function scheduleTimeBoundaryListener(
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const scheduleUpdate = () => {
// Read hass here so a timezone change applies at the next boundary.
const delay = calculateNextTimeUpdate(getHass(), timeCondition);
// Read these here so a timezone change applies at the next boundary.
const delay = calculateNextTimeUpdate(
getLocale(),
getConfig(),
timeCondition
);
if (delay === undefined) return;
@@ -59,13 +65,14 @@ function scheduleTimeBoundaryListener(
* could have flipped.
*
* This does not evaluate the conditions itself: the caller recombines client
* and server results on notification. Used by `ConditionEvaluatorController`,
* and server results on notification. Used by `ConditionEvaluator`,
* which merges these client signals with the results of `subscribe_condition`
* subscriptions.
*/
export function observeConditionChanges(
conditions: VisibilityCondition[],
getHass: () => HomeAssistant,
getLocale: () => FrontendLocaleData,
getConfig: () => HassConfig,
addListener: (unsub: () => void) => void,
onChange: () => void
): void {
@@ -74,6 +81,12 @@ export function observeConditionChanges(
});
extractTimeConditions(conditions).forEach((timeCondition) => {
scheduleTimeBoundaryListener(getHass, timeCondition, addListener, onChange);
scheduleTimeBoundaryListener(
getLocale,
getConfig,
timeCondition,
addListener,
onChange
);
});
}
@@ -0,0 +1,66 @@
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 { ConditionEvaluator } 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 => {
let active = true;
const evaluator = new ConditionEvaluator({
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;
evaluator.connect();
evaluator.setInputs(hass, hass.connection, hass.localize);
evaluator.observe(validConditions, getContext);
return {
update: (newHass) => {
if (active) {
evaluator.setInputs(newHass, newHass.connection, newHass.localize);
}
},
unsubscribe: () => {
active = false;
evaluator.disconnect();
},
};
};
+8 -5
View File
@@ -5,24 +5,27 @@ import {
addMinutes,
differenceInMilliseconds,
} from "date-fns";
import type { HomeAssistant } from "../../types";
import type { HassConfig } from "home-assistant-js-websocket";
import type { FrontendLocaleData } from "../../data/translation";
import { TimeZone } from "../../data/translation";
import { parseTimeString } from "../datetime/check_time";
import type { TimeCondition } from "../../panels/lovelace/common/validate-condition";
/**
* Calculate milliseconds until next time boundary for a time condition
* @param hass Home Assistant object
* @param locale User locale (time zone preference)
* @param config Core config (server time zone)
* @param timeCondition Time condition to calculate next update for
* @returns Milliseconds until next boundary, or undefined if no boundaries
*/
export function calculateNextTimeUpdate(
hass: HomeAssistant,
locale: FrontendLocaleData,
config: HassConfig,
{ after, before, weekdays }: Omit<TimeCondition, "condition">
): number | undefined {
const timezone =
hass.locale.time_zone === TimeZone.server
? hass.config.time_zone
locale.time_zone === TimeZone.server
? config.time_zone
: Intl.DateTimeFormat().resolvedOptions().timeZone;
const now = new TZDate(new Date(), timezone);
@@ -1,16 +1,31 @@
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
import type {
ReactiveController,
ReactiveControllerHost,
} from "@lit/reactive-element/reactive-controller";
import type { Connection, UnsubscribeFunc } from "home-assistant-js-websocket";
Connection,
HassEntityStates,
UnsubscribeFunc,
} from "home-assistant-js-websocket";
import { subscribeCondition } from "../../data/automation";
import {
configContext,
connectionContext,
internationalizationContext,
registriesContext,
statesContext,
} from "../../data/context";
import type {
Condition,
ConditionContext,
ConditionHass,
VisibilityCondition,
} from "../../panels/lovelace/common/validate-condition";
import { checkConditionsMet } from "../../panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../types";
import type {
HomeAssistantConfig,
HomeAssistantInternationalization,
HomeAssistantRegistries,
} from "../../types";
import { consumeContext, ContextController } from "../decorators/consume";
import type { LocalizeFunc } from "../translations/localize";
import { observeConditionChanges } from "../condition/listeners";
import { isPureClientCondition } from "../condition/translate";
import type {
@@ -38,19 +53,22 @@ const firstDefined = (
/**
* Live evaluation of a visibility tree: `subscribe_condition` for server
* subtrees, local checks for screen/user/time/etc. Call {@link observe} when
* inputs change. Result stays `unknown` until server replies so nothing flashes.
* subtrees, local checks for screen/user/time/etc. Call {@link observe} and
* {@link setInputs} when inputs change. Result stays `unknown` until server
* replies so nothing flashes.
*/
export class ConditionEvaluatorController implements ReactiveController {
private _host: ReactiveControllerHost;
export class ConditionEvaluator {
private readonly _onResult: ConditionEvaluatorOptions["onResult"];
private readonly _resubscribeDelay: number;
private _conditions?: VisibilityCondition[];
private _hass?: HomeAssistant;
private _conditionHass?: ConditionHass;
private _connection?: Connection;
private _localize?: LocalizeFunc;
private _getContext?: () => ConditionContext;
@@ -65,7 +83,7 @@ export class ConditionEvaluatorController implements ReactiveController {
private _hasPendingResubscribe = false;
// Resubscribe if hass.connection is replaced even when the tree is unchanged.
// Resubscribe if the connection is replaced even when the tree is unchanged.
private _subscribedConnection?: Connection;
// Skip JSON.stringify when the same array is observed again.
@@ -100,15 +118,10 @@ export class ConditionEvaluatorController implements ReactiveController {
private _notifiedError?: string;
constructor(
host: ReactiveControllerHost,
options: ConditionEvaluatorOptions
) {
this._host = host;
constructor(options: ConditionEvaluatorOptions) {
this._onResult = options.onResult;
this._resubscribeDelay =
options.resubscribeDelay ?? DEFAULT_RESUBSCRIBE_DELAY;
host.addController(this);
}
public get result(): ConditionEvaluation {
@@ -120,25 +133,38 @@ export class ConditionEvaluatorController implements ReactiveController {
}
/**
* Update inputs. Resubscribes only when the tree (or connection) changes.
* Update the tree. Resubscribes only when its content changes.
*/
public observe(
conditions: VisibilityCondition[] | undefined,
hass: HomeAssistant | undefined,
getContext?: () => ConditionContext
): void {
this._conditions = conditions;
this._hass = hass;
this._getContext = getContext;
this._sync();
}
public hostConnected(): void {
/**
* Update what client conditions read and where server subtrees subscribe.
* Resubscribes only when the connection is replaced.
*/
public setInputs(
conditionHass: ConditionHass | undefined,
connection: Connection | undefined,
localize: LocalizeFunc | undefined
): void {
this._conditionHass = conditionHass;
this._connection = connection;
this._localize = localize;
this._sync();
}
public connect(): void {
this._connected = true;
this._sync();
}
public hostDisconnected(): void {
public disconnect(): void {
this._connected = false;
this._teardown();
// Subscriptions are gone; don't keep showing a stale result.
@@ -176,14 +202,14 @@ export class ConditionEvaluatorController implements ReactiveController {
return;
}
const signature = this._signatureOf(this._conditions);
// Resubscribe when the tree content or hass.connection changed.
// Resubscribe when the tree content or the connection changed.
const targetSignature = this._hasPendingResubscribe
? this._pendingSignature
: this._subscribedSignature;
const connectionReplaced =
this._subscribedConnection !== undefined &&
this._hass !== undefined &&
this._hass.connection !== this._subscribedConnection;
this._connection !== undefined &&
this._connection !== this._subscribedConnection;
if (signature !== targetSignature || connectionReplaced) {
// Drop the old subscriptions immediately so their result can't leak through.
this._teardown();
@@ -217,12 +243,13 @@ export class ConditionEvaluatorController implements ReactiveController {
this._teardown();
const conditions = this._conditions;
const hass = this._hass;
const conditionHass = this._conditionHass;
const connection = this._connection;
this._pendingSignature = undefined;
this._hasPendingResubscribe = false;
if (!conditions || !hass) {
// Don't mark subscribed yet; hass often arrives after connect.
if (!conditions || !conditionHass || !connection) {
// Don't mark subscribed yet; inputs often arrive after connect.
this._setResult("unknown", undefined);
return;
}
@@ -232,7 +259,6 @@ export class ConditionEvaluatorController implements ReactiveController {
this._split = split;
const generation = this._generation;
const connection: Connection = hass.connection;
this._subscribedConnection = connection;
for (const subtree of split.serverSubtrees) {
@@ -267,7 +293,9 @@ export class ConditionEvaluatorController implements ReactiveController {
}
this._serverResults[subtree.id] = undefined;
this._subtreeErrors[subtree.id] =
getWsErrorMessage(err) ?? hass.localize("ui.common.unknown_error");
getWsErrorMessage(err) ??
this._localize?.("ui.common.unknown_error") ??
String(err);
this._recompute();
});
this._subscriptions.push(subscription);
@@ -275,7 +303,8 @@ export class ConditionEvaluatorController implements ReactiveController {
observeConditionChanges(
conditions,
() => this._hass ?? hass,
() => (this._conditionHass ?? conditionHass).locale,
() => (this._conditionHass ?? conditionHass).config,
(unsub) => this._listeners.push(unsub),
() => this._recompute()
);
@@ -284,16 +313,20 @@ export class ConditionEvaluatorController implements ReactiveController {
}
private _recompute(): void {
if (!this._split || !this._hass) {
if (!this._split || !this._conditionHass) {
this._setResult("unknown", undefined);
return;
}
const hass = this._hass;
const conditionHass = this._conditionHass;
const context = this._getContext?.() ?? {};
const clientEvaluator: ClientConditionEvaluator = (condition) => {
try {
return checkConditionsMet([condition as Condition], hass, context);
return checkConditionsMet(
[condition as Condition],
conditionHass,
context
);
} catch (_err) {
return false;
}
@@ -326,7 +359,6 @@ export class ConditionEvaluatorController implements ReactiveController {
this._notifiedResult = result;
this._notifiedError = error;
this._onResult(result, error);
this._host.requestUpdate();
}
private _teardown(): void {
@@ -353,3 +385,108 @@ export class ConditionEvaluatorController implements ReactiveController {
this._subscribedConnection = undefined;
}
}
/**
* {@link ConditionEvaluator} for a Lit host. Reads states, user, config,
* locale, registries and the connection from context; the host only passes
* the tree to {@link observe}.
*/
export class ConditionEvaluatorController extends ContextController {
@consumeContext({ context: statesContext, subscribe: true })
private _states?: HassEntityStates | null;
@consumeContext({ context: configContext, subscribe: true })
private _hassConfig?: HomeAssistantConfig | null;
@consumeContext({ context: internationalizationContext, subscribe: true })
private _i18n?: HomeAssistantInternationalization | null;
@consumeContext({ context: registriesContext, subscribe: true })
private _registries?: HomeAssistantRegistries | null;
@consumeContext({
context: connectionContext,
subscribe: true,
transform: (value) => value?.connection,
})
private _connection?: Connection;
private readonly _evaluator: ConditionEvaluator;
// Hosts without conditions skip the per-state-message input rebuild.
private _observing = false;
private _inputsStale = false;
constructor(
host: ReactiveControllerHost & HTMLElement,
options: ConditionEvaluatorOptions
) {
super(host);
this._evaluator = new ConditionEvaluator({
resubscribeDelay: options.resubscribeDelay,
onResult: (result, error) => {
options.onResult(result, error);
host.requestUpdate();
},
});
}
public get result(): ConditionEvaluation {
return this._evaluator.result;
}
public get error(): string | undefined {
return this._evaluator.error;
}
public observe(
conditions: VisibilityCondition[] | undefined,
getContext?: () => ConditionContext
): void {
this._observing = conditions !== undefined;
if (this._observing && this._inputsStale) {
this._pushInputs();
}
this._evaluator.observe(conditions, getContext);
}
public hostConnected(): void {
this._evaluator.connect();
}
public hostDisconnected(): void {
this._evaluator.disconnect();
}
protected contextUpdated(): void {
if (!this._observing) {
this._inputsStale = true;
return;
}
this._pushInputs();
}
private _pushInputs(): void {
this._inputsStale = false;
const hassConfig = this._hassConfig;
const locale = this._i18n?.locale;
// States and registries load after connect; missing ones read as empty,
// so conditions that don't need them are not held back.
this._evaluator.setInputs(
hassConfig && locale
? {
states: this._states ?? {},
user: hassConfig.user,
locale,
config: hassConfig.config,
entities: this._registries?.entities ?? {},
devices: this._registries?.devices ?? {},
areas: this._registries?.areas ?? {},
}
: undefined,
this._connection,
this._i18n?.localize
);
}
}
@@ -2,7 +2,7 @@ import type {
ReactiveController,
ReactiveControllerHost,
} from "@lit/reactive-element/reactive-controller";
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } from "home-assistant-js-websocket";
import { timerTimeRemaining } from "../../data/timer";
/**
@@ -17,7 +17,7 @@ export class TimerRemainingTimeController implements ReactiveController {
private _host: ReactiveControllerHost;
private _stateObj?: HassEntity;
private _stateObj?: HassEntityState;
private _interval?: number;
@@ -26,7 +26,7 @@ export class TimerRemainingTimeController implements ReactiveController {
host.addController(this);
}
public setStateObj(stateObj: HassEntity | undefined): void {
public setStateObj(stateObj: HassEntityState | undefined): void {
this._stateObj = stateObj;
this._startInterval();
}
+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,
+16 -13
View File
@@ -1,5 +1,8 @@
import type { Context } from "@lit/context";
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
import type {
HassEntityStates,
HassEntityState,
} from "home-assistant-js-websocket";
import type {
HomeAssistant,
HomeAssistantInternationalization,
@@ -28,9 +31,9 @@ const resolveAtPath = (host: unknown, path: readonly string[]) => {
return cur;
};
/** Reuse `previous` when every entry still references the same `HassEntity`. */
/** Reuse `previous` when every entry still references the same `HassEntityState`. */
export const preserveUnchangedEntityStatesRecord = <
T extends Record<string, HassEntity | undefined>,
T extends Record<string, HassEntityState | undefined>,
>(
previous: T | undefined,
next: T
@@ -80,7 +83,7 @@ const composeDecorator = <T, V>(
};
/**
* Consumes `statesContext` and narrows it to the `HassEntity` for the entity
* Consumes `statesContext` and narrows it to the `HassEntityState` for the entity
* ID found at `entityIdPath` on the host (e.g. `["_config", "entity"]`).
*
* The first path segment is watched on the host — changes to it re-run the
@@ -88,7 +91,7 @@ const composeDecorator = <T, V>(
* nullish values.
*/
export const consumeEntityState = (config: ConsumeEntryConfig) =>
composeDecorator<HassEntities, HassEntity>(
composeDecorator<HassEntityStates, HassEntityState>(
statesContext,
config.entityIdPath[0],
function (states) {
@@ -106,10 +109,10 @@ export const consumeEntityState = (config: ConsumeEntryConfig) =>
*/
export const consumeEntityStates = (config: ConsumeEntryConfig) => {
const watchKey = config.entityIdPath[0];
const buildRecord = function (this: unknown, states: HassEntities) {
const buildRecord = function (this: unknown, states: HassEntityStates) {
const ids = ensureArray(resolveAtPath(this, config.entityIdPath));
if (!ids || !states) return undefined;
const result: Record<string, HassEntity> = {};
const result: Record<string, HassEntityState> = {};
for (const id of ids) {
if (typeof id !== "string") continue;
const state = states[id];
@@ -121,22 +124,22 @@ export const consumeEntityStates = (config: ConsumeEntryConfig) => {
return (proto: unknown, propertyKey: string) => {
const key = String(propertyKey);
const transformDec = transform<
HassEntities,
Record<string, HassEntity> | undefined
HassEntityStates,
Record<string, HassEntityState> | undefined
>({
transformer: function (this: unknown, states: HassEntities) {
transformer: function (this: unknown, states: HassEntityStates) {
const next = buildRecord.call(this, states);
if (next === undefined) {
return undefined;
}
const previous = (this as Record<string, unknown>)[
`__transform_${key}`
] as Record<string, HassEntity> | undefined;
] as Record<string, HassEntityState> | undefined;
return preserveUnchangedEntityStatesRecord(previous, next);
},
watch: watchKey ? [watchKey] : [],
});
const consumeDec = subscribeContext<HassEntities>(statesContext);
const consumeDec = subscribeContext<HassEntityStates>(statesContext);
transformDec(proto as never, propertyKey);
consumeDec(proto as never, propertyKey);
};
@@ -166,5 +169,5 @@ export const consumeLocalize = () =>
composeDecorator<HomeAssistantInternationalization, LocalizeFunc>(
internationalizationContext,
undefined,
({ localize }) => localize
(i18n) => i18n?.localize
);
+12
View File
@@ -0,0 +1,12 @@
import { getShadowRootHost } from "./get-shadow-root-host";
/** The element and its ancestors, crossing shadow root boundaries. */
export const composedAncestors = (element: Element | null): Element[] => {
const ancestors: Element[] = [];
let current = element;
while (current) {
ancestors.push(current);
current = current.parentElement ?? getShadowRootHost(current);
}
return ancestors;
};
+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],
};
};
+7 -1
View File
@@ -1,7 +1,13 @@
/** Loads an image, resolves with undefined when it can't be loaded. */
export const loadImage = (url: string): Promise<HTMLImageElement | undefined> =>
export const loadImage = (
url: string,
crossOrigin?: "anonymous" | "use-credentials"
): Promise<HTMLImageElement | undefined> =>
new Promise((resolve) => {
const image = new Image();
if (crossOrigin) {
image.crossOrigin = crossOrigin;
}
image.onload = () => resolve(image);
image.onerror = () => resolve(undefined);
image.src = url;
-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],
+3 -3
View File
@@ -1,4 +1,4 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } from "home-assistant-js-websocket";
import { computeCssColor } from "../color/compute-color";
import { computeDomain } from "./compute_domain";
import { stateColorCss } from "./state_color";
@@ -23,11 +23,11 @@ export const computeAlertActiveStates = (entityId: string): string[] => {
}
};
export const isAlertActive = (stateObj: HassEntity): boolean =>
export const isAlertActive = (stateObj: HassEntityState): boolean =>
computeAlertActiveStates(stateObj.entity_id).includes(stateObj.state);
export const computeAlertColor = (
stateObj: HassEntity,
stateObj: HassEntityState,
color: string
): string | undefined => {
if (color === "none") {
+2 -2
View File
@@ -1,7 +1,7 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } from "home-assistant-js-websocket";
export const attributeClassNames = (
stateObj: HassEntity,
stateObj: HassEntityState,
attributes: string[]
): string => {
if (!stateObj) {
+2 -2
View File
@@ -12,7 +12,7 @@ import {
mdiBatteryAlertVariantOutline,
mdiBatteryUnknown,
} from "@mdi/js";
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } from "home-assistant-js-websocket";
const BATTERY_ICONS = {
10: "mdi:battery-10",
@@ -51,7 +51,7 @@ const BATTERY_CHARGING_ICONS = {
100: "mdi:battery-charging",
};
export const batteryIcon = (stateObj: HassEntity, state?: string) => {
export const batteryIcon = (stateObj: HassEntityState, state?: string) => {
const level = state ?? stateObj.state;
return batteryLevelIcon(level);
};
+4 -4
View File
@@ -1,6 +1,6 @@
import type {
HassEntities,
HassEntity,
HassEntityStates,
HassEntityState,
HassServices,
} from "home-assistant-js-websocket";
import { canToggleDomain } from "./can_toggle_domain";
@@ -9,9 +9,9 @@ import { supportsFeature } from "./supports-feature";
import { SPECIAL_TOGGLE_ACTIONS } from "./get_toggle_action";
export const canToggleState = (
states: HassEntities,
states: HassEntityStates,
services: HassServices,
stateObj: HassEntity
stateObj: HassEntityState
) => {
const domain = computeStateDomain(stateObj);
@@ -1,4 +1,4 @@
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import type { HassConfig, HassEntityState } from "home-assistant-js-websocket";
import {
DOMAIN_ATTRIBUTES_FORMATERS,
DOMAIN_ATTRIBUTES_UNITS,
@@ -25,7 +25,7 @@ import { computeStateDomain } from "./compute_state_domain";
export const computeAttributeValueDisplay = (
localize: LocalizeFunc,
stateObj: HassEntity,
stateObj: HassEntityState,
locale: FrontendLocaleData,
config: HassConfig,
entities: HomeAssistant["entities"],
@@ -47,7 +47,7 @@ export const computeAttributeValueDisplay = (
export const computeAttributeValueToParts = (
localize: LocalizeFunc,
stateObj: HassEntity,
stateObj: HassEntityState,
locale: FrontendLocaleData,
config: HassConfig,
entities: HomeAssistant["entities"],
@@ -205,7 +205,7 @@ export const computeAttributeValueToParts = (
// effects of a light group, so use the translation of a member.
const computeMemberAttributeValueDisplay = (
localize: LocalizeFunc,
stateObj: HassEntity,
stateObj: HassEntityState,
entities: HomeAssistant["entities"],
attribute: string,
attributeValue: string
@@ -224,7 +224,7 @@ const computeMemberAttributeValueDisplay = (
export const computeAttributeNameDisplay = (
localize: LocalizeFunc,
stateObj: HassEntity,
stateObj: HassEntityState,
entities: HomeAssistant["entities"],
attribute: string
): string => {
@@ -1,4 +1,4 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } from "home-assistant-js-websocket";
import type {
EntityRegistryDisplayEntry,
EntityRegistryEntry,
@@ -56,7 +56,7 @@ const computeTextOnlyName = (
* while the real formatter is still loading.
*/
export const computeEntityNameDisplayWithoutContext = (
stateObj: HassEntity,
stateObj: HassEntityState,
name?: string | EntityNameItem | EntityNameItem[],
options?: EntityNameOptions
): string => {
@@ -125,7 +125,7 @@ export const computeEntityEntryNameParts = (
};
export const computeEntityNameParts = (
stateObj: HassEntity,
stateObj: HassEntityState,
registries: HomeAssistantRegistries,
options?: EntityNamePartsOptions
): EntityNameParts => {
@@ -139,7 +139,7 @@ export const computeEntityNameParts = (
};
export const computeDefaultEntityNameItems = (
stateObj: HassEntity,
stateObj: HassEntityState,
registries: HomeAssistantRegistries
): EntityNameItem[] => {
const parts = computeEntityNameParts(stateObj, registries);
@@ -147,7 +147,7 @@ export const computeDefaultEntityNameItems = (
};
export const computeEntityNameDisplay = (
stateObj: HassEntity,
stateObj: HassEntityState,
name: string | EntityNameItem | EntityNameItem[] | undefined,
registries: HomeAssistantRegistries,
options?: EntityNameOptions
@@ -194,7 +194,7 @@ export const computeEntityNameDisplay = (
};
export const computeEntitySearchLabels = (
stateObj: HassEntity,
stateObj: HassEntityState,
registries: HomeAssistantRegistries
) => {
const parts = computeEntityNameParts(stateObj, registries, {
@@ -221,7 +221,7 @@ export interface EntityPickerDisplayOptions extends HomeAssistantRegistries {
export const computeEntityPickerDisplay = (
options: EntityPickerDisplayOptions,
stateObj: HassEntity
stateObj: HassEntityState
): EntityPickerDisplay => {
const parts = computeEntityNameParts(stateObj, options);
@@ -1,6 +1,6 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } from "home-assistant-js-websocket";
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import type { HomeAssistant } from "../../types";
import type { HomeAssistantFormatters } from "../../types";
import { unitFromParts } from "./value_parts";
interface EntityUnitStubConfig {
@@ -12,14 +12,14 @@ interface EntityUnitStubConfig {
/**
* Computes the display unit for an entity.
*
* @param hass - Home Assistant instance
* @param formatters - Entity formatters
* @param stateObj - Entity state object
* @param config - Element configuration
* @returns Computed entity unit
*/
export const computeEntityUnitDisplay = (
hass: HomeAssistant,
stateObj: HassEntity | undefined,
formatters: HomeAssistantFormatters,
stateObj: HassEntityState | undefined,
config: EntityUnitStubConfig
): string => {
if (
@@ -38,8 +38,8 @@ export const computeEntityUnitDisplay = (
// otherwise derive from the entity's state or attribute
const parts = config.attribute
? hass.formatEntityAttributeValueToParts(stateObj, config.attribute)
: hass.formatEntityStateToParts(stateObj);
? formatters.formatEntityAttributeValueToParts(stateObj, config.attribute)
: formatters.formatEntityStateToParts(stateObj);
return unitFromParts(parts);
};
+17 -13
View File
@@ -1,10 +1,11 @@
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { parseISO } from "date-fns";
import type { HassConfig, HassEntityState } from "home-assistant-js-websocket";
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
import type { FrontendLocaleData } from "../../data/translation";
import { TimeZone } from "../../data/translation";
import type { HomeAssistant, ValuePart } from "../../types";
import { formatDate } from "../datetime/format_date";
import { formatDateNumeric } from "../datetime/format_date";
import { formatDateTime } from "../datetime/format_date_time";
import { DURATION_UNITS, formatDuration } from "../datetime/format_duration";
import { formatTime } from "../datetime/format_time";
@@ -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";
@@ -42,7 +44,7 @@ const NUMERICAL_DOMAINS = ["counter", "input_number", "number"];
export const computeStateDisplay = (
localize: LocalizeFunc,
stateObj: HassEntity,
stateObj: HassEntityState,
locale: FrontendLocaleData,
config: HassConfig,
entities: HomeAssistant["entities"],
@@ -144,7 +146,7 @@ const computeStateToPartsFromEntityAttributes = (
minimumFractionDigits: 2,
// Override monetary options with number format
...getNumberFormatOptions(
{ state, attributes } as HassEntity,
{ state, attributes } as HassEntityState,
entity
),
});
@@ -175,7 +177,7 @@ const computeStateToPartsFromEntityAttributes = (
const value = formatNumber(
state,
locale,
getNumberFormatOptions({ state, attributes } as HassEntity, entity)
getNumberFormatOptions({ state, attributes } as HassEntityState, entity)
);
const unit =
@@ -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
value: formatDateNumeric(
parseISO(`${state}T00:00:00Z`),
{ ...locale, time_zone: TimeZone.server },
{ ...config, time_zone: "UTC" }
),
},
];
@@ -294,7 +298,7 @@ const computeStateToPartsFromEntityAttributes = (
export const computeStateToParts = (
localize: LocalizeFunc,
stateObj: HassEntity,
stateObj: HassEntityState,
locale: FrontendLocaleData,
config: HassConfig,
entities: HomeAssistant["entities"],
+2 -2
View File
@@ -1,5 +1,5 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } from "home-assistant-js-websocket";
import { computeDomain } from "./compute_domain";
export const computeStateDomain = (stateObj: HassEntity) =>
export const computeStateDomain = (stateObj: HassEntityState) =>
computeDomain(stateObj.entity_id);
+2 -2
View File
@@ -1,4 +1,4 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } from "home-assistant-js-websocket";
import { computeObjectId } from "./compute_object_id";
export const computeStateNameFromEntityAttributes = (
@@ -9,5 +9,5 @@ export const computeStateNameFromEntityAttributes = (
? computeObjectId(entityId).replace(/_/g, " ")
: (attributes.friendly_name ?? "").toString();
export const computeStateName = (stateObj: HassEntity): string =>
export const computeStateName = (stateObj: HassEntityState): string =>
computeStateNameFromEntityAttributes(stateObj.entity_id, stateObj.attributes);
@@ -1,4 +1,4 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } from "home-assistant-js-websocket";
import type { AreaRegistryEntry } from "../../../data/area/area_registry";
import type { DeviceRegistryEntry } from "../../../data/device/device_registry";
import type {
@@ -19,7 +19,7 @@ interface EntityContext {
}
export const getEntityContext = (
stateObj: HassEntity,
stateObj: HassEntityState,
entities: HomeAssistant["entities"],
devices: HomeAssistant["devices"],
areas: HomeAssistant["areas"],
+3 -3
View File
@@ -9,9 +9,9 @@ import {
mdiGate,
mdiGateOpen,
} from "@mdi/js";
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } from "home-assistant-js-websocket";
export const computeOpenIcon = (stateObj: HassEntity): string => {
export const computeOpenIcon = (stateObj: HassEntityState): string => {
switch (stateObj.attributes.device_class) {
case "door":
return mdiDoorOpen;
@@ -26,7 +26,7 @@ export const computeOpenIcon = (stateObj: HassEntity): string => {
}
};
export const computeCloseIcon = (stateObj: HassEntity): string => {
export const computeCloseIcon = (stateObj: HassEntityState): string => {
switch (stateObj.attributes.device_class) {
case "door":
return mdiDoorClosed;
+5 -2
View File
@@ -1,6 +1,9 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } from "home-assistant-js-websocket";
export const deviceTrackerIcon = (stateObj: HassEntity, state?: string) => {
export const deviceTrackerIcon = (
stateObj: HassEntityState,
state?: string
) => {
const compareState = state ?? stateObj.state;
if (stateObj?.attributes.source_type === "router") {
return compareState === "home" ? "mdi:lan-connect" : "mdi:lan-disconnect";
+67 -2
View File
@@ -1,8 +1,10 @@
import type { HassEntity } from "home-assistant-js-websocket";
import type { HassEntityState } 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";
@@ -66,7 +68,7 @@ export const generateEntityFilter = (
: undefined;
return (entityId: string) => {
const stateObj = states[entityId] as HassEntity | undefined;
const stateObj = states[entityId] as HassEntityState | undefined;
if (!stateObj) {
return false;
}
@@ -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;
}
);
};
+2 -2
View File
@@ -1,9 +1,9 @@
import type { HassEntities } from "home-assistant-js-websocket";
import type { HassEntityStates } from "home-assistant-js-websocket";
import type { GroupEntity } from "../../data/group";
import { DEFAULT_VIEW_ENTITY_ID } from "../const";
// Return an ordered array of available views
export const extractViews = (entities: HassEntities): GroupEntity[] => {
export const extractViews = (entities: HassEntityStates): GroupEntity[] => {
const views: GroupEntity[] = [];
Object.keys(entities).forEach((entityId) => {
+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;
};
+8 -5
View File
@@ -1,4 +1,7 @@
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
import type {
HassEntityStates,
HassEntityState,
} from "home-assistant-js-websocket";
import { computeStateDomain } from "./compute_state_domain";
export interface EntityLocation {
@@ -9,8 +12,8 @@ export interface EntityLocation {
export const findFirstActiveZone = (
inZones: readonly string[],
states: HassEntities
): HassEntity | undefined => {
states: HassEntityStates
): HassEntityState | undefined => {
for (const zoneId of inZones) {
const zone = states[zoneId];
if (
@@ -26,8 +29,8 @@ export const findFirstActiveZone = (
};
export const getEntityLocation = (
stateObj: HassEntity,
states: HassEntities
stateObj: HassEntityState,
states: HassEntityStates
): EntityLocation | undefined => {
const {
latitude,
+2 -2
View File
@@ -1,8 +1,8 @@
import type { HassEntities } from "home-assistant-js-websocket";
import type { HassEntityStates } from "home-assistant-js-websocket";
import type { GroupEntity } from "../../data/group";
export const getGroupEntities = (
entities: HassEntities,
entities: HassEntityStates,
group: GroupEntity
) => {
const result = {};
Loaded 100 of 925 files, more files were not shown because too many files have changed in this diff. Show more